# ============================================================================
#  StockFolio  -  Stockholm-exchange portfolio tracker
#  Created by  Lars "Issu" Olsson
# ============================================================================
#  ALL TEXT IN THIS PROGRAM IS ALWAYS IN ENGLISH - NEVER SWEDISH!
# ============================================================================
#
#  # ToDo / WHAT THIS PROGRAM DOES
#  ------------------------------------------------------------------------
#  * Track a stock portfolio with MANUAL entry of buy/sell transactions
#    (date, shares, price, brokerage, account, notes).
#  * Fetch LIVE prices from Yahoo Finance (free, no key) for Stockholm
#    tickers using the ".ST" suffix  (e.g.  SWED-A.ST , VOLV-B.ST).
#  * Maintain a DIVIDEND calendar: enter dividend events (date + amount per
#    share); the program computes totals, the next payout, yearly income,
#    yield, and WARNS when a dividend date is approaching.
#  * A WHAT-IF calculator: pick a holding, type a change in kronor OR
#    percent and instantly see the equivalent in the other unit and what it
#    means for the position value and the whole portfolio.
#  * Remembers everything between sessions (data + window size + settings).
#  * Crash catcher + diagnostics log.
#
#  Data source endpoint (stable, no login):
#     https://query1.finance.yahoo.com/v8/finance/chart/<TICKER>.ST
#
#  All helper/data files live UNDER the program folder in /Helpfiles, so it
#  keeps working even as a moved .EXE.  Logs go to /Helpfiles/0---Empty.
#
#  # ToDo / CHANGE LOG
#  ------------------------------------------------------------------------
#  2026-11-24  NEW (1.7): PHONE SYNC with the Android app "Issu's StockFolio".  File > "Phone sync (Issu's StockFolio app)...":
#     Use relay.json, Copy phone code, paste it in the app, done.  The open portfolio (transactions, dividends, companies, accounts,
#     price history, warning days) is kept equal on both sides through a relay server of your own; every record is ENCRYPTED here with
#     a secret that only lives on this PC and in the phone code, so the server cannot read anything.  Newest change of a row wins;
#     a row deleted on one side is deleted on the other.  The code is in the NEW file StockFolio_sync.py (copy it next to this file);
#     this file only got a menu item, a timer, a hook in Portfolio.save() and three small App methods (DEL 22 markers).
#     Without StockFolio_sync.py the program works as before.
#  2026-11-24  NEW (1.6): Account SECTION.  Manage accounts has a new Section column
#     (= the real broker account the shares sit in, e.g. Lars's and Benjamin's
#     shares both sit in 'Olga Avanza') and a '+ New account' button (prepare
#     Benjamin's own Avanza before any CSV exists).  Per account groups accounts
#     with the same section under one heading but keeps owners apart; accounts
#     prepared without trades show as '(no trades yet)'.  Owner = whose shares.
#  2026-11-24  NEW (1.6): "Check against broker..." (By account tab): type in or
#     paste the broker's own holdings (shares + GAV, parse_holdings_paste) and
#     _reconcile() says what is missing: shares fewer = unrecorded SALE (price
#     must be looked up), more = unrecorded PURCHASE (average price worked out
#     from the broker's total cost), same shares + other GAV = the difference.
#     "Add missing sale/purchase" writes a "pasted (reconcile)" row; the broker's
#     numbers are saved in the portfolio file (broker_checks) and shown as a
#     tick / warning per company in By account.
#  2026-11-24  NEW (1.6): By account has a second view, "Per broker (all
#     owners)": everything at Avanza / Nordnet in one list sorted per company,
#     owner in brackets; checkbox "Owners as headings" (default off) groups it
#     under each owner instead.
#  2026-11-24  NEW (1.6): "By account" tab next to "By person": one block per
#     broker account (owner filter), holdings with value/result, last trade
#     date and a "Check" column (no brokerage / not from a statement / pasted),
#     double-click opens the buys-sells-dividends popup.  A check aid: compare
#     with the broker's own holdings list to spot trades the CSV missed.
#  2026-11-24  NEW (1.6): "Paste orders..." in the Import CSV window.  Finished
#     orders copied from Nordnet's order view (no API, no login) become BUY /
#     SELL rows for a trade the statement does not list yet: parse_order_paste(),
#     _match_ticker_by_name() (company names compared as word sets, SELL only
#     among what the account holds).  Stored as note "pasted ..." with no
#     brokerage; when the real statement rows arrive they REPLACE the pasted
#     ones (_placeholders_replaced_by), so a sale is never counted twice.
#  2026-11-24  NEW (1.6): Import CSV now also finds statements in the user's
#     Downloads folder and in StockFolio's own Helpfiles folder (besides the
#     program folder), but only .csv files whose header is a Nordnet/Avanza
#     statement - see find_statement_csvs().  "Look again" button rescans.
#  2026-11-24  NEW (1.6): "Buys, sells & dividends" popup (_show_trade_detail):
#     one chronological list of every purchase, sale and received dividend of a
#     company, with the shares held after each event, the realised result of
#     each sale and a summary (bought / sold / dividends / realised /
#     unrealised / result so far).  Opened by double-clicking a row in
#     "Sold / realized" (that sale's account), by right-click on a holding in
#     the Portfolio tab, and by the new button in the company info window.
#     The drop-down in the popup switches account or shows all of them.
#  2026-11-24  NEW (1.6): "Overview" button (after Import CSV; also Tools menu).
#     A quick total value of the accounts YOU tick: tick boxes per account,
#     the choice is kept in settings ("overview_accounts").  First time, it
#     ticks Lars' accounts except the ones with code ON / OA.  Shows broker ->
#     account -> value, invested, price +/-, and a grand total.  Stays open and
#     updates itself after Refresh prices / import / edits.
#  2026-11-24  NEW (1.6): Import CSV fills in MISSING brokerage.  A trade that
#     is already stored (same account/date/ISIN/shares/price) but has NO
#     brokerage used to be skipped as a duplicate for good, so a fee the broker
#     booked later never arrived.  Now the newer statement's brokerage is
#     written into the existing row (preview status "fill").  A row that
#     already HAS a brokerage is never changed.
#  2026-10-06  NEW (1.5): "By person" tab > checkbox "Assume calendar dividends
#     were paid".  Imported statements are the only PROOF of a payout, so a
#     payout the calendar knows about but no statement has been imported for
#     (e.g. Corem's June/September 2026) showed as nothing.  With the box
#     ticked the tab ALSO counts, per held position, every calendar event
#     from the first purchase up to today as per-share x the quantity held that
#     day (i.e. "no unrecorded buys or sells").  Holes in a series with an
#     explicit frequency are filled too.  Recorded payouts are untouched and
#     an event within 10 days of a recorded payout on the same account is
#     taken to be that payout.  Rows/totals that include assumed money carry
#     a "~".  Nothing is written to the portfolio file.  See assumed_dividends().
#  2026-08-31  FIXED (1.4): "Include sold" threw away most of a person's
#     closed positions in the DEFAULT merged view.  The check for "this is
#     still partly held, skip it" keyed on the ticker ALONE while the
#     accounts are merged - so a closed position was dropped whenever the
#     same ticker was still owned on another account, INCLUDING ANOTHER
#     PERSON'S account.  Real cost on the live portfolio: Lars' net went
#     43 229 kr instead of 82 904 kr, hiding 94 693 kr of dividends (one
#     COLLAX position alone was worth 73 307 kr) because somebody else still
#     owned the same stocks.  The key now carries the owner, and a closed
#     account of a ticker the SAME owner still holds elsewhere is folded
#     into that held row (realized P/L + dividends) instead of vanishing.
#     Merged and "Separate by account" now give identical totals - they are
#     the same money either way, which is exactly how this was caught.
#  2026-08-31  Ticking "Include sold (closed positions)" now also ticks
#     "Include dividends from sold stocks".  A closed position is its
#     realized loss AND everything it paid out while it was open; showing
#     only the loss half was the misleading default, not the cautious one.
#     Untick it afterwards if you want the price movement alone.
#  2026-08-29  FIXED: importing holdings from the Google Sheet created
#     DUPLICATE positions.  The sheet import appended every row without any
#     duplicate check at all, while the sheet is just a summary of the same
#     trades the broker CSV already delivered - only under the sheet's own
#     account names ("N-Lars") instead of the broker's ("64352081"), so
#     nothing looked equal.  The preview now classifies every row
#     (DUP / LIKELY / OWNED / NEW, see _sheet_dup_check), ticks ONLY the
#     genuinely new ones, imports nothing that is not ticked, and asks again
#     if a ticked row already looks stored.
#  2026-08-29  Broker CSVs no longer have to be kept next to the program.
#     A statement is input only - everything it carries ends up in the
#     portfolio file and it is never read again - so the import now MOVES the
#     files it used into Helpfiles/StockFolio/imported/ (dated, never
#     deleted) and logs them in import_log.txt.  Checkbox in the import
#     dialog, remembered as settings.archive_imported_csv.
#  2026-08-29  The mark in both the duplicate finder and the sheet-import
#     preview reads keep/DELETE and IMPORT/skip in words, in a wide column,
#     and CLICKING ANYWHERE ON THE ROW toggles it.  The old 46-pixel "[ ]"
#     in a narrow column was simply not findable.
#  2026-08-29  NEW: Tools > "Find duplicates..." - scans the portfolio for
#     the same trade stored twice (accounts ignored, because that is exactly
#     what differs), suggests keeping the broker copy, and deletes the extra
#     copies after writing a backup.  Also flags rows with NO account.
#  2026-08-08  FIXED: dividends were SILENTLY LOST on CSV import.
#     The duplicate check for a received dividend used only
#     (ticker, date, per share).  Every account that owns the same stock is
#     paid on the SAME date at the SAME amount per share, so the second and
#     third account always looked like a duplicate of the first and was
#     dropped without a word.  The key now also contains the ACCOUNT and the
#     SHARE COUNT (see _div_signature), and the raw statement depot-id is
#     normalised against the account map so re-importing never duplicates.
#     -> Re-run "Import CSV" on your statements to recover lost payouts.
#  2026-08-08  The import preview now marks dividend rows NEW / dup like it
#     already did for buy/sell, and counts both - the loss above was
#     invisible because every dividend row was simply labelled "DIV".
#  2026-08-08  Dividend calendar: new "Account" column.  A payout already
#     received shows the account, share count and amount from the statement
#     instead of guessing from the total shares held today.
#  2026-08-08  Forecast rows from the "Bolag" tab are no longer created on a
#     day where real money was already received for that company.
# ============================================================================


# ============================================================================
#  DEL 01 .... IMPORTS
# ============================================================================
import os
import sys
import glob
import re
import json
import time
import shutil
import subprocess
import platform
import collections
import traceback
import threading
import datetime as _dt
import urllib.request
import urllib.parse
import webbrowser

import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import os
import sys

# Phone sync with the Android app "Issu's StockFolio" (DEL 22).  The code is in StockFolio_sync.py (same folder as this file); without it
# everything below still works, only the File > Phone sync item then says the file is missing.
try:
    import StockFolio_sync as PHONE
except Exception:
    PHONE = None


# ---- 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 .... APP IDENTITY  (AppUserModelID must run BEFORE tk.Tk())
# ============================================================================
APP_NAME    = "StockFolio"
APP_VERSION = "1.7"

if platform.system() == "Windows":
    try:
        import ctypes
        ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(
            "IssuSoft.StockFolio.1")
    except Exception:
        pass


# ============================================================================
#  DEL 03 .... COLORS  (button colors written out plainly - easy to change)
# ============================================================================
# ---- Theme palette ----
C_BG      = "#0f2034"   # main background (deep navy)
C_BG2     = "#16263f"   # panels
C_BG3     = "#1b2e49"   # dialogs
C_PANEL   = "#252535"   # donation panel
C_SEP     = "#2b496e"   # separators / grid lines
C_FG      = "#e8eef6"   # main text
C_FG_DIM  = "#9fb3c9"   # dim text
C_ACCENT  = "#7be896"   # bright green accent
C_GOOD    = "#5ec880"   # gains  (green)
C_BAD     = "#e05a5a"   # losses (red)
C_WARN    = "#f0c040"   # warning (amber)
C_HEAD    = "#6cb4ff"   # block headings in By account (blue, so they differ from green gains)

# ---- Button colors (change these names freely: red / blue / green / grey ...) ----
BTN_ADD       = "white"
BTN_EDIT      = "white"
BTN_DELETE    = "white"
BTN_REFRESH   = "white"
BTN_DIVIDEND  = "white"
BTN_WHATIF    = "white"
BTN_HELP      = "white"
BTN_ABOUT     = "white"
BTN_DIALOG_OK     = "white"
BTN_DIALOG_CANCEL = "white"

FONT      = ("Segoe UI", 10)
FONT_B    = ("Segoe UI", 10, "bold")
FONT_MONO = ("Consolas", 10)

# Subtle per-person background shades (cycled in the "By person" view)
PERSON_SHADES = ["#1b2e49", "#1d3340", "#272543", "#19303a",
                 "#2e2838", "#203a44", "#33304a", "#1a3530"]


# ============================================================================
#  DEL 04 .... PATHS & DIRECTORIES  (always relative to the program)
# ============================================================================
def _base_dir():
    """Folder of the script / frozen EXE - the anchor for everything."""
    if getattr(sys, "frozen", False):
        return _program_home()
    return _program_home()


BASE_DIR    = _base_dir()
HELP_DIR    = os.path.join(BASE_DIR, "Helpfiles", APP_NAME)
LOG_DIR     = os.path.join(BASE_DIR, "Helpfiles", "0---Empty")
DATA_FILE   = os.path.join(HELP_DIR, "portfolio.json")
SETT_FILE   = os.path.join(HELP_DIR, "settings.json")
HIST_FILE   = os.path.join(HELP_DIR, "price_history.json")

for _d in (HELP_DIR, LOG_DIR):
    try:
        os.makedirs(_d, exist_ok=True)
    except Exception:
        pass


# ============================================================================
#  DEL 05 .... LOGGING & CRASH CATCHER / DIAGNOSTICS
# ============================================================================
LOG_FILE = os.path.join(LOG_DIR, f"{APP_NAME}.log")


def log(msg):
    """Append a timestamped line to the diagnostics log (never raises)."""
    try:
        stamp = _dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        with open(LOG_FILE, "a", encoding="utf-8") as f:
            f.write(f"[{stamp}] {msg}\n")
    except Exception:
        pass


def _crash(exc_type, exc_value, exc_tb):
    """Global crash catcher: log full traceback and show a dialog."""
    text = "".join(traceback.format_exception(exc_type, exc_value, exc_tb))
    log("UNCAUGHT EXCEPTION:\n" + text)
    try:
        crash_path = os.path.join(LOG_DIR, f"{APP_NAME}_crash.log")
        with open(crash_path, "a", encoding="utf-8") as f:
            f.write(_dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + "\n")
            f.write(text + "\n" + "-" * 60 + "\n")
    except Exception:
        pass
    try:
        messagebox.showerror(
            f"{APP_NAME} - unexpected error",
            "An unexpected error occurred and was logged to:\n"
            f"{LOG_DIR}\n\n{exc_type.__name__}: {exc_value}")
    except Exception:
        pass


sys.excepthook = _crash


# ============================================================================
#  DEL 06 .... UI HELPERS  (NO BLINKING CURSORS anywhere)
# ============================================================================
def no_blink(w):
    """Force a SOLID (non-blinking) caret on any Entry/Text widget."""
    try:
        w.configure(insertofftime=0, insertontime=9999999)
    except Exception:
        pass
    return w


def mk_entry(parent, **kw):
    """tk.Entry (never ttk) with a solid caret."""
    e = tk.Entry(parent, insertofftime=0, insertontime=9999999, **kw)
    assert e.cget("insertofftime") == 0
    return e


def mk_text(parent, **kw):
    """tk.Text (never ttk) with a solid caret."""
    t = tk.Text(parent, insertofftime=0, insertontime=9999999, **kw)
    return t


def init_dialog(top, root):
    """Standard Toplevel setup: grab_set(), focus_force(), <Escape> (in order)."""
    top.transient(root)
    top.grab_set()
    top.focus_force()
    top.bind("<Escape>", lambda e: top.destroy())


def flash_ok(root, message, ms=1000):
    """A success popup that auto-closes after ~1 second."""
    top = tk.Toplevel(root)
    top.overrideredirect(True)
    top.configure(bg=C_ACCENT)
    top.attributes("-topmost", True)
    lbl = tk.Label(top, text="  " + message + "  ", bg=C_ACCENT, fg="#0c1a2a",
                   font=("Segoe UI", 11, "bold"), padx=14, pady=10)
    lbl.pack()
    top.update_idletasks()
    rx, ry = root.winfo_rootx(), root.winfo_rooty()
    rw, rh = root.winfo_width(), root.winfo_height()
    w, h = top.winfo_width(), top.winfo_height()
    top.geometry(f"+{rx + (rw - w)//2}+{ry + (rh - h)//3}")
    top.after(ms, top.destroy)


def bind_mousewheel(widget, target=None):
    """Mouse-wheel scrolling for a scrollable widget."""
    target = target or widget

    def _on(e):
        delta = -1 * int(e.delta / 120) if e.delta else 0
        try:
            target.yview_scroll(delta, "units")
        except Exception:
            pass
    widget.bind("<MouseWheel>", _on)


def today_str():
    return _dt.date.today().isoformat()


def parse_date(s):
    """Return a date from 'YYYY-MM-DD' or None."""
    try:
        return _dt.date.fromisoformat(s.strip())
    except Exception:
        return None


def fnum(v, dec=2):
    """Format a number with thousands spaces, or '-' if None."""
    if v is None:
        return "-"
    try:
        s = f"{float(v):,.{dec}f}".replace(",", " ")
        return s
    except Exception:
        return str(v)


# ---- share class -----------------------------------------------------------
# Yahoo hands back one name for every class of a company: SHB-A.ST and SHB-B.ST
# are both "Svenska Handelsbanken AB (publ)".  Two rows with the same name are
# easy to mix up, so the class is read off the TICKER and shown in brackets.
#
# Only these are share classes.  A ticker's last segment is just as often a
# country or an instrument type - NDA-SE / NDA-FI (Nordea in Stockholm and in
# Helsinki) and ARION-SDB (a depositary receipt) are NOT classes, and guessing
# from "it has a dash" would label all three wrongly.
SHARE_CLASSES = {"A": "A", "B": "B", "C": "C", "D": "D", "PREF": "Pref"}

# Brackets, not round ones: nearly every Swedish name already ends in "(publ)",
# and "Handelsbanken AB (publ) (B)" reads like a typo.  Change this one line to
# ("(", ")") if you want them round anyway.
CLASS_BRACKETS = ("[", "]")


def share_class(ticker):
    """'BETS-B.ST' -> 'B',  'ALM-PREF.ST' -> 'Pref',  'NDA-SE.ST' -> ''."""
    if not ticker:
        return ""
    base = str(ticker).split(".")[0]          # drop the exchange suffix
    seg = [p for p in base.split("-") if p]
    if len(seg) < 2:
        return ""
    last = seg[-1].upper()
    # "...-PREF-B": a class of a preference share, e.g. Pref B
    if len(seg) >= 3 and seg[-2].upper() == "PREF" and last in ("A", "B", "C", "D"):
        return f"Pref {last}"
    return SHARE_CLASSES.get(last, "")


def with_share_class(name, ticker):
    """'Betsson AB (publ)' + 'BETS-B.ST' -> 'Betsson AB (publ) [B]'.

    Left alone when the name already carries the class - the imported Nordnet
    and Avanza names say "Betsson B" already, and "Betsson B [B]" helps nobody.
    """
    cls = share_class(ticker)
    if not cls or not name or name == ticker:
        return name
    tail = name.strip().upper()
    if (tail.endswith(" " + cls.upper()) or tail.endswith("[" + cls.upper() + "]")
            or tail.endswith("(" + cls.upper() + ")")):
        return name
    lb, rb = CLASS_BRACKETS
    return f"{name} {lb}{cls}{rb}"


# ============================================================================
#  DEL 07 .... SETTINGS  (window size + preferences, remembered every time)
# ============================================================================
DEFAULT_GSHEET = {
    "url": "",                  # full sheet URL or just the spreadsheet ID
    "gid": "507464238",         # the holdings tab's gid ("Aktier")
    "col_name": "BOLAG",        # company
    "col_code": "KOD",          # exchange code, e.g. STO:SWED-A
    "col_account": "KONTO",
    "col_shares": "ANTAL",
    "col_date": "DATUM",        # YY-MM-DD
    "col_buyprice": "KURS",
    "col_courtage": "Courtage",
    "col_value": "VÄRDE",       # current market value -> price = value/shares
    "col_dividend": "UTDELNING",
    # --- "Bolag" dividend tab (forward dividends) ---
    "div_gid": "403105218",
    "div_col_code": "KOD",
    "div_col_date": "X",        # a date OR a frequency word
    "div_col_pershare": ":-",   # kronor per share
    # --- "Kurser" price-history tab ---
    "hist_gid": "1255905222",
}

DEFAULT_SETTINGS = {
    "geometry": "1320x640",
    "warn_days": 14,            # dividend warning window
    "auto_refresh_on_start": True,
    "prices": {},               # ticker -> {price, currency, name, ts}  (Yahoo)
    "sheet_prices": {},         # ticker -> {price, ts}                  (Google Sheet)
    "gsheet": dict(DEFAULT_GSHEET),
    "price_source": "yahoo",    # which source drives Value / Gain-Loss: yahoo | gsheet
    "accounts": ["OA-Lars", "N-Lars", "A-Lars", "ON-Lars"],
    "account_map": {},          # statement account id -> logical account name
    "account_meta": {},         # account name -> {"owner": ..., "broker": ...}
    "last_portfolio": "",       # path of the most recently used portfolio file
    "archive_imported_csv": True,   # move a statement into Helpfiles/StockFolio/imported/ once read
    "sort_col": "value",
    "sort_desc": True,
}


def load_settings():
    s = dict(DEFAULT_SETTINGS)
    s["gsheet"] = dict(DEFAULT_GSHEET)
    try:
        with open(SETT_FILE, "r", encoding="utf-8") as f:
            loaded = json.load(f)
        gs = loaded.pop("gsheet", None)
        s.update(loaded)
        if isinstance(gs, dict):
            merged = dict(DEFAULT_GSHEET)
            merged.update(gs)
            s["gsheet"] = merged
    except Exception:
        pass
    return s


def save_settings(s):
    try:
        with open(SETT_FILE, "w", encoding="utf-8") as f:
            json.dump(s, f, indent=2)
    except Exception as e:
        log(f"save_settings failed: {e}")


def load_price_history():
    """{ticker: {date: price}} accumulated over time (append-only)."""
    try:
        with open(HIST_FILE, "r", encoding="utf-8") as f:
            return json.load(f)
    except Exception:
        return {}


def save_price_history(hist):
    try:
        with open(HIST_FILE, "w", encoding="utf-8") as f:
            json.dump(hist, f, indent=2)
    except Exception as e:
        log(f"save_price_history failed: {e}")


def merge_price_history(store, new):
    """Merge new {ticker:{date:price}} into store; never delete. Returns new-date count."""
    added = 0
    for t, dmap in new.items():
        s = store.setdefault(t, {})
        for d, p in dmap.items():
            if d not in s:
                added += 1
            s[d] = p           # refresh existing, keep dates not present in sheet
    return added


# ============================================================================
#  DEL 08 .... DATA MODEL  (transactions, dividends, instruments)
# ============================================================================
#  portfolio.json structure:
#  {
#    "transactions": [ {id, ticker, company, account, type, date,
#                       shares, price, courtage, note}, ... ],
#    "dividends":    [ {id, ticker, date, per_share, note}, ... ],
#    "instruments":  { ticker: {company, note} }
#  }
# ----------------------------------------------------------------------------
BACKUP_KEEP = 60        # how many timestamped backups to keep per file


def _backup_dir(path):
    return os.path.join(os.path.dirname(path) or ".", "backups")


def backup_file(path):
    """Copy an existing non-empty file into a timestamped backup; prune old ones."""
    try:
        if not os.path.isfile(path) or os.path.getsize(path) < 5:
            return
        bdir = _backup_dir(path)
        os.makedirs(bdir, exist_ok=True)
        base = os.path.splitext(os.path.basename(path))[0]
        stamp = _dt.datetime.now().strftime("%Y%m%d_%H%M%S_%f")
        dst = os.path.join(bdir, f"{base}_{stamp}.json")
        if not os.path.exists(dst):
            shutil.copy2(path, dst)
        files = sorted(glob.glob(os.path.join(bdir, f"{base}_*.json")))
        for old in files[:-BACKUP_KEEP]:
            try:
                os.remove(old)
            except Exception:
                pass
    except Exception as e:
        log(f"backup_file failed: {e}")


def list_backups(path):
    base = os.path.splitext(os.path.basename(path))[0]
    return sorted(glob.glob(os.path.join(_backup_dir(path), f"{base}_*.json")),
                  reverse=True)


def load_latest_backup(path):
    for b in list_backups(path):
        try:
            with open(b, "r", encoding="utf-8") as f:
                return json.load(f)
        except Exception:
            continue
    return None


class Portfolio:
    def __init__(self, path=None):
        self.path = path or DATA_FILE
        self.transactions = []
        self.dividends = []
        self.instruments = {}
        self.isin_map = {}      # ISIN -> ticker
        # what the broker's own holdings list said, per account and ticker:
        # {account: {ticker: {"shares", "gav", "date"}}} - see "Check against broker"
        self.broker_checks = {}
        self.load()

    # ---- persistence (with automatic backups + atomic writes) ----
    def _apply(self, d):
        self.transactions = d.get("transactions", [])
        self.dividends = d.get("dividends", [])
        self.instruments = d.get("instruments", {})
        self.isin_map = d.get("isin_map", {})
        self.broker_checks = d.get("broker_checks", {})

    def load(self):
        self.transactions, self.dividends = [], []
        self.instruments, self.isin_map = {}, {}
        self.broker_checks = {}
        if not os.path.isfile(self.path):
            return
        try:
            with open(self.path, "r", encoding="utf-8") as f:
                self._apply(json.load(f))
        except Exception as e:
            # file exists but is unreadable/corrupt: recover from newest backup
            log(f"portfolio load failed ({e}); trying backup")
            d = load_latest_backup(self.path)
            if d is not None:
                self._apply(d)
                log("recovered portfolio from backup")

    def save(self):
        try:
            folder = os.path.dirname(self.path)
            if folder:
                os.makedirs(folder, exist_ok=True)
            backup_file(self.path)                       # keep the previous version
            payload = {
                "transactions": self.transactions,
                "dividends": self.dividends,
                "instruments": self.instruments,
                "isin_map": self.isin_map,
                "broker_checks": self.broker_checks,
            }
            tmp = self.path + ".tmp"
            with open(tmp, "w", encoding="utf-8") as f:
                json.dump(payload, f, indent=2)
            os.replace(tmp, self.path)                   # atomic, never half-written
        except Exception as e:
            log(f"portfolio save failed: {e}")
            return
        if PHONE is not None:                            # the phone sync notes WHEN each row changed (cheap, never raises)
            PHONE.after_save(self)

    # ---- ids ----
    def _new_id(self):
        return str(int(time.time() * 1000)) + str(len(self.transactions))

    # ---- tickers in use ----
    def tickers(self):
        seen = []
        for t in self.transactions:
            if t["ticker"] not in seen:
                seen.append(t["ticker"])
        return seen

    def company_for(self, ticker, prices=None):
        name = self._company_name(ticker, prices)
        return with_share_class(name, ticker)

    def _company_name(self, ticker, prices=None):
        if prices and ticker in prices and prices[ticker].get("name"):
            return prices[ticker]["name"]
        inst = self.instruments.get(ticker, {})
        if inst.get("company"):
            return inst["company"]
        for t in self.transactions:
            if t["ticker"] == ticker and t.get("company"):
                return t["company"]
        return ticker

    # ---- aggregation into holdings (ticker + account) ----
    def holdings(self):
        """Return list of holdings dicts using average-cost method."""
        groups = {}
        # chronological order so SELL reduces correct basis
        for t in sorted(self.transactions, key=lambda x: x.get("date", "")):
            key = (t["ticker"], t.get("account", ""))
            g = groups.setdefault(key, {
                "ticker": t["ticker"], "account": t.get("account", ""),
                "qty": 0.0, "cost": 0.0, "realized": 0.0})
            sh = float(t.get("shares", 0))
            pr = float(t.get("price", 0))
            cg = float(t.get("courtage", 0))
            if t.get("type", "BUY") == "BUY":
                g["qty"] += sh
                g["cost"] += sh * pr + cg
            else:  # SELL
                if g["qty"] > 0:
                    avg = g["cost"] / g["qty"]
                    g["realized"] += sh * (pr - avg) - cg
                    g["cost"] -= avg * sh
                g["qty"] -= sh
        result = []
        for (tk_, acc), g in groups.items():
            if round(g["qty"], 6) <= 0:
                continue
            gav = g["cost"] / g["qty"] if g["qty"] else 0.0
            result.append({
                "ticker": tk_, "account": acc,
                "qty": g["qty"], "gav": gav,
                "cost": g["cost"], "realized": g["realized"],
            })
        return result

    # ---- realized sales (closed/partly-closed trades) ----
    def realized_sales(self):
        """One record per SELL with its realized P/L (average-cost method)."""
        groups = {}
        out = []
        for t in sorted(self.transactions, key=lambda x: x.get("date", "")):
            key = (t["ticker"], t.get("account", ""))
            g = groups.setdefault(key, {"qty": 0.0, "cost": 0.0})
            sh = float(t.get("shares", 0))
            pr = float(t.get("price", 0))
            cg = float(t.get("courtage", 0))
            if t.get("type", "BUY") == "BUY":
                g["qty"] += sh
                g["cost"] += sh * pr + cg
            else:
                avg = g["cost"] / g["qty"] if g["qty"] else 0.0
                realized = sh * (pr - avg) - cg
                out.append({
                    "ticker": t["ticker"], "account": t.get("account", ""),
                    "date": t.get("date", ""), "qty": sh, "price": pr,
                    "avg": avg, "courtage": cg, "proceeds": sh * pr - cg,
                    "realized": realized})
                g["cost"] -= avg * sh
                g["qty"] -= sh
        return out

    # ---- dividends ----
    def dividends_for(self, ticker):
        return sorted([d for d in self.dividends if d["ticker"] == ticker],
                      key=lambda x: x.get("date", ""))

    def next_dividend(self, ticker, from_date=None):
        from_date = from_date or _dt.date.today()
        upcoming = []
        for d in self.dividends_for(ticker):
            dd = parse_date(d.get("date", ""))
            if dd and dd >= from_date:
                upcoming.append((dd, d))
        if not upcoming:
            return None
        upcoming.sort(key=lambda x: x[0])
        return upcoming[0][1]

    def annual_dividend_per_share(self, ticker):
        """Sum of dividend events in the coming 12 months, per share."""
        today = _dt.date.today()
        horizon = today + _dt.timedelta(days=365)
        total = 0.0
        for d in self.dividends_for(ticker):
            dd = parse_date(d.get("date", ""))
            if dd and today <= dd < horizon:
                total += float(d.get("per_share", 0))
        return total


# ============================================================================
#  DEL 09 .... YAHOO FINANCE PRICE FETCH  (chart endpoint, no key)
# ============================================================================
def fetch_one(ticker, timeout=12):
    """Return dict(price, currency, name, prev) for one ticker or None."""
    url = ("https://query1.finance.yahoo.com/v8/finance/chart/"
           f"{ticker}?interval=1d&range=5d")
    req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
    with urllib.request.urlopen(req, timeout=timeout) as r:
        data = json.load(r)
    meta = data["chart"]["result"][0]["meta"]
    return {
        "price": meta.get("regularMarketPrice"),
        "currency": meta.get("currency", ""),
        "name": meta.get("longName") or meta.get("shortName") or ticker,
        "prev": meta.get("chartPreviousClose") or meta.get("previousClose"),
        "ts": int(time.time()),
    }


def fetch_many(tickers, on_each=None):
    """Fetch a list of tickers; returns {ticker: info}. on_each(tk, ok)."""
    out = {}
    for tk_ in tickers:
        try:
            out[tk_] = fetch_one(tk_)
            if on_each:
                on_each(tk_, True)
        except Exception as e:
            log(f"fetch failed {tk_}: {e}")
            if on_each:
                on_each(tk_, False)
    return out


# ============================================================================
#  DEL 09B .. GOOGLE SHEET  (one-time import + ongoing price source)
# ============================================================================
#  Live price from the sheet = current value / shares (the GOOGLEFINANCE value
#  column divided by the share count), since the sheet stores current market
#  VALUE rather than a clean per-share price column.
# ----------------------------------------------------------------------------
def to_float(s):
    """Tolerant number parser: handles '1 234,56', '46 968 kr', '226.90', nbsp."""
    if s is None:
        return None
    s = str(s).strip()
    if not s:
        return None
    # keep digits, separators and sign only
    s = s.replace("\xa0", "").replace(" ", "")
    s = s.replace("kr", "").replace("%", "").replace("−", "-")
    keep = "".join(ch for ch in s if ch.isdigit() or ch in ".,-")
    if not keep or keep in ("-", ".", ","):
        return None
    if "," in keep and "." in keep:
        # the rightmost separator is the decimal one
        if keep.rfind(",") > keep.rfind("."):
            keep = keep.replace(".", "").replace(",", ".")
        else:
            keep = keep.replace(",", "")
    elif "," in keep:
        keep = keep.replace(",", ".")
    try:
        return float(keep)
    except ValueError:
        return None


def parse_sheet_date(s):
    """Convert '25-02-28' (YY-MM-DD) or 'YYYY-MM-DD' to an ISO string, or ''."""
    if not s:
        return ""
    s = str(s).strip()
    parts = s.replace("/", "-").split("-")
    if len(parts) == 3:
        y, m, d = parts
        if len(y) == 2:
            y = "20" + y
        try:
            return _dt.date(int(y), int(m), int(d)).isoformat()
        except ValueError:
            return ""
    return ""


FREQ_MONTHS = {
    "månadsvis": 1, "manadsvis": 1, "monthly": 1,
    "kvartalsvis": 3, "quarterly": 3,
    "halvårsvis": 6, "halvarsvis": 6, "semi": 6, "semi-annual": 6,
    "årsvis": 12, "arsvis": 12, "årligen": 12, "arligen": 12,
    "årlig": 12, "annual": 12, "yearly": 12,
}


def recognize_frequency(s):
    """Map a Swedish/English frequency word to a month step, or None."""
    if not s:
        return None
    return FREQ_MONTHS.get(str(s).strip().lower())


def add_months(d, n):
    """Add n months to a date, clamping the day to <=28 for safety."""
    m = d.month - 1 + n
    y = d.year + m // 12
    m = m % 12 + 1
    return _dt.date(y, m, min(d.day, 28))


def code_to_ticker(code):
    """'STO:SWED-A' -> 'SWED-A.ST'.  Bare codes get '.ST' appended."""
    if not code:
        return ""
    code = str(code).strip().upper()
    if ":" in code:
        code = code.split(":", 1)[1]
    if not code:
        return ""
    if "." in code:        # already an exchange-suffixed ticker
        return code
    return code + ".ST"


def gsheet_export_url(url_or_id, gid):
    """Build the CSV-export URL from a full sheet URL or a bare spreadsheet ID."""
    text = (url_or_id or "").strip()
    sid = text
    marker = "/spreadsheets/d/"
    if marker in text:
        sid = text.split(marker, 1)[1].split("/")[0]
    return ("https://docs.google.com/spreadsheets/d/"
            f"{sid}/export?format=csv&gid={gid or '0'}")


def read_gsheet_csv(url_or_id, gid, timeout=25):
    """Return the raw rows (list of list) from the sheet's CSV export."""
    import csv
    import io
    url = gsheet_export_url(url_or_id, gid)
    req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
    raw = urllib.request.urlopen(req, timeout=timeout).read().decode("utf-8", "replace")
    return list(csv.reader(io.StringIO(raw)))


def read_gsheet_rows(url_or_id, gid, timeout=25):
    """Return (headers, list-of-dict-rows) from the sheet's CSV export."""
    rdr = read_gsheet_csv(url_or_id, gid, timeout)
    if not rdr:
        return [], []
    headers = rdr[0]
    rows = []
    for r in rdr[1:]:
        d = {}
        for i, h in enumerate(headers):
            d[h] = r[i] if i < len(r) else ""
        rows.append(d)
    return headers, rows


def parse_kurser_history(rows):
    """Parse the transposed 'Kurser' tab into {ticker: {date: price}}.

    The code row is the one with the most ':' cells (columns C+); every row
    whose column A is a valid date is a data row.  Column positions are not
    assumed fixed, so temp columns and added companies are handled.
    """
    if not rows:
        return {}
    # locate the code row
    code_row_idx, best = None, 0
    for i, r in enumerate(rows[:10]):
        cnt = sum(1 for c in r[2:] if ":" in str(c))
        if cnt > best:
            best, code_row_idx = cnt, i
    if code_row_idx is None:
        return {}
    coderow = rows[code_row_idx]
    col_ticker = {}
    for ci in range(2, len(coderow)):
        code = str(coderow[ci]).strip()
        if code and ":" in code:
            t = code_to_ticker(code)
            if t:
                col_ticker[ci] = t
    hist = {}
    for r in rows:
        if not r:
            continue
        d = parse_sheet_date(r[0])
        if not d:
            continue
        for ci, t in col_ticker.items():
            if ci < len(r):
                p = to_float(r[ci])
                if p is not None and p > 0:
                    hist.setdefault(t, {})[d] = p
    return hist


def history_stats(dmap):
    """Return summary stats for one ticker's {date: price} map."""
    if not dmap:
        return None
    items = sorted(dmap.items())                       # by date
    lo_date, lo = min(dmap.items(), key=lambda x: x[1])
    hi_date, hi = max(dmap.items(), key=lambda x: x[1])
    return {
        "n": len(dmap), "first": items[0][0], "last": items[-1][0],
        "low": lo, "low_date": lo_date, "high": hi, "high_date": hi_date,
        "latest": items[-1][1],
    }


# ============================================================================
#  DEL 09C .. BROKER STATEMENTS  (Nordnet / Avanza CSV import + ISIN lookup)
# ============================================================================
#  Both statements share: date, account, type, security, ISIN, qty, price,
#  brokerage.  We normalise them to a common record and resolve ISIN -> Yahoo
#  ticker (preferring the Stockholm ".ST" listing).
# ----------------------------------------------------------------------------
NORDNET_TYPES = {"KÖPT": "BUY", "SÅLT": "SELL", "UTDELNING": "DIV"}
AVANZA_TYPES = {"Köp": "BUY", "Sälj": "SELL", "Utdelning": "DIV"}


def _decode_statement(path):
    """Read a broker CSV as text, handling Nordnet UTF-16 and Avanza UTF-8."""
    raw = open(path, "rb").read()
    if raw[:2] in (b"\xff\xfe", b"\xfe\xff"):
        return raw.decode("utf-16", "replace")
    for enc in ("utf-8-sig", "utf-8", "cp1252", "latin-1"):
        try:
            return raw.decode(enc)
        except Exception:
            continue
    return raw.decode("utf-8", "replace")


def downloads_dir():
    """The user's real Downloads folder (follows a moved one), else ~/Downloads."""
    try:
        import ctypes
        import uuid
        from ctypes import wintypes

        class _GUID(ctypes.Structure):
            _fields_ = [("Data1", wintypes.DWORD), ("Data2", wintypes.WORD),
                        ("Data3", wintypes.WORD), ("Data4", ctypes.c_ubyte * 8)]
        u = uuid.UUID("374DE290-123F-4565-9164-39C4925E467B")   # FOLDERID_Downloads
        g = _GUID(u.time_low, u.time_mid, u.time_hi_version,
                  (ctypes.c_ubyte * 8)(*u.bytes[8:]))
        ptr = ctypes.c_wchar_p()
        if ctypes.windll.shell32.SHGetKnownFolderPath(
                ctypes.byref(g), 0, None, ctypes.byref(ptr)) == 0 and ptr.value:
            path = ptr.value
            ctypes.windll.ole32.CoTaskMemFree(ptr)
            return path
    except Exception:
        pass
    return os.path.join(os.path.expanduser("~"), "Downloads")


def looks_like_statement(path):
    """Cheap check of the header line: is this a Nordnet or Avanza statement?
    Downloads is full of other .csv files that must not show up in the import."""
    try:
        with open(path, "rb") as fh:
            raw = fh.read(4096)
        if raw[:2] in (b"\xff\xfe", b"\xfe\xff"):
            text = raw.decode("utf-16", "ignore")
        else:
            text = raw.decode("utf-8-sig", "ignore")
        first = text.splitlines()[0] if text.splitlines() else ""
        return (("Transaktionstyp" in first and "\t" in first)
                or "Typ av transaktion" in first)
    except Exception:
        return False


def find_statement_csvs():
    """Broker statements waiting to be imported: .csv files that LOOK like a
    Nordnet / Avanza statement in the program folder, the user's Downloads
    folder and StockFolio's own Helpfiles folder (top level only - the
    'imported' sub-folder holds what has already been read).  Newest first."""
    return scan_statement_folders()[0]


def scan_statement_folders():
    """(files, where) - the statements found, plus a plain sentence saying
    which folders were searched and how many were found in each, so an empty
    list is never a mystery."""
    found, seen, parts = [], set(), []
    for label, folder in (("Downloads", downloads_dir()),
                          ("program folder", BASE_DIR),
                          ("Helpfiles", HELP_DIR)):
        n = 0
        try:
            names = os.listdir(folder)
        except Exception:
            parts.append(f"{label} {folder} (cannot be read)")
            continue
        for fn in names:
            p = os.path.join(folder, fn)
            key = os.path.normcase(os.path.abspath(p))
            if (fn.lower().endswith(".csv") and key not in seen
                    and os.path.isfile(p) and looks_like_statement(p)):
                seen.add(key)
                found.append(p)
                n += 1
        parts.append(f"{label} {folder}: {n}")
    found.sort(key=lambda p: os.path.getmtime(p), reverse=True)
    where = "Looked in  " + "   |   ".join(parts)
    if not found:
        where += ("   -   nothing waiting. Statements that were already imported "
                  "are in Helpfiles\\StockFolio\\imported - use 'From imported...' "
                  "to read one again.")
    return found, where


def read_statement(path):
    """Return (broker, [normalised rows]).  broker in {'nordnet','avanza',''}."""
    import csv
    import io
    text = _decode_statement(path)
    first = text.splitlines()[0] if text.splitlines() else ""
    if "Transaktionstyp" in first and "\t" in first:
        broker, delim, tmap = "nordnet", "\t", NORDNET_TYPES
        c_date, c_acc, c_type = "Affärsdag", "Depå", "Transaktionstyp"
        c_name, c_isin, c_qty = "Värdepapper", "ISIN", "Antal"
        c_price, c_brok, c_amt = "Kurs", "Courtage", "Belopp"
        c_ref = "Notanummer"
    elif "Typ av transaktion" in first:
        broker, delim, tmap = "avanza", ";", AVANZA_TYPES
        c_date, c_acc, c_type = "Datum", "Konto", "Typ av transaktion"
        c_name, c_isin, c_qty = "Värdepapper/beskrivning", "ISIN", "Antal"
        c_price, c_brok, c_amt = "Kurs", "Courtage", "Belopp"
        c_ref = None
    else:
        return "", []

    rows = list(csv.reader(io.StringIO(text), delimiter=delim))
    if not rows:
        return broker, []
    hdr = rows[0]

    def idx(name):
        try:
            return hdr.index(name)
        except ValueError:
            return -1

    i_date, i_acc, i_type = idx(c_date), idx(c_acc), idx(c_type)
    i_name, i_isin, i_qty = idx(c_name), idx(c_isin), idx(c_qty)
    i_price, i_brok, i_amt = idx(c_price), idx(c_brok), idx(c_amt)
    i_ref = idx(c_ref) if c_ref else -1

    out = []
    for r in rows[1:]:
        if i_type < 0 or i_type >= len(r):
            continue
        kind = tmap.get(r[i_type].strip())
        if not kind:
            continue

        def cell(i):
            return r[i].strip() if 0 <= i < len(r) else ""
        qty = to_float(cell(i_qty))
        out.append({
            "broker": broker,
            "date": cell(i_date),
            "account_id": cell(i_acc),
            "kind": kind,
            "name": cell(i_name),
            "isin": cell(i_isin),
            "qty": abs(qty) if qty is not None else None,
            "price": to_float(cell(i_price)),
            "courtage": to_float(cell(i_brok)) or 0.0,
            "amount": to_float(cell(i_amt)),
            "ref": cell(i_ref) if i_ref >= 0 else "",
        })
    return broker, out


# ---- holdings pasted from the broker's holdings list ------------------------
_CCY_LINE = re.compile(r"^[A-Z]{3}$")
_NUM_LINE = re.compile(r"^[+\-−]?\d[\d\s.,]*(\s*[A-Za-z]{3})?$")


def parse_holdings_paste(text):
    """Parse rows copied from Nordnet's holdings list, e.g.

        Handelsbanken A / SEK / 470 / (blank) / 142,90 / +0,28% / 160,6 SEK / 75 482

    -> [{"name", "shares", "gav", "price", "value"}].  Several companies in one
    paste are fine.  A company starts where a line is followed by a currency
    code; the numbers after it are shares, average cost (GAV), price, value -
    percentages are skipped."""
    lines = [ln.strip() for ln in (text or "").replace("\xa0", " ").splitlines()]
    lines = [ln for ln in lines if ln]
    starts = [i for i in range(len(lines) - 1)
              if _CCY_LINE.match(lines[i + 1]) and not _NUM_LINE.match(lines[i])
              and "%" not in lines[i]]
    out = []
    for n, i in enumerate(starts):
        end = starts[n + 1] if n + 1 < len(starts) else len(lines)
        nums = []
        for ln in lines[i + 2:end]:
            if "%" in ln or not _NUM_LINE.match(ln):
                continue
            v = to_float(ln)
            if v is not None:
                nums.append(v)
        if len(nums) >= 2 and nums[0] > 0:
            out.append({"name": lines[i], "shares": nums[0], "gav": nums[1],
                        "price": nums[2] if len(nums) > 2 else None,
                        "value": nums[3] if len(nums) > 3 else None})
    return out


# ---- orders pasted from the broker's order view ----------------------------
# Broker statements (CSV) lag behind: a sale made today is often missing from
# the export until the next day.  The order view already shows it, so the text
# of a finished order can be pasted instead.  It carries account, company,
# traded volume and average price - but NO date and NO brokerage.
_ORDER_HEAD = re.compile(r"^(s[äa]ljorder|k[öo]porder|s[äa]lj|k[öo]p)\b", re.I)

# words that say nothing about WHICH company it is ("Öresund, Investment AB"
# in the order view is just "Öresund" in the statements)
_NAME_STOP = {"ab", "publ", "ser", "serie", "series", "investment", "inv", "the",
              "ltd", "plc", "oyj", "asa", "as", "nv", "sa", "inc", "corp"}


def name_tokens(s):
    s = re.sub(r"[^\w]+", " ", (s or "").casefold())
    return {w for w in s.split() if w not in _NAME_STOP}


def parse_order_paste(text):
    """Parse text copied from Nordnet's order view.

    Returns (orders, skipped).  orders = [{"kind", "account_id", "name",
    "qty", "price"}] for every FINISHED ("Avslutad") order; skipped = a list of
    plain sentences saying why something was left out."""
    lines = []
    for ln in (text or "").replace("\xa0", " ").splitlines():
        ln = ln.strip().lstrip("*•").strip()
        if ln:
            lines.append(ln)
    blocks, cur = [], None
    for ln in lines:
        if _ORDER_HEAD.match(ln) and len(ln.split()) <= 2:
            cur = [ln]
            blocks.append(cur)
        elif cur is not None:
            cur.append(ln)

    orders, skipped = [], []
    for b in blocks:
        kind = "SELL" if b[0].lower().startswith(("sälj", "salj")) else "BUY"
        acc, acc_i = "", None
        for i, ln in enumerate(b):
            m = re.match(r"^[·•.\-\s]*(\d{5,})$", ln)
            if m:
                acc, acc_i = m.group(1), i
                break
        if acc_i is not None and acc_i + 1 < len(b):
            name = b[acc_i + 1]
        else:
            name = b[1] if len(b) > 1 else ""

        def after(label):
            for i, ln in enumerate(b):
                if ln.lower().startswith(label):
                    rest = ln[len(label):].strip(" :")
                    if rest:
                        return rest
                    if i + 1 < len(b):
                        return b[i + 1]
            return ""
        qty = to_float(after("handlad volym"))
        pr_txt = after("snittpris")
        price = to_float(pr_txt)
        ccy = (re.search(r"\b([A-Za-z]{3})\b", pr_txt) or [None, "SEK"])[1].upper()
        status = after("status") or next(
            (l for l in b if l.lower() == "avslutad"), "")
        label = f"{b[0]} {name}".strip()
        if not acc:
            skipped.append(f"{label}: no account number found")
        elif qty is None or qty <= 0:
            skipped.append(f"{label}: no traded volume")
        elif price is None:
            skipped.append(f"{label}: no average price")
        elif status.strip().lower() != "avslutad":
            skipped.append(f"{label}: status '{status or '?'}' - only finished "
                           f"('Avslutad') orders are used")
        elif ccy != "SEK":
            skipped.append(f"{label}: price in {ccy} - only SEK is handled")
        elif not name:
            skipped.append(f"{label}: no company name")
        else:
            orders.append({"kind": kind, "account_id": acc, "name": name,
                           "qty": qty, "price": price})
    return orders, skipped


def yahoo_isin_to_ticker(isin, timeout=12):
    """Resolve an ISIN to a Yahoo ticker, preferring the Stockholm (.ST) listing."""
    import urllib.parse
    url = ("https://query1.finance.yahoo.com/v1/finance/search?q="
           + urllib.parse.quote(isin))
    req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
    data = json.load(urllib.request.urlopen(req, timeout=timeout))
    quotes = [q for q in data.get("quotes", []) if q.get("symbol")]
    if not quotes:
        return ""
    for q in quotes:                       # prefer Stockholm
        if str(q.get("symbol", "")).endswith(".ST") or q.get("exchange") == "STO":
            return q["symbol"]
    return quotes[0]["symbol"]


# ============================================================================
#  DEL 10 .... WINDOW ICON  (external Icons/StockFolio.ico)
# ============================================================================
def set_window_icon(root):
    if platform.system() != "Windows":
        return
    ico_path = os.path.join(BASE_DIR, "Icons", f"{APP_NAME}.ico")
    if not os.path.isfile(ico_path):
        log(f"icon not found: {ico_path}")
        return
    try:
        root.iconbitmap(ico_path)
    except Exception:
        pass
    try:
        user32 = ctypes.windll.user32
        LR_LOADFROMFILE = 0x0010
        LR_DEFAULTSIZE = 0x0040
        IMAGE_ICON = 1
        WM_SETICON = 0x0080
        hwnd = user32.FindWindowW(None, root.title())
        if not hwnd:
            return
        hbig = user32.LoadImageW(None, 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)
    except Exception as e:
        log(f"set_window_icon win32 failed: {e}")


# ============================================================================
#  DEL 11 .... MAIN APPLICATION  -  build UI
# ============================================================================
class App:
    def __init__(self, root):
        self.root = root
        self.S = load_settings()
        init_path = self.S.get("last_portfolio") or DATA_FILE
        if not os.path.isfile(init_path):
            init_path = DATA_FILE
        self.pf = Portfolio(init_path)
        self.prices = self.S.get("prices", {})            # Yahoo prices
        self.sheet_prices = self.S.get("sheet_prices", {})  # Google Sheet prices
        self.gsheet = self.S.get("gsheet", dict(DEFAULT_GSHEET))
        self.price_source = self.S.get("price_source", "yahoo")
        self.accounts = self.S.get("accounts", ["OA-Lars", "N-Lars", "A-Lars", "ON-Lars"])
        self.account_map = self.S.get("account_map", {})
        self.account_meta = self.S.get("account_meta", {})   # acct -> {owner, broker}
        self.price_history = load_price_history()   # {ticker: {date: price}}
        self.busy = False

        root.title(APP_NAME)
        root.configure(bg=C_BG)
        root.geometry(self.S.get("geometry", "1180x640"))
        root.minsize(900, 480)
        root.protocol("WM_DELETE_WINDOW", self.on_close)

        self._build_style()
        self._build_menubar()
        self._build_toolbar()
        self._build_tabs()
        self._build_statusbar()

        self.refresh_table()
        self.refresh_dividends_view()
        self.refresh_person_view()
        self.refresh_account_view()
        self.refresh_sold_view()
        self.update_warnings()

        self._update_title()
        self._attach_phone_sync()

        if self.S.get("auto_refresh_on_start", True) and self.pf.tickers():
            root.after(400, self.refresh_prices)

    def _update_title(self):
        try:
            self.root.title(f"{APP_NAME}  -  {os.path.basename(self.pf.path)}")
        except Exception:
            self.root.title(APP_NAME)

    # ---- ttk style ----
    def _build_style(self):
        st = ttk.Style()
        try:
            st.theme_use("clam")
        except Exception:
            pass
        st.configure("Treeview",
                     background=C_BG2, fieldbackground=C_BG2, foreground=C_FG,
                     rowheight=24, font=FONT, borderwidth=0)
        st.configure("Treeview.Heading",
                     background=C_BG3, foreground=C_ACCENT,
                     font=FONT_B, relief="flat")
        st.map("Treeview.Heading", background=[("active", C_SEP)])
        st.map("Treeview", background=[("selected", C_SEP)],
               foreground=[("selected", C_FG)])
        st.configure("TNotebook", background=C_BG, borderwidth=0)
        st.configure("TNotebook.Tab", background=C_BG2, foreground=C_FG_DIM,
                     padding=(16, 7), font=FONT_B)
        st.map("TNotebook.Tab",
               background=[("selected", C_BG3)],
               foreground=[("selected", C_ACCENT)])

    # ---- menu bar ----
    def _build_menubar(self):
        mb = tk.Menu(self.root)
        filem = tk.Menu(mb, tearoff=0)
        filem.add_command(label="New portfolio...", command=self.portfolio_new)
        filem.add_command(label="Open portfolio...", command=self.portfolio_open)
        filem.add_command(label="Save", command=self.portfolio_save)
        filem.add_command(label="Save As...", command=self.portfolio_save_as)
        filem.add_separator()
        filem.add_command(label="Restore from backup...", command=self.portfolio_restore_backup)
        filem.add_command(label="Open backups folder", command=self._open_backups_folder)
        filem.add_separator()
        filem.add_command(label="Phone sync (Issu's StockFolio app)...", command=self.open_phone_sync)
        filem.add_separator()
        filem.add_command(label="Exit", command=self.on_close)
        mb.add_cascade(label="File", menu=filem)

        toolsm = tk.Menu(mb, tearoff=0)
        toolsm.add_command(label="Manage accounts (owner / broker / code)...",
                           command=self.open_account_manager)
        toolsm.add_command(label="Add company...", command=self.add_company)
        toolsm.add_command(label="Attention - check sheet vs your data...",
                           command=self.open_attention)
        toolsm.add_command(label="Find duplicates...", command=self.open_duplicates)
        toolsm.add_separator()
        toolsm.add_command(label="Import broker CSV...", command=self.open_import_csv)
        toolsm.add_command(label="Quick overview - total value of chosen accounts...",
                           command=self.open_overview)
        toolsm.add_command(label="Google Sheet...", command=self.open_gsheet)
        toolsm.add_command(label="Price history...", command=self.open_price_history)
        mb.add_cascade(label="Tools", menu=toolsm)

        helpm = tk.Menu(mb, tearoff=0)
        helpm.add_command(label="Help", command=self.show_help)
        helpm.add_command(label="About", command=self.show_about)
        mb.add_cascade(label="Help", menu=helpm)
        self.root.config(menu=mb)

    def _btn(self, parent, text, cmd, color):
        return tk.Button(parent, text=text, command=cmd, bg=color, fg="#10243a",
                         activebackground="#dfe8f2", relief="flat",
                         font=FONT_B, padx=12, pady=6, cursor="hand2",
                         highlightthickness=0, bd=0)

    # ---- toolbar ----
    def _build_toolbar(self):
        bar = tk.Frame(self.root, bg=C_BG)
        bar.pack(fill="x", padx=10, pady=(10, 4))
        self._btn(bar, "+ Add transaction", self.add_transaction, BTN_ADD).pack(side="left", padx=3)
        self._btn(bar, "Edit", self.edit_transaction, BTN_EDIT).pack(side="left", padx=3)
        self._btn(bar, "Delete", self.delete_transaction, BTN_DELETE).pack(side="left", padx=3)
        self._btn(bar, "Dividends", self.open_dividends, BTN_DIVIDEND).pack(side="left", padx=3)
        self._btn(bar, "What-if", self.open_whatif, BTN_WHATIF).pack(side="left", padx=3)
        self.refresh_btn = self._btn(bar, "Refresh (Yahoo)", self.refresh_prices, BTN_REFRESH)
        self.refresh_btn.pack(side="left", padx=3)
        self._btn(bar, "Google Sheet", self.open_gsheet, BTN_REFRESH).pack(side="left", padx=3)
        self._btn(bar, "Import CSV", self.open_import_csv, BTN_ADD).pack(side="left", padx=3)
        self._btn(bar, "Overview", self.open_overview, BTN_REFRESH).pack(side="left", padx=3)
        self._btn(bar, "History", self.open_price_history, BTN_REFRESH).pack(side="left", padx=3)
        self._btn(bar, "About", self.show_about, BTN_ABOUT).pack(side="right", padx=3)
        self._btn(bar, "Help", self.show_help, BTN_HELP).pack(side="right", padx=3)

    # ---- tabs ----
    def _build_tabs(self):
        self.nb = ttk.Notebook(self.root)
        self.nb.pack(fill="both", expand=True, padx=10, pady=4)
        self._build_portfolio_tab()
        self._build_person_tab()
        self._build_account_tab()
        self._build_dividend_tab()
        self._build_sold_tab()

    def _build_portfolio_tab(self):
        frame = tk.Frame(self.nb, bg=C_BG)
        self.nb.add(frame, text="  Portfolio  ")

        cols = ("company", "ticker", "owner", "account", "qty", "gav", "invested",
                "price", "day", "gprice", "value", "pl", "plpct", "net",
                "divdate", "divsum")
        heads = {
            "company": "Company", "ticker": "Ticker", "owner": "Owner",
            "account": "Broker", "qty": "Shares", "gav": "Avg cost",
            "invested": "Invested", "price": "Yahoo", "day": "Day %",
            "gprice": "Sheet", "value": "Value", "pl": "Price +/-",
            "plpct": "G/L %", "net": "Net +/- (inc. div)",
            "divdate": "Next div.", "divsum": "Div. amount",
        }
        widths = {
            "company": 190, "ticker": 88, "owner": 78, "account": 100, "qty": 64,
            "gav": 84, "invested": 100, "price": 76, "day": 64, "gprice": 76,
            "value": 104, "pl": 100, "plpct": 64, "net": 120, "divdate": 90,
            "divsum": 92,
        }
        wrap = tk.Frame(frame, bg=C_BG)
        wrap.pack(fill="both", expand=True)
        self.tree = ttk.Treeview(wrap, columns=cols, show="headings", selectmode="browse")
        for c in cols:
            anchor = "w" if c in ("company", "ticker", "owner", "account") else "e"
            self.tree.heading(c, text=heads[c],
                              command=lambda cc=c: self.sort_by(cc))
            self.tree.column(c, width=widths[c], anchor=anchor,
                             stretch=(c == "company"))
        vs = ttk.Scrollbar(wrap, orient="vertical", command=self.tree.yview)
        hs = ttk.Scrollbar(wrap, orient="horizontal", command=self.tree.xview)
        self.tree.configure(yscrollcommand=vs.set, xscrollcommand=hs.set)
        wrap.rowconfigure(0, weight=1)
        wrap.columnconfigure(0, weight=1)
        self.tree.grid(row=0, column=0, sticky="nsew")
        vs.grid(row=0, column=1, sticky="ns")
        hs.grid(row=1, column=0, sticky="ew")
        bind_mousewheel(self.tree)
        self.tree.tag_configure("gain", foreground=C_GOOD)
        self.tree.tag_configure("loss", foreground=C_BAD)
        self.tree.tag_configure("warn", background="#3a3320")
        self.tree.tag_configure("total", background=C_BG3, foreground=C_ACCENT,
                                font=FONT_B)
        self.tree.bind("<Double-1>", self._on_tree_double)
        self.tree.bind("<Button-3>", self._on_tree_right)

    def _on_tree_double(self, event):
        row = self.tree.identify_row(event.y)
        if not row:
            return
        vals = self.tree.item(row, "values")
        if not vals or vals[0] == "TOTAL":
            return
        if self.tree.identify_column(event.x) == "#1":   # Company column
            self._show_company(vals[1])
        else:
            self.edit_transaction()

    def _on_tree_right(self, event):
        """Right-click a holding: buys / sells / dividends popup, company info, edit."""
        row = self.tree.identify_row(event.y)
        if not row:
            return
        self.tree.selection_set(row)
        vals = self.tree.item(row, "values")
        if not vals or vals[0] == "TOTAL":
            return
        ticker, owner, broker = vals[1], vals[2], vals[3]
        cands = [h["account"] for h in self.pf.holdings()
                 if h["ticker"] == ticker and self.owner_of(h["account"]) == owner
                 and self.broker_display(h["account"]) == broker]
        acc = cands[0] if len(cands) == 1 else None
        m = tk.Menu(self.root, tearoff=0, bg=C_BG2, fg=C_FG)
        m.add_command(label="Buys, sells & dividends...",
                      command=lambda: self._show_trade_detail(ticker, acc))
        m.add_command(label="Company info...",
                      command=lambda: self._show_company(ticker, account=acc))
        m.add_command(label="Edit transaction...", command=self.edit_transaction)
        try:
            m.tk_popup(event.x_root, event.y_root)
        finally:
            m.grab_release()

    def _filter_menu(self, parent, var):
        mnu = tk.OptionMenu(parent, var, "All")
        mnu.configure(bg=C_BG2, fg=C_FG, activebackground=C_SEP, relief="flat",
                      highlightthickness=0, font=("Segoe UI", 8), width=10)
        mnu["menu"].configure(bg=C_BG2, fg=C_FG)
        mnu.pack(side="left", padx=(0, 8))
        return mnu

    def _set_menu(self, mnu, var, options):
        m = mnu["menu"]
        m.delete(0, "end")
        if var.get() not in options:
            var.set("All")
        for opt in options:
            m.add_command(label=opt, command=lambda v=opt, vr=var:
                          (vr.set(v), self.refresh_person_view()))

    def _build_person_tab(self):
        frame = tk.Frame(self.nb, bg=C_BG)
        self.nb.add(frame, text="  By person  ")

        bar = tk.Frame(frame, bg=C_BG)
        bar.pack(fill="x", pady=(0, 2))
        tk.Label(bar, text="Owner", bg=C_BG, fg=C_FG_DIM, font=("Segoe UI", 8)).pack(side="left")
        self.f_owner = tk.StringVar(value="All")
        self.owner_menu = self._filter_menu(bar, self.f_owner)
        tk.Label(bar, text="Account", bg=C_BG, fg=C_FG_DIM, font=("Segoe UI", 8)).pack(side="left")
        self.f_acct = tk.StringVar(value="All")
        self.acct_menu = self._filter_menu(bar, self.f_acct)
        tk.Label(bar, text="Company", bg=C_BG, fg=C_FG_DIM, font=("Segoe UI", 8)).pack(side="left")
        self.f_company = tk.StringVar(value="All")
        self.company_menu = self._filter_menu(bar, self.f_company)
        self._btn(bar, "Accounts...", self.open_account_manager, BTN_REFRESH).pack(side="right", padx=2)
        self._btn(bar, "Add company", self.add_company, BTN_ADD).pack(side="right", padx=2)

        bar2 = tk.Frame(frame, bg=C_BG)
        bar2.pack(fill="x", pady=(0, 4))
        self.sep_acct = tk.BooleanVar(value=False)
        tk.Checkbutton(bar2, text="Separate by account", variable=self.sep_acct,
                       command=self.refresh_person_view, bg=C_BG, fg=C_FG,
                       selectcolor=C_BG2, activebackground=C_BG, font=("Segoe UI", 8),
                       highlightthickness=0).pack(side="left", padx=2)
        self.incl_sold = tk.BooleanVar(value=False)
        tk.Checkbutton(bar2, text="Include sold (closed positions)", variable=self.incl_sold,
                       command=self._on_incl_sold_toggle, bg=C_BG, fg=C_FG,
                       selectcolor=C_BG2, activebackground=C_BG, font=("Segoe UI", 8),
                       highlightthickness=0).pack(side="left", padx=2)
        self.incl_sold_div = tk.BooleanVar(value=False)
        self.chk_sold_div = tk.Checkbutton(
            bar2, text="Include dividends from sold stocks", variable=self.incl_sold_div,
            command=self.refresh_person_view, bg=C_BG, fg=C_FG,
            selectcolor=C_BG2, activebackground=C_BG, font=("Segoe UI", 8),
            highlightthickness=0, state="disabled")
        self.chk_sold_div.pack(side="left", padx=2)
        # ToDo (1.5): "Assume calendar dividends were paid" - see assumed_dividends().
        self.assume_div = tk.BooleanVar(value=False)
        tk.Checkbutton(bar2, text="Assume calendar dividends were paid", variable=self.assume_div,
                       command=self.refresh_person_view, bg=C_BG, fg=C_FG,
                       selectcolor=C_BG2, activebackground=C_BG, font=("Segoe UI", 8),
                       highlightthickness=0).pack(side="left", padx=2)
        self.person_hint = tk.Label(bar2, text=self._PERSON_HINT,
                                    bg=C_BG, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"))
        self.person_hint.pack(side="left", padx=10)

        wrap = tk.Frame(frame, bg=C_BG)
        wrap.pack(fill="both", expand=True)
        cols = ("accounts", "qty", "gav", "invested", "value", "pl", "net", "div")
        heads = {"accounts": "Accounts", "qty": "Shares", "gav": "Avg cost",
                 "invested": "Invested", "value": "Value", "pl": "Price +/-",
                 "net": "Net +/-", "div": "Dividends"}
        widths = {"accounts": 90, "qty": 64, "gav": 80, "invested": 92,
                  "value": 100, "pl": 92, "net": 100, "div": 80}
        self.ptree = ttk.Treeview(wrap, columns=cols, show="tree headings", selectmode="browse")
        self.ptree.heading("#0", text="Person / Company")
        self.ptree.column("#0", width=230, anchor="w")
        for c in cols:
            self.ptree.heading(c, text=heads[c])
            self.ptree.column(c, width=widths[c], anchor="w" if c == "accounts" else "e")
        vs = ttk.Scrollbar(wrap, orient="vertical", command=self.ptree.yview)
        self.ptree.configure(yscrollcommand=vs.set)
        self.ptree.pack(side="left", fill="both", expand=True)
        vs.pack(side="right", fill="y")
        bind_mousewheel(self.ptree)
        self.ptree.tag_configure("person", background=C_BG3, foreground=C_ACCENT, font=FONT_B)
        self.ptree.tag_configure("gain", foreground=C_GOOD)
        self.ptree.tag_configure("loss", foreground=C_BAD)
        self.ptree.tag_configure("sold", foreground=C_FG_DIM)
        self.ptree.tag_configure("total", background=C_BG3, foreground=C_ACCENT, font=FONT_B)
        self.ptree.bind("<Double-1>", self._person_detail)

    # ---- By account: one block per broker account, to check against the broker ----
    def _build_account_tab(self):
        frame = tk.Frame(self.nb, bg=C_BG)
        self.nb.add(frame, text="  By account  ")
        bar = tk.Frame(frame, bg=C_BG)
        bar.pack(fill="x", pady=(0, 4))
        tk.Label(bar, text="Owner", bg=C_BG, fg=C_FG_DIM, font=("Segoe UI", 8)).pack(side="left")
        self.f_acc_owner = tk.StringVar(value="All")
        self.acc_owner_menu = self._filter_menu(bar, self.f_acc_owner)
        # two ways to look at the same holdings
        self.acc_view = tk.StringVar(value="login")
        for txt, val in (("Per broker login", "login"), ("Per account", "account"),
                         ("Per broker (all owners)", "broker")):
            tk.Radiobutton(bar, text=txt, variable=self.acc_view, value=val,
                           command=self.refresh_account_view, bg=C_BG, fg=C_FG,
                           selectcolor=C_BG2, activebackground=C_BG, font=FONT,
                           highlightthickness=0).pack(side="left", padx=(8, 0))
        # per-broker view only: owners as headings (off = the owner is in brackets)
        self.acc_owner_heads = tk.BooleanVar(value=False)
        tk.Checkbutton(bar, text="Owners as headings", variable=self.acc_owner_heads,
                       command=self.refresh_account_view, bg=C_BG, fg=C_FG,
                       selectcolor=C_BG2, activebackground=C_BG, font=FONT,
                       highlightthickness=0).pack(side="left", padx=(14, 0))
        self._btn(bar, "Check against broker...", self.open_broker_check,
                  BTN_REFRESH).pack(side="right", padx=4)
        tk.Label(bar, text="Compare with the broker's holdings list. 'Last trade' shows how "
                 "fresh the data is; double-click a company for every purchase, sale and "
                 "dividend.",
                 bg=C_BG, fg=C_FG_DIM, font=("Segoe UI", 8, "italic")).pack(side="left", padx=10)

        cols = ("ticker", "qty", "gav", "invested", "value", "pl", "plpct", "last", "flags")
        heads = {"ticker": "Ticker", "qty": "Shares", "gav": "Avg cost",
                 "invested": "Invested", "value": "Value", "pl": "Price +/-",
                 "plpct": "%", "last": "Last trade", "flags": "Check"}
        widths = {"ticker": 90, "qty": 64, "gav": 76, "invested": 92, "value": 96,
                  "pl": 92, "plpct": 64, "last": 90, "flags": 230}
        wrap = tk.Frame(frame, bg=C_BG)
        wrap.pack(fill="both", expand=True)
        self.atree = ttk.Treeview(wrap, columns=cols, show="tree headings", selectmode="browse")
        self.atree.heading("#0", text="Account / company")
        self.atree.column("#0", width=300, anchor="w")
        for c in cols:
            self.atree.heading(c, text=heads[c])
            self.atree.column(c, width=widths[c], anchor="w" if c in ("ticker", "flags") else "e",
                              stretch=(c == "flags"))
        vs = ttk.Scrollbar(wrap, orient="vertical", command=self.atree.yview)
        self.atree.configure(yscrollcommand=vs.set)
        self.atree.pack(side="left", fill="both", expand=True)
        vs.pack(side="right", fill="y")
        bind_mousewheel(self.atree)
        self.atree.tag_configure("acct", background=C_BG3, foreground=C_HEAD, font=FONT_B)
        self.atree.tag_configure("gain", foreground=C_GOOD)
        self.atree.tag_configure("loss", foreground=C_BAD)
        self.atree.tag_configure("flag", foreground=C_WARN)
        self.atree.tag_configure("mismatch", background="#3a3320")
        self.atree.tag_configure("owner", background=C_BG2, foreground=C_HEAD, font=FONT_B)
        self.atree.bind("<Double-1>", self._account_detail)

    def _account_detail(self, event=None):
        sel = self.atree.selection()
        if sel and sel[0].startswith("H:"):
            acc, ticker = sel[0][2:].split("||", 1)
            self._show_trade_detail(ticker, acc)

    def refresh_account_view(self):
        if not hasattr(self, "atree"):
            return
        txs = {}
        for t in self.pf.transactions:
            txs.setdefault(t.get("account", ""), []).append(t)
        owners = sorted({self.owner_of(a) for a in txs}, key=str.casefold)
        mnu = self.acc_owner_menu["menu"]
        mnu.delete(0, "end")
        for o in ["All"] + owners:
            mnu.add_command(label=o, command=lambda v=o: (self.f_acc_owner.set(v),
                                                          self.refresh_account_view()))
        if self.f_acc_owner.get() not in ["All"] + owners:
            self.f_acc_owner.set("All")
        f_owner = self.f_acc_owner.get()

        acc_key = self._acc_sort_key

        def flags_of(rows):
            def is_adj(t):
                return str(t.get("note", "")).startswith("pasted (reconcile")

            def is_paste(t):
                return str(t.get("note", "")).startswith("pasted") and not is_adj(t)
            n_paste = sum(1 for t in rows if is_paste(t))
            n_adj = sum(1 for t in rows if is_adj(t))
            n_nocg = sum(1 for t in rows if not self._tx_courtage(t)
                         and not str(t.get("note", "")).startswith("pasted"))
            n_unver = sum(1 for t in rows if not t.get("verified")
                          and not str(t.get("note", "")).startswith("pasted"))
            parts = []
            if n_adj:
                parts.append(f"{n_adj} added to match the broker")
            if n_paste:
                parts.append(f"{n_paste} pasted (no brokerage yet)")
            if n_nocg:
                parts.append(f"{n_nocg} without brokerage")
            if n_unver:
                parts.append(f"{n_unver} not from a statement")
            return ", ".join(parts)

        def pct(v, c):
            return f"{(v - c) / c * 100:+.1f}%" if c else "-"

        self.atree.delete(*self.atree.get_children())
        by_acc = {}
        for h in self.pf.holdings():
            by_acc.setdefault(h["account"], []).append(h)

        def company_of(tk_):
            return self.pf.company_for(tk_, self.prices)

        def value_of(h):
            price = self.active_price(h["ticker"])
            return price * h["qty"] if price is not None else None

        def sums(pairs):
            """(invested, value, value-cost of the priced ones, without price)"""
            val = cost_p = cost_all = 0.0
            missing = 0
            for _acc, h in pairs:
                v = value_of(h)
                cost_all += h["cost"]
                if v is None:
                    missing += 1
                else:
                    val += v
                    cost_p += h["cost"]
            return cost_all, val, val - cost_p, pct(val, cost_p), missing

        def holding_vals(acc, h):
            """(values, tags) of one holding row."""
            mine = [t for t in txs.get(acc, []) if t.get("ticker") == h["ticker"]]
            value = value_of(h)
            pl = (value - h["cost"]) if value is not None else None
            tags = [] if pl is None else (["gain"] if pl >= 0 else ["loss"])
            chk, bad = self._check_status(acc, h["ticker"], h["qty"])
            if bad:
                tags.append("mismatch")
            flags = "; ".join(x for x in (chk, flags_of(mine)) if x)
            return ((h["ticker"], fnum(h["qty"], 0), fnum(h["gav"]), fnum(h["cost"], 0),
                     fnum(value, 0) if value is not None else "-",
                     fnum(pl, 0) if pl is not None else "-",
                     pct(value, h["cost"]) if value is not None else "-",
                     max((t.get("date", "") for t in mine), default=""), flags),
                    tuple(tags))

        def node_flags(accs, n_trades, missing):
            parts = [f"{n_trades} trades"]
            fl = flags_of([t for a in accs for t in txs.get(a, [])])
            if fl:
                parts.append(fl)
            bad = sum(len(self._check_mismatches(a)) for a in accs)
            if bad:
                parts.append(f"{bad} differ from the broker check")
            if missing:
                parts.append(f"{missing} without price")
            return ", ".join(parts)

        def who_of(acc):
            code = (self.account_meta.get(acc, {}).get("code") or "").strip()
            return f"{self.owner_of(acc)} {code}".strip()

        def section_of(a):
            return (self.account_meta.get(a, {}).get("section") or "").strip()

        if self.acc_view.get() == "login":
            # ---- one block per real broker login (= what you see when you log in at the
            #      broker): the total matches the broker's own total.  Accounts with the same
            #      Section are one login; an account without Section is a login of its own ----
            logins = {}
            for a in sorted(set(txs) | {x for x in by_acc}, key=acc_key):
                if f_owner != "All" and self.owner_of(a) != f_owner:
                    continue
                logins.setdefault(section_of(a) or self._overview_label(a), []).append(a)
            heads = self.acc_owner_heads.get()
            for name, members in logins.items():
                items = [(a, h) for a in members for h in by_acc.get(a, [])]
                inv, val, pl, pc, miss = sums(items)
                last = max((t.get("date", "") for a in members for t in txs.get(a, [])), default="")
                owners = sorted({self.owner_of(a) for a in members}, key=str.casefold)
                n_comp = len({h["ticker"] for _a, h in items})
                node = self.atree.insert(
                    "", "end", iid="L:" + name, open=True, tags=("acct",),
                    text=f"{name}   ({', '.join(owners)};  {n_comp} companies)",
                    values=("", "", "", fnum(inv, 0), fnum(val, 0), fnum(pl, 0), pc, last,
                            node_flags(members, sum(len(txs.get(a, [])) for a in members), miss)))
                if heads:
                    for owner in owners:
                        sub = [(a, h) for a, h in items if self.owner_of(a) == owner]
                        si, sv, sp, spc, sm = sums(sub)
                        onode = self.atree.insert(
                            node, "end", iid=f"O:{name}||{owner}", open=True, tags=("owner",),
                            text=f"   {owner}", values=("", "", "", fnum(si, 0), fnum(sv, 0),
                                                         fnum(sp, 0), spc, "", ""))
                        for acc, h in sorted(sub, key=lambda x: company_of(x[1]["ticker"]).casefold()):
                            vals, tags = holding_vals(acc, h)
                            self.atree.insert(onode, "end", iid=f"H:{acc}||{h['ticker']}", tags=tags,
                                              values=vals, text="      " + company_of(h["ticker"]))
                    continue
                by_tk = {}
                for a, h in items:
                    by_tk.setdefault(h["ticker"], []).append((a, h))
                for tk_ in sorted(by_tk, key=lambda x: company_of(x).casefold()):
                    parts = by_tk[tk_]
                    if len(parts) == 1:
                        a, h = parts[0]
                        vals, tags = holding_vals(a, h)
                        self.atree.insert(node, "end", iid=f"H:{a}||{tk_}", tags=tags, values=vals,
                                          text=f"   {company_of(tk_)}  ({who_of(a)})")
                        continue
                    # several owners hold this company here: total row + one row per owner
                    qty = sum(h["qty"] for _a, h in parts)
                    cost = sum(h["cost"] for _a, h in parts)
                    v_all = [value_of(h) for _a, h in parts]
                    value = None if any(v is None for v in v_all) else sum(v_all)
                    plv = (value - cost) if value is not None else None
                    cn = self.atree.insert(
                        node, "end", iid=f"C:{name}||{tk_}", open=True,
                        tags=() if plv is None else (("gain",) if plv >= 0 else ("loss",)),
                        text=f"   {company_of(tk_)}  (total)",
                        values=(tk_, fnum(qty, 0), fnum(cost / qty) if qty else "", fnum(cost, 0),
                                fnum(value, 0) if value is not None else "-",
                                fnum(plv, 0) if plv is not None else "-",
                                pct(value, cost) if value is not None else "-", "", ""))
                    for a, h in sorted(parts, key=lambda x: acc_key(x[0])):
                        vals, tags = holding_vals(a, h)
                        self.atree.insert(cn, "end", iid=f"H:{a}||{tk_}", tags=tags, values=vals,
                                          text=f"         ({who_of(a)})")
            return
        if self.acc_view.get() == "broker":
            # ---- everything at one broker; sorted per company, owner in brackets ----
            by_broker = {}
            for acc, hs in by_acc.items():
                if f_owner != "All" and self.owner_of(acc) != f_owner:
                    continue
                by_broker.setdefault(self.broker_of(acc) or "(no broker)", []).extend(
                    (acc, h) for h in hs)
            heads = self.acc_owner_heads.get()
            for broker in sorted(by_broker, key=str.casefold):
                items = by_broker[broker]
                accs = sorted({a for a, _h in items}, key=acc_key)
                inv, val, pl, pc, miss = sums(items)
                last = max((t.get("date", "") for a in accs for t in txs.get(a, [])), default="")
                node = self.atree.insert(
                    "", "end", iid="B:" + broker, open=True, tags=("acct",),
                    text=f"{broker}   ({len(accs)} accounts, {len(items)} holdings)",
                    values=("", "", "", fnum(inv, 0), fnum(val, 0), fnum(pl, 0), pc, last,
                            node_flags(accs, sum(len(txs.get(a, [])) for a in accs), miss)))
                if heads:
                    owner_order = sorted({self.owner_of(a) for a, _h in items},
                                         key=lambda o: (o.casefold() != self.OVERVIEW_DEFAULT_OWNER.casefold(),
                                                        o.casefold()))
                    for owner in owner_order:
                        sub = [(a, h) for a, h in items if self.owner_of(a) == owner]
                        o_accs = sorted({a for a, _h in sub}, key=acc_key)
                        si, sv, sp, spc, sm = sums(sub)
                        onode = self.atree.insert(
                            node, "end", iid=f"O:{broker}||{owner}", open=True, tags=("owner",),
                            text=f"   {owner}", values=("", "", "", fnum(si, 0), fnum(sv, 0),
                                                         fnum(sp, 0), spc, "", ""))
                        for acc, h in sorted(sub, key=lambda x: (company_of(x[1]["ticker"]).casefold(),
                                                                 acc_key(x[0]))):
                            vals, tags = holding_vals(acc, h)
                            code = (self.account_meta.get(acc, {}).get("code") or "").strip()
                            extra = f"  ({code})" if code and len(o_accs) > 1 else ""
                            self.atree.insert(onode, "end", iid=f"H:{acc}||{h['ticker']}",
                                              tags=tags, values=vals,
                                              text=f"      {company_of(h['ticker'])}{extra}")
                else:
                    for acc, h in sorted(items, key=lambda x: (company_of(x[1]["ticker"]).casefold(),
                                                               acc_key(x[0]))):
                        vals, tags = holding_vals(acc, h)
                        self.atree.insert(node, "end", iid=f"H:{acc}||{h['ticker']}",
                                          tags=tags, values=vals,
                                          text=f"   {company_of(h['ticker'])}  ({who_of(acc)})")
            return

        # ---- one block per account; accounts with the same "section" (the real
        #      broker account they sit in, e.g. Olga Avanza) are grouped together ----
        def section_of(a):
            return (self.account_meta.get(a, {}).get("section") or "").strip()

        # accounts prepared in Manage accounts (a broker is set) but with no trades yet
        aliases = set(self.account_map.keys()) if isinstance(self.account_map, dict) else set()
        prepared = {a for a, m in self.account_meta.items()
                    if a not in txs and a not in aliases
                    and ((m.get("broker") or "").strip() or (m.get("section") or "").strip())}
        all_accs = [a for a in sorted(set(txs) | prepared, key=acc_key)
                    if f_owner == "All" or self.owner_of(a) == f_owner]
        order, groups = [], {}
        for a in all_accs:
            sec = section_of(a)
            if sec:
                if sec not in groups:
                    groups[sec] = []
                    order.append(("S", sec))
                groups[sec].append(a)
            else:
                order.append(("A", a))

        def add_account(parent, acc):
            rows = txs.get(acc, [])
            hs = sorted(by_acc.get(acc, []), key=lambda h: company_of(h["ticker"]).casefold())
            inv, val, pl, pc, miss = sums([(acc, h) for h in hs])
            last = max((t.get("date", "") for t in rows), default="")
            note = ""
            if not rows:
                note = "  (no trades yet)"
            elif not hs:
                note = "  (nothing held)"
            node = self.atree.insert(
                parent, "end", iid="A:" + acc, open=True, tags=("acct",),
                text=self._overview_label(acc) + note,
                values=("", "", "", fnum(inv, 0), fnum(val, 0), fnum(pl, 0), pc, last,
                        node_flags([acc], len(rows), miss)))
            for h in hs:
                vals, tags = holding_vals(acc, h)
                self.atree.insert(node, "end", iid=f"H:{acc}||{h['ticker']}", tags=tags,
                                  text="   " + company_of(h["ticker"]), values=vals)
            # companies the broker check says the broker holds, but the portfolio does not
            held = {h["ticker"] for h in hs}
            for tk_ in self._check_mismatches(acc):
                if tk_ not in held:
                    chk, _bad = self._check_status(acc, tk_, 0.0)
                    self.atree.insert(node, "end", iid=f"H:{acc}||{tk_}", tags=("mismatch",),
                                      text="   " + company_of(tk_),
                                      values=(tk_, "0", "", "", "", "", "", "", chk))

        for kind, key in order:
            if kind == "A":
                add_account("", key)
                continue
            members = groups[key]
            items = [(a, h) for a in members for h in by_acc.get(a, [])]
            inv, val, pl, pc, miss = sums(items)
            last = max((t.get("date", "") for a in members for t in txs.get(a, [])), default="")
            owners = sorted({self.owner_of(a) for a in members}, key=str.casefold)
            node = self.atree.insert(
                "", "end", iid="S:" + key, open=True, tags=("acct",),
                text=f"{key}   (holdings of {', '.join(owners)})",
                values=("", "", "", fnum(inv, 0), fnum(val, 0), fnum(pl, 0), pc, last,
                        node_flags(members, sum(len(txs.get(a, [])) for a in members), miss)))
            for a in members:
                add_account(node, a)
    # ---- account helpers: sort order, broker-check status ----
    def _acc_sort_key(self, a):
        """Your own accounts first, the O accounts after the plain ones."""
        m = self.account_meta.get(a, {})
        code = (m.get("code") or "").strip().upper()
        owner = self.owner_of(a)
        return (owner.casefold() != self.OVERVIEW_DEFAULT_OWNER.casefold(), owner.casefold(),
                code.startswith("O") and code not in ("N", "A"),
                (m.get("broker") or "").casefold(), code, a.casefold())

    def _check_status(self, acc, ticker, qty):
        """('✔ ...' / '⚠ ...', mismatch?) from the saved broker check, or ('', False)."""
        snap = self.pf.broker_checks.get(acc, {}).get(ticker)
        if not snap:
            return "", False
        d = snap.get("date", "")
        if abs(float(snap.get("shares", 0)) - qty) < 0.5:
            return f"✔ matches broker ({d})", False
        return (f"⚠ broker had {fnum(snap.get('shares', 0), 0)} on {d}, "
                f"now {fnum(qty, 0)}"), True

    def _check_mismatches(self, acc):
        """Tickers whose share count differs from the saved broker check."""
        snaps = self.pf.broker_checks.get(acc, {})
        if not snaps:
            return []
        have = {}
        for h in self.pf.holdings():
            if h["account"] == acc:
                have[h["ticker"]] = have.get(h["ticker"], 0.0) + h["qty"]
        return [tk_ for tk_, s in snaps.items()
                if abs(float(s.get("shares", 0)) - have.get(tk_, 0.0)) >= 0.5]

    # ---- check against the broker: "I have 470, my average cost is 142,90" ----
    def _reconcile(self, acc, ticker, b_sh, b_gav):
        """Compare what the broker says (shares, GAV) with the portfolio.

        status: ok / sold (the broker has FEWER shares - an unrecorded sale) /
        bought (the broker has MORE - an unrecorded purchase) / gav (same shares,
        another average cost).  For 'bought' the missing shares' average price is
        worked out from the broker's total cost, so a purchase made over several
        periods is averaged.  A sale's price cannot be worked out - it has to be
        looked up at the broker."""
        key = self._norm_account(acc)
        qty = cost = 0.0
        for h in self.pf.holdings():
            if h["ticker"] == ticker and self._norm_account(h["account"]) == key:
                qty += h["qty"]
                cost += h["cost"]
        gav = cost / qty if qty else 0.0
        diff = qty - b_sh
        broker = self.broker_of(acc) or "the broker"
        r = {"qty": qty, "cost": cost, "gav": gav, "diff": diff, "status": "ok",
             "short": "✔ matches", "implied": None, "text": "Shares and average cost match."}
        if abs(diff) >= 0.5:
            if diff > 0:
                r["status"] = "sold"
                r["short"] = f"✘ {diff:g} sold, not recorded"
                r["text"] = (
                    f"The portfolio has {diff:g} more shares than {broker}: {diff:g} shares "
                    f"must have been SOLD without being recorded. The sale price cannot be "
                    f"worked out - look it up in {broker}'s transactions or order view "
                    f"(price and date), then use 'Add missing sale...'.")
            else:
                miss = -diff
                implied_total = b_sh * b_gav - cost
                r["status"] = "bought"
                r["short"] = f"✘ {miss:g} bought, not recorded"
                if b_gav and implied_total > 0:
                    r["implied"] = implied_total / miss
                    r["text"] = (
                        f"{broker} has {miss:g} more shares than the portfolio: they must "
                        f"have been BOUGHT without being recorded. From the broker's average "
                        f"cost they cost about {r['implied']:.2f} kr per share "
                        f"({implied_total:.0f} kr in total) - an estimate: if they were bought "
                        f"in several periods this is the average. Use 'Add missing "
                        f"purchase...' and set the date.")
                else:
                    r["text"] = (
                        f"{broker} has {miss:g} more shares than the portfolio, but the "
                        f"broker's average cost leaves no money for them "
                        f"({implied_total:.0f} kr) - so a SALE is probably missing too, or "
                        f"some purchase price is wrong. Look up the purchases at {broker}.")
        elif qty and b_gav and abs(b_gav - gav) >= 0.02:
            extra = (b_gav - gav) * qty
            r["status"] = "gav"
            r["short"] = f"≈ avg cost {gav:.2f} vs {b_gav:.2f}"
            r["text"] = (
                f"The shares match, but the average cost differs: {broker} {b_gav:.2f}, "
                f"portfolio {gav:.2f} - {extra:+.0f} kr in total. Usual causes: brokerage "
                f"missing on a purchase (see 'without brokerage' in the By account tab), "
                f"a price that was typed in, or an old sale/purchase that differs.")
        return r

    def _reconcile_add_dialog(self, parent, acc, ticker, kind, shares, price_default, done):
        """Add the trade the comparison found to be missing."""
        d = tk.Toplevel(parent, bg=C_BG3)
        d.title("Add missing sale" if kind == "SELL" else "Add missing purchase")
        init_dialog(d, parent)
        name = self.pf.company_for(ticker, self.prices)
        tk.Label(d, text=f"{'Sale' if kind == 'SELL' else 'Purchase'}: {name}",
                 bg=C_BG3, fg=C_ACCENT, font=("Segoe UI", 13, "bold")).pack(padx=16, pady=(12, 2))
        tk.Label(d, text=self._overview_label(acc), bg=C_BG3, fg=C_FG_DIM,
                 font=FONT).pack()
        form = tk.Frame(d, bg=C_BG3)
        form.pack(padx=16, pady=10)
        ents = {}
        for r_, (lab, val) in enumerate((("Date (YYYY-MM-DD)", today_str()),
                                         ("Shares", f"{shares:g}"),
                                         ("Price per share", price_default))):
            tk.Label(form, text=lab, bg=C_BG3, fg=C_FG, font=FONT, width=18,
                     anchor="w").grid(row=r_, column=0, pady=3)
            e = mk_entry(form, width=16, bg=C_BG2, fg=C_FG, insertbackground=C_FG,
                         relief="flat", font=FONT)
            e.insert(0, val)
            e.grid(row=r_, column=1, pady=3)
            ents[lab] = e
        hint = ("The price is not known to the program - find it in the broker's "
                "transaction list and type it here." if kind == "SELL" else
                "The price is the estimate from the broker's average cost - change it "
                "if you know the real one.")
        res = tk.Label(d, text=hint, bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                       wraplength=380, justify="left")
        res.pack(padx=16)

        def ok():
            date = parse_sheet_date(ents["Date (YYYY-MM-DD)"].get().strip())
            sh = to_float(ents["Shares"].get())
            pr = to_float(ents["Price per share"].get())
            if not date:
                res.config(text="The date must look like 2026-11-24.", fg=C_BAD)
                return
            if not sh or sh <= 0:
                res.config(text="Type the number of shares.", fg=C_BAD)
                return
            if not pr or pr <= 0:
                res.config(text="A price is needed - look it up at the broker first.",
                           fg=C_BAD)
                return
            self.pf.transactions.append({
                "id": self.pf._new_id() + str(len(self.pf.transactions)),
                "ticker": ticker, "company": self.pf._company_name(ticker), "account": acc,
                "type": kind, "date": date, "shares": sh, "price": pr, "courtage": 0.0,
                "isin": self.isin_of(ticker),
                "note": "pasted (reconcile) - added by comparing with the broker's holdings",
                "verified": False, "ref": "reconcile"})
            self.pf.save()
            self.after_data_change()
            d.destroy()
            done()
            flash_ok(self.root, "Added")
        bb = tk.Frame(d, bg=C_BG3)
        bb.pack(pady=10)
        self._btn(bb, "Add", ok, BTN_DIALOG_OK).pack(side="left", padx=6)
        self._btn(bb, "Cancel", d.destroy, BTN_DIALOG_CANCEL).pack(side="left", padx=6)

    def open_broker_check(self, account=None):
        """Type in (or paste) what the broker's own holdings list says and see
        what the portfolio is missing."""
        accs = sorted({t.get("account", "") for t in self.pf.transactions
                       if t.get("account")}, key=self._acc_sort_key)
        if not accs:
            messagebox.showinfo(APP_NAME, "There are no accounts yet.")
            return
        labels = {self._overview_label(a): a for a in accs}
        if account is None:                       # take the account selected in the tab
            sel = self.atree.selection() if hasattr(self, "atree") else ()
            if sel and sel[0][:2] in ("A:", "H:"):
                account = sel[0][2:].split("||")[0]
        start = next((lab for lab, a in labels.items() if a == account), next(iter(labels)))
        names = {}
        for tk_ in self.pf.tickers():
            names[self.pf.company_for(tk_, self.prices)] = tk_
        name_of = {v: k for k, v in names.items()}

        top = tk.Toplevel(self.root, bg=C_BG3)
        top.title("Check against broker")
        init_dialog(top, self.root)
        top.geometry("1020x760")
        tk.Label(top, text="Check against broker", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 14, "bold")).pack(pady=(12, 0))
        tk.Label(top, text="Copy the holdings from the broker (company, shares, average cost) "
                 "or type them in. The program shows what does not match - sales or "
                 "purchases the statements did not bring.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                 wraplength=960).pack()

        store = {a: {tk_: {"shares": float(s.get("shares", 0)), "gav": float(s.get("gav", 0))}
                     for tk_, s in self.pf.broker_checks.get(a, {}).items()} for a in accs}
        v_acc = tk.StringVar(value=start)
        v_complete = tk.BooleanVar(value=False)
        bar = tk.Frame(top, bg=C_BG3)
        bar.pack(fill="x", padx=14, pady=(8, 2))
        tk.Label(bar, text="Account:", bg=C_BG3, fg=C_FG, font=FONT_B).pack(side="left")
        om = tk.OptionMenu(bar, v_acc, *labels.keys())
        om.configure(bg=C_BG2, fg=C_FG, activebackground=C_SEP, highlightthickness=0,
                     relief="flat", font=FONT)
        om["menu"].configure(bg=C_BG2, fg=C_FG)
        om.pack(side="left", padx=6)
        tk.Checkbutton(bar, text="This is the COMPLETE list for the account (anything I have "
                       "that is not in it counts as 0 at the broker)",
                       variable=v_complete, bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG3, font=("Segoe UI", 8),
                       highlightthickness=0).pack(side="left", padx=10)

        txt = mk_text(top, height=6, bg=C_BG2, fg=C_FG, insertbackground=C_FG,
                      relief="flat", font=FONT_MONO, wrap="word")
        txt.pack(fill="x", padx=14, pady=4)
        msg = tk.Label(top, text="", bg=C_BG3, fg=C_FG_DIM, font=FONT, wraplength=960,
                       justify="left", anchor="w")

        cols = ("company", "b_sh", "b_gav", "o_sh", "o_gav", "verdict")
        wrap = tk.Frame(top, bg=C_BG3)
        wrap.pack(fill="both", expand=True, padx=14, pady=4)
        tree = ttk.Treeview(wrap, columns=cols, show="headings", selectmode="browse", height=8)
        for c, t, w in (("company", "Company", 260), ("b_sh", "Broker shares", 100),
                        ("b_gav", "Broker avg cost", 105), ("o_sh", "Our shares", 90),
                        ("o_gav", "Our avg cost", 100), ("verdict", "Result", 260)):
            tree.heading(c, text=t)
            tree.column(c, width=w, anchor="w" if c in ("company", "verdict") else "e")
        vs = ttk.Scrollbar(wrap, orient="vertical", command=tree.yview)
        tree.configure(yscrollcommand=vs.set)
        tree.pack(side="left", fill="both", expand=True)
        vs.pack(side="right", fill="y")
        bind_mousewheel(tree)
        tree.tag_configure("ok", foreground=C_GOOD)
        tree.tag_configure("bad", foreground=C_BAD)
        tree.tag_configure("gav", foreground=C_WARN)

        # manual entry of one company
        ef = tk.Frame(top, bg=C_BG3)
        ef.pack(fill="x", padx=14, pady=2)
        v_co = tk.StringVar(value=sorted(names, key=str.casefold)[0] if names else "")
        tk.Label(ef, text="Company", bg=C_BG3, fg=C_FG, font=FONT).pack(side="left")
        com = tk.OptionMenu(ef, v_co, *(sorted(names, key=str.casefold) or [""]))
        com.configure(bg=C_BG2, fg=C_FG, activebackground=C_SEP, highlightthickness=0,
                      relief="flat", font=FONT, width=28)
        com["menu"].configure(bg=C_BG2, fg=C_FG)
        com.pack(side="left", padx=6)
        tk.Label(ef, text="I have", bg=C_BG3, fg=C_FG, font=FONT).pack(side="left")
        e_sh = mk_entry(ef, width=9, bg=C_BG2, fg=C_FG, insertbackground=C_FG,
                        relief="flat", font=FONT)
        e_sh.pack(side="left", padx=4)
        tk.Label(ef, text="avg cost (GAV)", bg=C_BG3, fg=C_FG, font=FONT).pack(side="left")
        e_gav = mk_entry(ef, width=9, bg=C_BG2, fg=C_FG, insertbackground=C_FG,
                         relief="flat", font=FONT)
        e_gav.pack(side="left", padx=4)

        detail = tk.Label(top, text="", bg=C_BG3, fg=C_FG, font=FONT, wraplength=960,
                          justify="left", anchor="nw", height=4)
        detail.pack(fill="x", padx=14, pady=(4, 0))
        msg.pack(fill="x", padx=14)

        def cur():
            return labels[v_acc.get()]

        def rows_for_view():
            """stored rows + (when complete) the held companies not in them, as 0."""
            acc = cur()
            rows = dict(store[acc])
            if v_complete.get():
                key = self._norm_account(acc)
                for h in self.pf.holdings():
                    if self._norm_account(h["account"]) == key and h["ticker"] not in rows:
                        rows[h["ticker"]] = {"shares": 0.0, "gav": 0.0}
            return rows

        results = {}

        def recalc():
            sel = tree.selection()
            tree.delete(*tree.get_children())
            results.clear()
            acc = cur()
            for tk_, v in sorted(rows_for_view().items(),
                                 key=lambda kv: self.pf.company_for(kv[0], self.prices).casefold()):
                r = self._reconcile(acc, tk_, v["shares"], v["gav"])
                results[tk_] = r
                tag = {"ok": "ok", "gav": "gav"}.get(r["status"], "bad")
                tree.insert("", "end", iid=tk_, tags=(tag,), values=(
                    self.pf.company_for(tk_, self.prices), fnum(v["shares"], 0),
                    fnum(v["gav"]) if v["gav"] else "-", fnum(r["qty"], 0),
                    fnum(r["gav"]) if r["qty"] else "-", r["short"]))
            if sel and tree.exists(sel[0]):
                tree.selection_set(sel[0])
            on_select()

        def on_select(event=None):
            sel = tree.selection()
            if not sel:
                detail.config(text="Select a row to see what it means.")
                b_sale.config(state="disabled")
                b_buy.config(state="disabled")
                return
            tk_ = sel[0]
            r = results.get(tk_)
            v = rows_for_view().get(tk_, {})
            detail.config(text=r["text"] if r else "")
            e_sh.delete(0, "end")
            e_sh.insert(0, f"{v.get('shares', 0):g}")
            e_gav.delete(0, "end")
            e_gav.insert(0, f"{v.get('gav', 0):g}" if v.get("gav") else "")
            if tk_ in name_of:
                v_co.set(name_of[tk_])
            b_sale.config(state="normal" if r and r["status"] == "sold" else "disabled")
            b_buy.config(state="normal" if r and r["status"] == "bought" else "disabled")

        def read_text():
            found = parse_holdings_paste(txt.get("1.0", "end"))
            if not found:
                msg.config(text="Found no holdings in that text. Copy the rows of the "
                                "holdings list (company, currency, shares, average cost ...).",
                           fg=C_BAD)
                return
            bad = []
            for f in found:
                tk_ = self._match_ticker_by_name(f["name"], cur(), "SELL")
                if not tk_:
                    bad.append(f["name"])
                    continue
                store[cur()][tk_] = {"shares": f["shares"], "gav": f["gav"]}
            recalc()
            msg.config(text=(f"Read {len(found) - len(bad)} companies."
                             + (f"  No clear match for: {', '.join(bad)} - add them with the "
                                f"Company box below (or import a statement that mentions them)."
                                if bad else "")),
                       fg=C_WARN if bad else C_ACCENT)

        def from_clip():
            try:
                txt.delete("1.0", "end")
                txt.insert("1.0", top.clipboard_get())
            except Exception:
                msg.config(text="The clipboard has no text.", fg=C_BAD)
                return
            read_text()

        def set_row():
            tk_ = names.get(v_co.get())
            sh = to_float(e_sh.get())
            gav = to_float(e_gav.get()) or 0.0
            if not tk_ or sh is None or sh < 0:
                msg.config(text="Pick a company and type how many shares you have.", fg=C_BAD)
                return
            store[cur()][tk_] = {"shares": sh, "gav": gav}
            tree.selection_set(tk_) if tree.exists(tk_) else None
            recalc()
            if tree.exists(tk_):
                tree.selection_set(tk_)
            msg.config(text="", fg=C_FG_DIM)

        def remove_row():
            sel = tree.selection()
            if sel and sel[0] in store[cur()]:
                del store[cur()][sel[0]]
                recalc()

        def add_trade(kind):
            sel = tree.selection()
            if not sel:
                return
            tk_ = sel[0]
            r = results.get(tk_)
            if not r:
                return
            shares = abs(r["diff"])
            price = f"{r['implied']:.2f}" if (kind == "BUY" and r["implied"]) else ""
            self._reconcile_add_dialog(top, cur(), tk_, kind, shares, price, recalc)

        def save_check():
            acc = cur()
            snap = {}
            for tk_, v in rows_for_view().items():
                snap[tk_] = {"shares": v["shares"], "gav": v["gav"], "date": today_str()}
            self.pf.broker_checks[acc] = snap
            self.pf.save()
            self.after_data_change()
            flash_ok(self.root, "Broker check saved")

        def clear_check():
            acc = cur()
            self.pf.broker_checks.pop(acc, None)
            store[acc] = {}
            self.pf.save()
            self.after_data_change()
            recalc()
            msg.config(text="The saved check for this account was removed.", fg=C_FG_DIM)

        btn1 = tk.Frame(top, bg=C_BG3)
        btn1.pack(pady=(2, 0))
        self._btn(btn1, "Paste from clipboard", from_clip, BTN_REFRESH).pack(side="left", padx=4)
        self._btn(btn1, "Read text above", read_text, BTN_REFRESH).pack(side="left", padx=4)
        self._btn(btn1, "Set row", set_row, BTN_DIALOG_OK).pack(side="left", padx=4)
        self._btn(btn1, "Remove row", remove_row, BTN_REFRESH).pack(side="left", padx=4)
        btn2 = tk.Frame(top, bg=C_BG3)
        btn2.pack(pady=4)
        b_sale = self._btn(btn2, "Add missing sale...", lambda: add_trade("SELL"), BTN_EDIT)
        b_sale.pack(side="left", padx=4)
        b_buy = self._btn(btn2, "Add missing purchase...", lambda: add_trade("BUY"), BTN_EDIT)
        b_buy.pack(side="left", padx=4)
        self._btn(btn2, "Save this check", save_check, BTN_DIALOG_OK).pack(side="left", padx=14)
        self._btn(btn2, "Clear saved check", clear_check, BTN_REFRESH).pack(side="left", padx=4)
        self._btn(btn2, "Close", top.destroy, BTN_DIALOG_CANCEL).pack(side="left", padx=4)

        tree.bind("<<TreeviewSelect>>", on_select)
        v_acc.trace_add("write", lambda *a: (msg.config(text=""), recalc()))
        v_complete.trace_add("write", lambda *a: recalc())
        recalc()

    _PERSON_HINT = "Merged by default - 'N, OA' = held in both. Double-click a row to open the company."
    _PERSON_HINT_ASSUMED = ("'~' = includes ASSUMED payouts (calendar x shares held); "
                            "recorded ones are unchanged.")

    def assumed_dividends(self):
        """{(ticker, account): kronor} the dividend CALENDAR says was paid but
        that no imported statement has proven.

        The assumption is deliberately naive: nothing was bought or sold that
        the portfolio does not already know about, so every calendar event
        from the first purchase up to today paid  per_share x the quantity
        held that day (= the CURRENT quantity unless a recorded trade changed
        it since - shares bought in August did not get the July payout).
        Nothing stored is changed - recorded (imported) payouts stay exactly as they are and a
        calendar event within 10 days of a recorded payout on the same
        account is taken to BE that payout, so it is never counted twice.

        Calendar = every stored event with a per-share amount.  If the company
        has an explicit frequency (instrument setting or a 'Bolag: Kvartalsvis'
        note), holes in the series up to today are filled too - e.g. a June
        payout that was never stored because the forecast import only adds
        future dates.  Without an explicit frequency nothing is guessed.
        """
        today = _dt.date.today()
        step_for = {"Monthly": 1, "Quarterly": 3, "Semi-annual": 6,
                    "Annual": 12, "Yearly": 12}
        items, proven, trades = {}, {}, {}
        for d in self.pf.dividends:
            dd = parse_date(d.get("date", ""))
            if not dd:
                continue
            if d.get("per_share"):
                items.setdefault(d["ticker"], []).append((dd, float(d["per_share"]), d))
            if d.get("amount") is not None and d.get("account"):
                proven.setdefault((d["ticker"], d["account"]), []).append(dd)
        for t in self.pf.transactions:
            td = parse_date(t.get("date", ""))
            if td:
                sh = float(t.get("shares", 0))
                trades.setdefault((t["ticker"], t.get("account", "")), []).append(
                    (td, sh if t.get("type", "BUY") == "BUY" else -sh))

        series = {}
        for ticker, its in items.items():
            its.sort(key=lambda x: x[0])
            step = step_for.get(self.pf.instruments.get(ticker, {}).get("freq", ""))
            if not step:
                for _dd, _ps, d in its:
                    note = str(d.get("note", ""))
                    if ":" in note:
                        step = recognize_frequency(note.split(":", 1)[1])
                        if step:
                            break
            pts = []
            for i, (dd, ps, _d) in enumerate(its):
                pts.append((dd, ps))
                if not step:
                    continue
                nxt = its[i + 1][0] if i + 1 < len(its) else None
                cur = add_months(dd, step)
                guard = 0
                while (cur <= today and guard < 60
                       and (nxt is None or (nxt - cur).days >= step * 15)):
                    pts.append((cur, ps))        # hole in the series -> assumed event
                    cur = add_months(cur, step)
                    guard += 1
            series[ticker] = pts

        res = {}
        for h in self.pf.holdings():
            key = (h["ticker"], h["account"])
            tot = 0.0
            for dd, ps in series.get(h["ticker"], []):
                if dd > today:
                    continue
                if any(abs((dd - p).days) <= 10 for p in proven.get(key, [])):
                    continue                     # proven by a statement - leave it alone
                qty = sum(dl for td, dl in trades.get(key, []) if td < dd)
                if qty > 0:
                    tot += ps * qty
            if tot:
                res[key] = tot
        return res

    def _on_incl_sold_toggle(self):
        """'Include dividends from sold stocks' only makes sense together
        with 'Include sold' - grey it out otherwise.

        Turning 'Include sold' ON turns the dividend half ON as well: a closed
        position is realized loss AND the payouts it made while it was open,
        and showing only the loss half is the misleading answer, not the safe
        one.  Untick it afterwards if you really want the loss alone.
        """
        on = self.incl_sold.get()
        self.chk_sold_div.config(state=("normal" if on else "disabled"))
        self.incl_sold_div.set(on)
        self.refresh_person_view()

    def _rebuild_person_filters(self):
        hs = self.pf.holdings()
        owners = sorted(set(self.owner_of(h["account"]) for h in hs))
        accts = sorted(set(h["account"] for h in hs))
        self._person_acct_labelmap = {self.account_label(a): a for a in accts}
        companies = sorted(set(self.pf.company_for(h["ticker"], self.prices) for h in hs))
        self._set_menu(self.owner_menu, self.f_owner, ["All"] + owners)
        self._set_menu(self.acct_menu, self.f_acct, ["All"] + list(self._person_acct_labelmap.keys()))
        self._set_menu(self.company_menu, self.f_company, ["All"] + companies)

    def refresh_person_view(self):
        if not hasattr(self, "ptree"):
            return
        self._rebuild_person_filters()
        self.ptree.delete(*self.ptree.get_children())
        sep = self.sep_acct.get()
        incl_sold = self.incl_sold.get()
        incl_sold_div = incl_sold and self.incl_sold_div.get()
        f_owner, f_co = self.f_owner.get(), self.f_company.get()
        f_acc = self._person_acct_labelmap.get(self.f_acct.get())   # key or None=All
        div_recv = self.dividends_received()
        assumed = self.assumed_dividends() if self.assume_div.get() else {}
        self.person_hint.config(text=self._PERSON_HINT_ASSUMED if assumed
                                else self._PERSON_HINT)

        def money(v, a=0.0):
            return (fnum(v) if v else "0") + (" ~" if a else "")

        def keep(owner, acc, company):
            return ((f_owner == "All" or owner == f_owner)
                    and (f_acc is None or acc == f_acc)
                    and (f_co == "All" or company == f_co))

        # held holdings -> owner -> group
        people = {}
        for h in self.pf.holdings():
            acc = h["account"]
            owner = self.owner_of(acc)
            company = self.pf.company_for(h["ticker"], self.prices)
            if not keep(owner, acc, company):
                continue
            price = self.active_price(h["ticker"])
            value = price * h["qty"] if price is not None else 0.0
            pl = value - h["cost"] if price is not None else 0.0
            dr = div_recv.get((h["ticker"], acc), 0.0)
            da = assumed.get((h["ticker"], acc), 0.0)    # calendar-only, never proven
            net = pl + dr + da + h.get("realized", 0.0)
            gk = (h["ticker"], acc) if sep else (h["ticker"],)
            g = people.setdefault(owner, {}).setdefault(gk, {
                "company": company, "ticker": h["ticker"], "accs": set(),
                "qty": 0.0, "cost": 0.0, "value": 0.0, "pl": 0.0, "div": 0.0, "net": 0.0,
                "assumed": 0.0})
            g["accs"].add(acc)
            for f in ("qty", "cost", "value", "pl", "div", "net", "assumed"):
                g[f] += {"qty": h["qty"], "cost": h["cost"], "value": value,
                         "pl": pl, "div": dr + da, "net": net, "assumed": da}[f]

        # closed positions per owner (for Include sold)
        closed = {}
        if incl_sold:
            # The exact (ticker, account) pairs that are still open.  A sell on
            # an account that still holds shares of the same ticker is a PART
            # sale of a live position - it stays inside that holding's own
            # h["realized"] and gets no row of its own.
            held_pairs = set()
            for h in self.pf.holdings():
                held_pairs.add((h["ticker"], h["account"]))
            # Group key for a CLOSED position: with the accounts merged, all of
            # one owner's closed accounts of a ticker share one grey row, but a
            # closed position NEVER merges into a held one - a position that is
            # gone has no shares, no cost and no value, so folding its realised
            # profit into a live holding just hides both numbers.  Closed rows
            # therefore live in their own dict, always separate from `people`.
            for s in self.pf.realized_sales():
                owner = self.owner_of(s["account"])
                company = self.pf.company_for(s["ticker"], self.prices)
                if not keep(owner, s["account"], company):
                    continue
                pair = (s["ticker"], s["account"])
                if pair in held_pairs:
                    continue        # this account still holds it -> h["realized"]
                gk = (s["ticker"], s["account"]) if sep else (s["ticker"],)
                g = closed.setdefault(owner, {}).setdefault(gk, {
                    "company": company, "ticker": s["ticker"], "accs": set(),
                    "qty": 0.0, "realized": 0.0, "div": 0.0})
                g["accs"].add(s["account"])
                g["qty"] += s["qty"]
                g["realized"] += s["realized"]
            if incl_sold_div:
                # dividends received while the position was open don't belong
                # to "held" any more once it's fully closed - add them here
                # instead, so they aren't shown as 0 nor double-counted.
                for groups in closed.values():
                    for g in groups.values():
                        for acc in g["accs"]:
                            g["div"] += div_recv.get((g["ticker"], acc), 0.0)

        owners = sorted(set(people) | set(closed))
        gv = gpl = gnet = ginv = gdiv = gass = 0.0
        for pidx, owner in enumerate(owners):
            # subtle per-person SECTION background (whole block), keeping gain/loss colors
            shade = PERSON_SHADES[pidx % len(PERSON_SHADES)]
            th, tg, tl, ts = f"p{pidx}h", f"p{pidx}g", f"p{pidx}l", f"p{pidx}s"
            self.ptree.tag_configure(th, background=shade, foreground=C_ACCENT, font=FONT_B)
            self.ptree.tag_configure(tg, background=shade, foreground=C_GOOD)
            self.ptree.tag_configure(tl, background=shade, foreground=C_BAD)
            self.ptree.tag_configure(ts, background=shade, foreground=C_FG_DIM)
            pv = ppl = pnet = pinv = pdiv = pass_ = 0.0
            pnode = self.ptree.insert("", "end", text=f"👤 {owner}", open=True,
                                      tags=(th,), values=("", "", "", "", "", "", "", ""))
            for gk in sorted(people.get(owner, {}),
                             key=lambda k: people[owner][k]["company"].lower()):
                g = people[owner][gk]
                gav = g["cost"] / g["qty"] if g["qty"] else 0.0
                accs = ", ".join(sorted(self.code_of(a) for a in g["accs"]))
                iid = (("H:" + next(iter(g["accs"])) + "||" + g["ticker"]) if sep
                       else ("C:" + owner + "||" + g["ticker"]))
                self.ptree.insert(pnode, "end", iid=iid, text="   " + g["company"],
                                  values=(accs, fnum(g["qty"], 0), fnum(gav),
                                          fnum(g["cost"]), fnum(g["value"]), fnum(g["pl"]),
                                          fnum(g["net"]), money(g["div"], g["assumed"])),
                                  tags=(tg if g["net"] >= 0 else tl,))
                pv += g["value"]; ppl += g["pl"]; pnet += g["net"]; pinv += g["cost"]; pdiv += g["div"]
                pass_ += g["assumed"]
            for gk in sorted(closed.get(owner, {}),
                             key=lambda k: closed[owner][k]["company"].lower()):
                g = closed[owner][gk]
                accs = ", ".join(sorted(self.code_of(a) for a in g["accs"]))
                g_div = g.get("div", 0.0)
                net_closed = g["realized"] + g_div
                iid = (("S:" + next(iter(g["accs"])) + "||" + g["ticker"]) if sep
                       else ("S:" + owner + "||" + g["ticker"]))
                self.ptree.insert(pnode, "end", iid=iid,
                                  text="   " + g["company"] + "  (sold)",
                                  values=(accs, fnum(g["qty"], 0), "", "", "", "",
                                          fnum(net_closed),
                                          money(g_div) if incl_sold_div else ""), tags=(ts,))
                pnet += net_closed
                pdiv += g_div
            self.ptree.item(pnode, values=("", "", "", fnum(pinv), fnum(pv),
                                           fnum(ppl), fnum(pnet), money(pdiv, pass_)))
            gv += pv; gpl += ppl; gnet += pnet; ginv += pinv; gdiv += pdiv; gass += pass_
        self.ptree.insert("", "end", text="TOTAL",
                          values=("", "", "", fnum(ginv), fnum(gv), fnum(gpl),
                                  fnum(gnet), money(gdiv, gass)), tags=("total",))

    def _person_detail(self, event=None):
        sel = self.ptree.selection()
        if not sel:
            return
        node = sel[0]
        if node.startswith("H:"):
            acc, ticker = node[2:].split("||", 1)
            self._show_company(ticker, account=acc)
        elif node.startswith("C:"):
            _owner, ticker = node[2:].split("||", 1)
            self._show_company(ticker)
        elif node.startswith("S:"):          # a closed "(sold)" row
            _who, ticker = node[2:].split("||", 1)
            self._show_company(ticker)

    def _build_dividend_tab(self):
        frame = tk.Frame(self.nb, bg=C_BG)
        self.nb.add(frame, text="  Dividend calendar  ")

        # "account" sits AFTER "ticker" so ticker stays column index 3
        # (_div_to_company reads vals[3]).
        cols = ("date", "in_days", "company", "ticker", "account", "per_share",
                "shares", "total", "note")
        heads = {"date": "Date", "in_days": "In (days)", "company": "Company",
                 "ticker": "Ticker", "account": "Account", "per_share": "Per share",
                 "shares": "Shares", "total": "Total payout", "note": "Note"}
        widths = {"date": 100, "in_days": 80, "company": 190, "ticker": 90,
                  "account": 125, "per_share": 90, "shares": 80,
                  "total": 110, "note": 160}
        wrap = tk.Frame(frame, bg=C_BG)
        wrap.pack(fill="both", expand=True)
        self.divtree = ttk.Treeview(wrap, columns=cols, show="headings", selectmode="browse")
        for c in cols:
            anchor = "w" if c in ("company", "ticker", "account", "note") else "e"
            self.divtree.heading(c, text=heads[c])
            self.divtree.column(c, width=widths[c], anchor=anchor,
                                stretch=(c == "note"))
        vs = ttk.Scrollbar(wrap, orient="vertical", command=self.divtree.yview)
        self.divtree.configure(yscrollcommand=vs.set)
        self.divtree.pack(side="left", fill="both", expand=True)
        vs.pack(side="right", fill="y")
        bind_mousewheel(self.divtree)
        self.divtree.tag_configure("soon", background="#3a3320", foreground=C_WARN)
        self.divtree.tag_configure("past", foreground=C_FG_DIM)
        self.divtree.tag_configure("expected", foreground="#7fa8d0")      # projected (blue)
        self.divtree.tag_configure("unknown", foreground=C_WARN)          # amount unknown
        self.divtree.tag_configure("total", background=C_BG3,
                                   foreground=C_ACCENT, font=FONT_B)
        tk.Label(frame, text="Black/white = recorded · blue = expected (from frequency) "
                 "· ? = amount not predictable yet. Double-click to open a company.",
                 bg=C_BG, fg=C_FG_DIM, font=("Segoe UI", 8, "italic")).pack(anchor="w", pady=(2, 0))
        self.divtree.bind("<Double-1>", self._div_to_company)

    def _div_to_company(self, event=None):
        sel = self.divtree.selection()
        if not sel:
            return
        vals = self.divtree.item(sel[0], "values")
        if vals and vals[3]:
            self._show_company(vals[3])

    def _build_sold_tab(self):
        frame = tk.Frame(self.nb, bg=C_BG)
        self.nb.add(frame, text="  Sold / realized  ")
        tk.Label(frame, text="Every sell with its realised profit/loss "
                 "(average-cost method, brokerage included)",
                 bg=C_BG, fg=C_FG_DIM, font=("Segoe UI", 8, "italic")).pack(anchor="w")
        cols = ("date", "owner", "account", "company", "qty", "price",
                "avg", "proceeds", "realized")
        heads = {"date": "Sold", "owner": "Owner", "account": "Broker",
                 "company": "Company", "qty": "Shares", "price": "Sell price",
                 "avg": "Avg cost", "proceeds": "Proceeds", "realized": "Realized +/-"}
        widths = {"date": 90, "owner": 75, "account": 95, "company": 180,
                  "qty": 70, "price": 80, "avg": 80, "proceeds": 100, "realized": 110}
        wrap = tk.Frame(frame, bg=C_BG)
        wrap.pack(fill="both", expand=True)
        self.soldtree = ttk.Treeview(wrap, columns=cols, show="headings", selectmode="browse")
        for c in cols:
            self.soldtree.heading(c, text=heads[c])
            self.soldtree.column(c, width=widths[c],
                                 anchor="w" if c in ("owner", "account", "company") else
                                 ("center" if c == "date" else "e"),
                                 stretch=(c == "company"))
        vs = ttk.Scrollbar(wrap, orient="vertical", command=self.soldtree.yview)
        self.soldtree.configure(yscrollcommand=vs.set)
        self.soldtree.pack(side="left", fill="both", expand=True)
        vs.pack(side="right", fill="y")
        bind_mousewheel(self.soldtree)
        self.soldtree.tag_configure("gain", foreground=C_GOOD)
        self.soldtree.tag_configure("loss", foreground=C_BAD)
        self.soldtree.tag_configure("total", background=C_BG3, foreground=C_ACCENT, font=FONT_B)
        self.soldtree.bind("<Double-1>", lambda e: self._sold_to_company())

    def _sold_to_company(self):
        """Double-click a sale: popup with every purchase, sale and dividend of
        that company on that sale's account."""
        sel = self.soldtree.selection()
        if not sel:
            return
        info = getattr(self, "_sold_map", {}).get(sel[0])
        if info:                              # the TOTAL row has no entry
            self._show_trade_detail(info[0], info[1])

    def refresh_sold_view(self):
        if not hasattr(self, "soldtree"):
            return
        self.soldtree.delete(*self.soldtree.get_children())
        sales = self.pf.realized_sales()
        sales.sort(key=lambda x: x.get("date", ""), reverse=True)
        tot = 0.0
        self._sold_map = {}
        for i, s in enumerate(sales):
            tag = "gain" if s["realized"] >= 0 else "loss"
            self._sold_map[f"s{i}"] = (s["ticker"], s["account"])
            self.soldtree.insert("", "end", iid=f"s{i}", values=(
                s["date"], self.owner_of(s["account"]), self.broker_display(s["account"]),
                self.pf.company_for(s["ticker"], self.prices), fnum(s["qty"], 0),
                fnum(s["price"]), fnum(s["avg"]), fnum(s["proceeds"]),
                fnum(s["realized"])), tags=(tag,))
            tot += s["realized"]
        self.soldtree.insert("", "end", values=(
            "TOTAL", "", "", "", "", "", "", "", fnum(tot)), tags=("total",))

    # ---- status bar ----
    def _build_statusbar(self):
        self.status = tk.Frame(self.root, bg=C_BG2)
        self.status.pack(fill="x", side="bottom")
        self.warn_lbl = tk.Label(self.status, text="", bg=C_BG2, fg=C_WARN,
                                 font=FONT_B, anchor="w")
        self.warn_lbl.pack(side="left", padx=10, pady=4)
        self.status_lbl = tk.Label(self.status, text="", bg=C_BG2, fg=C_FG_DIM,
                                   font=FONT, anchor="e")
        self.status_lbl.pack(side="right", padx=10, pady=4)

    def set_status(self, text):
        self.status_lbl.config(text=text)

    # ---- account metadata helpers ----
    def owner_of(self, account):
        m = self.account_meta.get(account, {})
        return m.get("owner") or account or "(unassigned)"

    def broker_of(self, account):
        return self.account_meta.get(account, {}).get("broker", "")

    def broker_display(self, account):
        """What to show in the Broker column (broker, else the raw key)."""
        return self.broker_of(account) or account

    def code_of(self, account):
        """Short account code (e.g. N, OA) for the Accounts column."""
        m = self.account_meta.get(account, {})
        return (m.get("code") or "").strip() or self.broker_of(account) or account

    def account_label(self, account):
        """Combined 'Owner (Broker)' label, with sensible fallbacks."""
        m = self.account_meta.get(account, {})
        owner = (m.get("owner") or "").strip()
        broker = (m.get("broker") or "").strip()
        if owner and broker:
            return f"{owner} ({broker})"
        return owner or broker or account

    def account_short(self, account):
        """Compact but UNIQUE account label - 'Owner (code)'.

        account_label() is not precise enough wherever one row per account is
        shown: two different accounts with the same owner AND the same broker
        (e.g. an ISK and a capital-insurance account at the same bank) both
        render as "Lars (Avanza)".  The short account code separates them, and
        if no code is set we fall back to the raw account name, which is
        unique by definition.
        """
        a = (account or "").strip()
        m = self.account_meta.get(a, {})
        owner = (m.get("owner") or "").strip()
        code = (m.get("code") or "").strip()
        if owner and code:
            return f"{owner} ({code})"
        return a or owner

    def active_price(self, ticker):
        """Price from the chosen source, falling back to the other."""
        y = self.prices.get(ticker, {}).get("price")
        g = self.sheet_prices.get(ticker, {}).get("price")
        if self.price_source == "gsheet":
            return g if g is not None else y
        return y if y is not None else g

    def dividends_received(self):
        """{(ticker, account): total received} from imported dividends (have amount)."""
        res = {}
        for d in self.pf.dividends:
            amt = d.get("amount")
            acc = d.get("account")
            if amt is None or not acc:
                continue
            key = (d["ticker"], acc)
            res[key] = res.get(key, 0.0) + float(amt)
        return res

    def all_accounts(self):
        """Accounts from settings plus any seen in transactions."""
        seen = list(self.accounts)
        for t in self.pf.transactions:
            a = t.get("account", "")
            if a and a not in seen:
                seen.append(a)
        return seen


# ============================================================================
#  DEL 12 .... PORTFOLIO TABLE POPULATION + SORTING
# ============================================================================
    def _holding_rows(self):
        """Build display rows with computed values from both price sources."""
        rows = []
        div_recv = self.dividends_received()
        for h in self.pf.holdings():
            tk_ = h["ticker"]
            yprice = self.prices.get(tk_, {}).get("price")
            yprev = self.prices.get(tk_, {}).get("prev")
            gprice = self.sheet_prices.get(tk_, {}).get("price")
            daypct = ((yprice - yprev) / yprev * 100
                      if (yprice is not None and yprev) else None)
            # the chosen source drives Value/PL; fall back to the other if missing
            if self.price_source == "gsheet":
                price = gprice if gprice is not None else yprice
            else:
                price = yprice if yprice is not None else gprice
            value = price * h["qty"] if price is not None else None
            pl = (value - h["cost"]) if value is not None else None
            plpct = (pl / h["cost"] * 100) if (pl is not None and h["cost"]) else None
            nd = self.pf.next_dividend(tk_)
            divdate = nd.get("date") if nd else None
            divsum = (float(nd.get("per_share", 0)) * h["qty"]) if nd else None
            dr = div_recv.get((tk_, h["account"]), 0.0)
            net = (pl + dr + h.get("realized", 0.0)) if pl is not None else None
            rows.append({
                "company": self.pf.company_for(tk_, self.prices),
                "ticker": tk_, "owner": self.owner_of(h["account"]),
                "account": h["account"], "qty": h["qty"],
                "gav": h["gav"], "invested": h["cost"], "price": yprice,
                "day": daypct, "gprice": gprice,
                "value": value, "pl": pl, "plpct": plpct, "net": net,
                "divdate": divdate, "divsum": divsum, "cost": h["cost"],
            })
        return rows

    def sort_by(self, col):
        if self.S.get("sort_col") == col:
            self.S["sort_desc"] = not self.S.get("sort_desc", True)
        else:
            self.S["sort_col"] = col
            self.S["sort_desc"] = True
        self.refresh_table()

    def refresh_table(self):
        self.tree.delete(*self.tree.get_children())
        rows = self._holding_rows()
        col = self.S.get("sort_col", "value")
        desc = self.S.get("sort_desc", True)

        def key(r):
            v = r.get(col)
            if isinstance(v, str) or v is None:
                return (v is None, (v or "").lower() if isinstance(v, str) else "")
            return (False, v)
        if col in ("company", "ticker", "owner", "account", "divdate"):
            rows.sort(key=lambda r: (r.get(col) is None, str(r.get(col) or "").lower()),
                      reverse=desc)
        else:
            rows.sort(key=lambda r: (r.get(col) is None, r.get(col) or 0),
                      reverse=desc)

        tot_val = tot_cost = tot_pl = tot_net = tot_inv = 0.0
        warn_days = int(self.S.get("warn_days", 14))
        today = _dt.date.today()
        for r in rows:
            tags = []
            if r["pl"] is not None:
                tags.append("gain" if r["pl"] >= 0 else "loss")
            dd = parse_date(r["divdate"]) if r["divdate"] else None
            if dd and 0 <= (dd - today).days <= warn_days:
                tags.append("warn")
            self.tree.insert("", "end", iid=r["ticker"] + "||" + r["account"], values=(
                r["company"], r["ticker"], r["owner"], self.broker_display(r["account"]),
                fnum(r["qty"], 0), fnum(r["gav"]), fnum(r["invested"]), fnum(r["price"]),
                (f"{r['day']:+.1f} %") if r["day"] is not None else "-",
                fnum(r["gprice"]), fnum(r["value"]),
                fnum(r["pl"]), (fnum(r["plpct"], 1) + " %") if r["plpct"] is not None else "-",
                fnum(r["net"]) if r["net"] is not None else "-",
                r["divdate"] or "-",
                fnum(r["divsum"]) if r["divsum"] is not None else "-",
            ), tags=tags)
            if r["value"] is not None:
                tot_val += r["value"]
                tot_cost += r["cost"]
            if r["pl"] is not None:
                tot_pl += r["pl"]
            if r["net"] is not None:
                tot_net += r["net"]
            tot_inv += r["invested"]
        tot_pct = (tot_pl / tot_cost * 100) if tot_cost else None
        self.tree.insert("", "end", iid="__total__", values=(
            "TOTAL", "", "", "", "", "", fnum(tot_inv), "", "", "",
            fnum(tot_val), fnum(tot_pl),
            (fnum(tot_pct, 1) + " %") if tot_pct is not None else "-",
            fnum(tot_net), "", ""),
            tags=("total",))
        self._update_sort_indicator()

    def _update_sort_indicator(self):
        names = {"company": "Company", "ticker": "Ticker", "owner": "Owner",
                 "account": "Broker", "qty": "Shares", "gav": "Avg cost",
                 "invested": "Invested", "price": "Yahoo", "day": "Day %",
                 "gprice": "Sheet", "value": "Value", "pl": "Price +/-",
                 "plpct": "G/L %", "net": "Net +/- (inc. div)",
                 "divdate": "Next div.", "divsum": "Div. amount"}
        # mark the active price source with a dot
        if self.price_source == "gsheet":
            names["gprice"] += " •"
        else:
            names["price"] += " •"
        arrow = " v" if self.S.get("sort_desc") else " ^"
        for c, n in names.items():
            self.tree.heading(c, text=n + (arrow if c == self.S.get("sort_col") else ""))

    def selected_ticker_account(self):
        sel = self.tree.selection()
        if not sel:
            return None
        iid = sel[0]
        if "||" not in iid:                 # TOTAL row or non-holding
            return None
        ticker, account = iid.split("||", 1)
        return ticker, account


# ============================================================================
#  DEL 13 .... DIVIDEND CALENDAR VIEW + WARNINGS
# ============================================================================
    def _inferred_per_share(self, ticker):
        """Return (per_share, consistent) from recent RECEIVED dividends."""
        vals = sorted([(d.get("date", ""), float(d["per_share"]))
                       for d in self.pf.dividends
                       if d["ticker"] == ticker and d.get("amount") and d.get("per_share")],
                      key=lambda x: x[0])
        ps = [v for _, v in vals][-4:]
        if not ps:
            return None, False
        lo, hi = min(ps), max(ps)
        consistent = (hi - lo) <= 0.20 * hi if hi else False
        return ps[-1], consistent

    def refresh_dividends_view(self):
        self.divtree.delete(*self.divtree.get_children())
        today = _dt.date.today()
        warn_days = int(self.S.get("warn_days", 14))
        held = {}
        for h in self.pf.holdings():
            held[h["ticker"]] = held.get(h["ticker"], 0) + h["qty"]

        rows = []   # (date_obj, values_tuple, tag, future_amount)
        existing = set()
        for d in self.pf.dividends:
            dd = parse_date(d.get("date", ""))
            if not dd:
                continue
            existing.add((d["ticker"], d["date"]))
            days = (dd - today).days
            # A RECEIVED dividend knows its own account, share count and amount -
            # use them.  Only a forecast (no amount) has to fall back on the
            # total number of shares currently held.
            if d.get("amount") is not None and d.get("account"):
                acc_txt = self.account_short(d["account"])
                sh = float(d.get("shares") or 0)
                total = float(d["amount"])
            else:
                acc_txt = ""
                sh = held.get(d["ticker"], 0)
                total = float(d.get("per_share", 0)) * sh
            tag = "past" if days < 0 else ("soon" if days <= warn_days else "")
            rows.append((dd, (d["date"], days if days >= 0 else f"{days}",
                         self.pf.company_for(d["ticker"], self.prices), d["ticker"],
                         acc_txt, fnum(d.get("per_share"), 2), fnum(sh, 0),
                         fnum(total), d.get("note", "")), tag,
                         total if days >= 0 else 0.0))

        # expected (projected) dividends from each held company's frequency
        step_for = {"Monthly": 1, "Quarterly": 3, "Semi-annual": 6, "Yearly": 12}
        horizon = today + _dt.timedelta(days=550)
        for ticker, sh in held.items():
            step = step_for.get(self.pf.instruments.get(ticker, {}).get("freq", ""))
            if not step or sh <= 0:
                continue
            kd = [parse_date(d["date"]) for d in self.pf.dividends if d["ticker"] == ticker]
            kd = [x for x in kd if x]
            anchor = max(kd) if kd else today
            ps, consistent = self._inferred_per_share(ticker)
            cur = add_months(anchor, step)
            guard = 0
            while cur <= horizon and guard < 30:
                guard += 1
                if cur >= today and (ticker, cur.isoformat()) not in existing:
                    if ps is not None and consistent:
                        amount = ps * sh
                        ps_s, am_s, tag = fnum(ps, 2), fnum(amount), "expected"
                    else:
                        amount, ps_s, am_s, tag = 0.0, "?", "?", "unknown"
                    rows.append((cur, (cur.isoformat(), (cur - today).days,
                                 self.pf.company_for(ticker, self.prices), ticker,
                                 "", ps_s, fnum(sh, 0), am_s, "expected"),
                                 tag, amount))
                cur = add_months(cur, step)

        rows.sort(key=lambda x: x[0])
        tot_future = 0.0
        for _dd, vals, tag, fut in rows:
            tot_future += fut
            self.divtree.insert("", "end", values=vals, tags=(tag,) if tag else ())
        self.divtree.insert("", "end", values=(
            "", "", "TOTAL upcoming (incl. expected)", "", "", "", "",
            fnum(tot_future), ""), tags=("total",))

    def update_warnings(self):
        today = _dt.date.today()
        warn_days = int(self.S.get("warn_days", 14))
        held = {h["ticker"] for h in self.pf.holdings()}
        soon = []
        for d in self.pf.dividends:
            if d["ticker"] not in held:
                continue
            dd = parse_date(d.get("date", ""))
            if dd and 0 <= (dd - today).days <= warn_days:
                soon.append((dd, d))
        soon.sort(key=lambda x: x[0])
        if soon:
            parts = []
            for dd, d in soon[:4]:
                days = (dd - today).days
                parts.append(f"{self.pf.company_for(d['ticker'], self.prices)} "
                             f"in {days}d ({d['date']})")
            self.warn_lbl.config(
                text="⚠  Upcoming dividend: " + "   |   ".join(parts))
        else:
            self.warn_lbl.config(text="")


# ============================================================================
#  DEL 14 .... ADD / EDIT / DELETE TRANSACTION DIALOG
# ============================================================================
    def add_transaction(self):
        self._transaction_dialog(None)

    def edit_transaction(self):
        ta = self.selected_ticker_account()
        if not ta:
            messagebox.showinfo(APP_NAME, "Select a holding first.")
            return
        # pick the transactions for this ticker+account to edit
        self._pick_transaction_dialog(ta[0], ta[1])

    def _pick_transaction_dialog(self, ticker, account):
        """List a holding's transactions (buys + sold history) to edit/delete."""
        all_txs = sorted([t for t in self.pf.transactions
                          if t["ticker"] == ticker and t.get("account", "") == account],
                         key=lambda x: x.get("date", ""))
        # realized P/L per sell, matched chronologically
        rsales = sorted([s for s in self.pf.realized_sales()
                         if s["ticker"] == ticker and s["account"] == account],
                        key=lambda x: x["date"])
        realized_for = {}
        ri = 0
        for t in all_txs:
            if t.get("type") == "SELL" and ri < len(rsales):
                realized_for[id(t)] = rsales[ri]["realized"]
                ri += 1

        top = tk.Toplevel(self.root, bg=C_BG3)
        top.title(f"Transactions - {ticker}")
        init_dialog(top, self.root)
        tk.Label(top, text=f"{self.pf.company_for(ticker, self.prices)}   -   "
                 f"{self.account_label(account)}",
                 bg=C_BG3, fg=C_ACCENT, font=FONT_B).pack(padx=14, pady=(12, 4))

        show_sold = tk.BooleanVar(value=True)
        tk.Checkbutton(top, text="Show sold history", variable=show_sold,
                       bg=C_BG3, fg=C_FG, selectcolor=C_BG2, activebackground=C_BG3,
                       font=FONT, highlightthickness=0).pack(anchor="w", padx=14)

        lst = tk.Listbox(top, width=68, height=12, bg=C_BG2, fg=C_FG,
                         font=FONT_MONO, selectbackground=C_SEP,
                         highlightthickness=0, bd=0, activestyle="none")
        lst.pack(padx=14, pady=4, fill="both", expand=True)
        shown = []

        def reload():
            lst.delete(0, "end")
            shown.clear()
            for t in all_txs:
                kind = t.get("type", "BUY")
                if kind == "SELL" and not show_sold.get():
                    continue
                if kind == "BUY":
                    line = f"BOUGHT  {t['date']}  {fnum(t['shares'],0):>7} @ {fnum(t['price'])}"
                else:
                    rz = realized_for.get(id(t))
                    rtxt = (f"   realized {rz:+,.0f}".replace(",", " ")) if rz is not None else ""
                    line = f"SOLD    {t['date']}  {fnum(t['shares'],0):>7} @ {fnum(t['price'])}{rtxt}"
                lst.insert("end", line)
                shown.append(t)
        reload()
        show_sold.trace_add("write", lambda *a: reload())

        btns = tk.Frame(top, bg=C_BG3)
        btns.pack(pady=10)

        def do_edit():
            i = lst.curselection()
            if not i:
                return
            top.destroy()
            self._transaction_dialog(shown[i[0]])

        def do_del():
            i = lst.curselection()
            if not i:
                return
            t = shown[i[0]]
            if messagebox.askyesno(APP_NAME, "Delete this transaction?"):
                self.pf.transactions = [x for x in self.pf.transactions
                                        if x.get("id") != t.get("id")]
                self.pf.save()
                top.destroy()
                self.after_data_change()
                flash_ok(self.root, "Deleted")
        self._btn(btns, "Edit", do_edit, BTN_EDIT).pack(side="left", padx=4)
        self._btn(btns, "Delete", do_del, BTN_DELETE).pack(side="left", padx=4)
        self._btn(btns, "Close", top.destroy, BTN_DIALOG_CANCEL).pack(side="left", padx=4)
        lst.bind("<Double-1>", lambda e: do_edit())
        lst.focus_set()

    def delete_transaction(self):
        ta = self.selected_ticker_account()
        if not ta:
            messagebox.showinfo(APP_NAME, "Select a holding first.")
            return
        self._pick_transaction_dialog(ta[0], ta[1])

    def _transaction_dialog(self, tx):
        """Add (tx=None) or edit an existing transaction."""
        top = tk.Toplevel(self.root, bg=C_BG3)
        top.title("Edit transaction" if tx else "Add transaction")
        init_dialog(top, self.root)

        form = tk.Frame(top, bg=C_BG3)
        form.pack(padx=16, pady=14)

        def row(r, label):
            tk.Label(form, text=label, bg=C_BG3, fg=C_FG, font=FONT,
                     anchor="w", width=16).grid(row=r, column=0, sticky="w", pady=4)

        # ticker
        row(0, "Ticker (Yahoo)")
        e_ticker = mk_entry(form, width=20, bg=C_BG2, fg=C_FG, insertbackground=C_FG,
                            font=FONT, relief="flat")
        e_ticker.grid(row=0, column=1, sticky="w")
        tk.Label(form, text=".ST for Stockholm, e.g. VOLV-B.ST",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8)).grid(row=0, column=2, padx=8)

        # company
        row(1, "Company")
        e_company = mk_entry(form, width=30, bg=C_BG2, fg=C_FG, insertbackground=C_FG,
                             font=FONT, relief="flat")
        e_company.grid(row=1, column=1, columnspan=2, sticky="w")

        # account  (type freely OR pick one of the configured accounts)
        row(2, "Account")
        e_account = mk_entry(form, width=20, bg=C_BG2, fg=C_FG, insertbackground=C_FG,
                             font=FONT, relief="flat")
        e_account.grid(row=2, column=1, sticky="w")
        acc_var = tk.StringVar(value="(pick)")
        _keys = sorted(set(t.get("account", "") for t in self.pf.transactions
                           if t.get("account")) | set(self.account_meta.keys()))
        _labelmap = {self.account_label(k): k for k in _keys}
        acc_choices = list(_labelmap.keys()) or ["(no accounts yet)"]

        def _pick_account(label):
            e_account.delete(0, "end")
            e_account.insert(0, _labelmap.get(label, label))
        acc_menu = tk.OptionMenu(form, acc_var, *acc_choices, command=_pick_account)
        acc_menu.configure(bg=C_BG2, fg=C_FG, activebackground=C_SEP,
                           highlightthickness=0, relief="flat", font=FONT)
        acc_menu["menu"].configure(bg=C_BG2, fg=C_FG)
        acc_menu.grid(row=2, column=2, sticky="w", padx=8)

        # type
        row(3, "Type")
        v_type = tk.StringVar(value=(tx["type"] if tx else "BUY"))
        tf = tk.Frame(form, bg=C_BG3)
        tf.grid(row=3, column=1, sticky="w")
        for val in ("BUY", "SELL"):
            tk.Radiobutton(tf, text=val, variable=v_type, value=val, bg=C_BG3,
                           fg=C_FG, selectcolor=C_BG2, font=FONT,
                           activebackground=C_BG3, highlightthickness=0).pack(side="left", padx=4)

        # date
        row(4, "Date (YYYY-MM-DD)")
        e_date = mk_entry(form, width=20, bg=C_BG2, fg=C_FG, insertbackground=C_FG,
                          font=FONT, relief="flat")
        e_date.grid(row=4, column=1, sticky="w")

        # shares
        row(5, "Shares")
        e_shares = mk_entry(form, width=20, bg=C_BG2, fg=C_FG, insertbackground=C_FG,
                            font=FONT, relief="flat")
        e_shares.grid(row=5, column=1, sticky="w")

        # price
        row(6, "Price / share")
        e_price = mk_entry(form, width=20, bg=C_BG2, fg=C_FG, insertbackground=C_FG,
                           font=FONT, relief="flat")
        e_price.grid(row=6, column=1, sticky="w")

        # courtage
        row(7, "Brokerage")
        e_courtage = mk_entry(form, width=20, bg=C_BG2, fg=C_FG, insertbackground=C_FG,
                              font=FONT, relief="flat")
        e_courtage.grid(row=7, column=1, sticky="w")

        # note
        row(8, "Note")
        e_note = mk_entry(form, width=30, bg=C_BG2, fg=C_FG, insertbackground=C_FG,
                          font=FONT, relief="flat")
        e_note.grid(row=8, column=1, columnspan=2, sticky="w")

        # pre-fill
        if tx:
            e_ticker.insert(0, tx.get("ticker", ""))
            e_company.insert(0, tx.get("company", ""))
            e_account.insert(0, tx.get("account", ""))
            e_date.insert(0, tx.get("date", today_str()))
            e_shares.insert(0, str(tx.get("shares", "")))
            e_price.insert(0, str(tx.get("price", "")))
            e_courtage.insert(0, str(tx.get("courtage", 0)))
            e_note.insert(0, tx.get("note", ""))
        else:
            e_date.insert(0, today_str())
            e_courtage.insert(0, "0")

        # lookup button: verify ticker + fill company + show live price
        info_lbl = tk.Label(form, text="", bg=C_BG3, fg=C_ACCENT, font=FONT)
        info_lbl.grid(row=9, column=1, columnspan=2, sticky="w", pady=(8, 0))

        def lookup():
            t = e_ticker.get().strip().upper()
            if not t:
                return
            info_lbl.config(text="Looking up...", fg=C_FG_DIM)
            top.update_idletasks()

            def work():
                try:
                    info = fetch_one(t)
                    def done():
                        if not e_company.get().strip():
                            e_company.delete(0, "end")
                            e_company.insert(0, info["name"])
                        if not e_price.get().strip():
                            e_price.insert(0, str(info["price"]))
                        info_lbl.config(
                            text=f"{info['name']}  -  {fnum(info['price'])} "
                                 f"{info['currency']}", fg=C_ACCENT)
                    self.root.after(0, done)
                except Exception:
                    self.root.after(0, lambda: info_lbl.config(
                        text="Ticker not found on Yahoo.", fg=C_BAD))
            threading.Thread(target=work, daemon=True).start()

        self._btn(form, "Look up ticker", lookup, BTN_REFRESH).grid(
            row=10, column=1, sticky="w", pady=(8, 0))

        # save / cancel
        btns = tk.Frame(top, bg=C_BG3)
        btns.pack(pady=(4, 14))

        def save():
            t = e_ticker.get().strip().upper()
            d = e_date.get().strip()
            if not t:
                messagebox.showwarning(APP_NAME, "Ticker is required.")
                return
            if not parse_date(d):
                messagebox.showwarning(APP_NAME, "Date must be YYYY-MM-DD.")
                return
            try:
                shares = float(e_shares.get().replace(",", ".").strip())
                price = float(e_price.get().replace(",", ".").strip())
                courtage = float((e_courtage.get() or "0").replace(",", ".").strip())
            except ValueError:
                messagebox.showwarning(APP_NAME, "Shares / price / brokerage must be numbers.")
                return
            company = e_company.get().strip()
            rec = {
                "id": tx["id"] if tx else self.pf._new_id(),
                "ticker": t, "company": company,
                "account": e_account.get().strip(),
                "type": v_type.get(), "date": d,
                "shares": shares, "price": price, "courtage": courtage,
                "note": e_note.get().strip(),
            }
            if tx:
                self.pf.transactions = [rec if x.get("id") == tx["id"] else x
                                        for x in self.pf.transactions]
            else:
                self.pf.transactions.append(rec)
            if company:
                self.pf.instruments.setdefault(t, {})["company"] = company
            acc = rec["account"]
            if acc and acc not in self.accounts:
                self.accounts.append(acc)
                self.S["accounts"] = self.accounts
                save_settings(self.S)
            self.pf.save()
            top.destroy()
            self.after_data_change()
            flash_ok(self.root, "Saved")

        self._btn(btns, "Save", save, BTN_DIALOG_OK).pack(side="left", padx=6)
        self._btn(btns, "Cancel", top.destroy, BTN_DIALOG_CANCEL).pack(side="left", padx=6)
        top.bind("<Return>", lambda e: save())
        e_ticker.focus_set()


# ============================================================================
#  DEL 15 .... DIVIDENDS MANAGER DIALOG
# ============================================================================
    def open_dividends(self):
        top = tk.Toplevel(self.root, bg=C_BG3)
        top.title("Dividend manager")
        init_dialog(top, self.root)
        top.geometry("720x520")

        tk.Label(top, text="Dividend events  (date + amount per share)",
                 bg=C_BG3, fg=C_ACCENT, font=FONT_B).pack(pady=(12, 4))

        # list of dividend events
        wrap = tk.Frame(top, bg=C_BG3)
        wrap.pack(fill="both", expand=True, padx=12)
        cols = ("date", "ticker", "per_share", "note")
        tree = ttk.Treeview(wrap, columns=cols, show="headings", selectmode="browse")
        for c, t, w in (("date", "Date", 110), ("ticker", "Ticker", 110),
                        ("per_share", "Per share", 100), ("note", "Note", 320)):
            tree.heading(c, text=t)
            tree.column(c, width=w, anchor="w" if c in ("ticker", "note") else "e")
        vs = ttk.Scrollbar(wrap, orient="vertical", command=tree.yview)
        tree.configure(yscrollcommand=vs.set)
        tree.pack(side="left", fill="both", expand=True)
        vs.pack(side="right", fill="y")
        bind_mousewheel(tree)

        def reload():
            tree.delete(*tree.get_children())
            for d in sorted(self.pf.dividends, key=lambda x: (x["ticker"], x["date"])):
                tree.insert("", "end", iid=d["id"], values=(
                    d["date"], d["ticker"], fnum(d.get("per_share"), 2),
                    d.get("note", "")))
        reload()

        # input row
        form = tk.Frame(top, bg=C_BG3)
        form.pack(fill="x", padx=12, pady=8)
        tickers = self.known_tickers()
        tk.Label(form, text="Ticker", bg=C_BG3, fg=C_FG, font=FONT).grid(row=0, column=0, padx=2)
        v_tk = tk.StringVar()
        # tk.Entry (not ttk) so the caret is SOLID, never blinking
        cb = mk_entry(form, textvariable=v_tk, width=12, bg=C_BG2, fg=C_FG,
                      insertbackground=C_FG, relief="flat", font=FONT)
        cb.grid(row=0, column=1, padx=2, sticky="w")
        _pick = tk.StringVar(value="▾")
        _mnu = tk.OptionMenu(form, _pick, *(tickers or [" "]),
                             command=lambda val: v_tk.set(val))
        _mnu.configure(bg=C_BG2, fg=C_FG, activebackground=C_SEP, relief="flat",
                       highlightthickness=0, font=FONT, width=1, bd=0)
        _mnu["menu"].configure(bg=C_BG2, fg=C_FG)
        _mnu.grid(row=0, column=1, padx=2, sticky="e")
        tk.Label(form, text="Date", bg=C_BG3, fg=C_FG, font=FONT).grid(row=0, column=2, padx=2)
        e_d = mk_entry(form, width=12, bg=C_BG2, fg=C_FG, insertbackground=C_FG, relief="flat")
        e_d.grid(row=0, column=3, padx=2)
        e_d.insert(0, today_str())
        tk.Label(form, text="Per share", bg=C_BG3, fg=C_FG, font=FONT).grid(row=0, column=4, padx=2)
        e_ps = mk_entry(form, width=8, bg=C_BG2, fg=C_FG, insertbackground=C_FG, relief="flat")
        e_ps.grid(row=0, column=5, padx=2)
        tk.Label(form, text="Note", bg=C_BG3, fg=C_FG, font=FONT).grid(row=0, column=6, padx=2)
        e_no = mk_entry(form, width=16, bg=C_BG2, fg=C_FG, insertbackground=C_FG, relief="flat")
        e_no.grid(row=0, column=7, padx=2)

        def add_div():
            t = v_tk.get().strip().upper()
            d = e_d.get().strip()
            if not t or not parse_date(d):
                messagebox.showwarning(APP_NAME, "Ticker and valid date required.")
                return
            try:
                ps = float(e_ps.get().replace(",", ".").strip())
            except ValueError:
                messagebox.showwarning(APP_NAME, "Per share must be a number.")
                return
            self.pf.dividends.append({
                "id": str(int(time.time() * 1000)) + str(len(self.pf.dividends)),
                "ticker": t, "date": d, "per_share": ps,
                "note": e_no.get().strip()})
            self.pf.save()
            reload()
            self.after_data_change()
            e_ps.delete(0, "end")

        def del_div():
            sel = tree.selection()
            if not sel:
                return
            self.pf.dividends = [x for x in self.pf.dividends if x["id"] not in sel]
            self.pf.save()
            reload()
            self.after_data_change()

        # quarterly series generator
        def gen_series():
            t = v_tk.get().strip().upper()
            d = parse_date(e_d.get().strip())
            if not t or not d:
                messagebox.showwarning(APP_NAME, "Ticker and valid start date required.")
                return
            try:
                ps = float(e_ps.get().replace(",", ".").strip())
            except ValueError:
                messagebox.showwarning(APP_NAME, "Per share must be a number.")
                return
            gtop = tk.Toplevel(top, bg=C_BG3)
            gtop.title("Generate series")
            init_dialog(gtop, top)
            tk.Label(gtop, text="Frequency", bg=C_BG3, fg=C_FG, font=FONT).grid(row=0, column=0, padx=8, pady=6)
            v_freq = tk.StringVar(value="Quarterly")
            ttk.Combobox(gtop, textvariable=v_freq, state="readonly", width=12,
                         values=("Monthly", "Quarterly", "Semi-annual", "Annual")
                         ).grid(row=0, column=1, padx=8)
            tk.Label(gtop, text="Count", bg=C_BG3, fg=C_FG, font=FONT).grid(row=1, column=0, padx=8, pady=6)
            e_cnt = mk_entry(gtop, width=6, bg=C_BG2, fg=C_FG, insertbackground=C_FG, relief="flat")
            e_cnt.grid(row=1, column=1, padx=8, sticky="w")
            e_cnt.insert(0, "4")

            def do_gen():
                try:
                    n = int(e_cnt.get().strip())
                except ValueError:
                    return
                step = {"Monthly": 1, "Quarterly": 3,
                        "Semi-annual": 6, "Annual": 12}[v_freq.get()]
                cur = d
                for _ in range(n):
                    self.pf.dividends.append({
                        "id": str(int(time.time() * 1e6)) + str(len(self.pf.dividends)),
                        "ticker": t, "date": cur.isoformat(),
                        "per_share": ps, "note": e_no.get().strip() or f"{v_freq.get()} (auto)"})
                    # advance months
                    m = cur.month - 1 + step
                    y = cur.year + m // 12
                    m = m % 12 + 1
                    day = min(cur.day, 28)
                    cur = _dt.date(y, m, day)
                self.pf.save()
                reload()
                self.after_data_change()
                gtop.destroy()
                flash_ok(self.root, f"{n} events added")
            self._btn(gtop, "Generate", do_gen, BTN_DIALOG_OK).grid(row=2, column=0, columnspan=2, pady=10)
            gtop.bind("<Return>", lambda e: do_gen())

        btns = tk.Frame(top, bg=C_BG3)
        btns.pack(pady=8)
        self._btn(btns, "Add event", add_div, BTN_ADD).pack(side="left", padx=4)
        self._btn(btns, "Generate series...", gen_series, BTN_REFRESH).pack(side="left", padx=4)
        self._btn(btns, "Delete selected", del_div, BTN_DELETE).pack(side="left", padx=4)
        self._btn(btns, "Close", top.destroy, BTN_DIALOG_CANCEL).pack(side="left", padx=4)
        top.bind("<Return>", lambda e: add_div())
        cb.focus_set()


# ============================================================================
#  DEL 16 .... WHAT-IF CALCULATOR DIALOG
# ============================================================================
    def open_whatif(self):
        rows = self._holding_rows()
        priced = [r for r in rows if r["price"] is not None]
        if not priced:
            messagebox.showinfo(APP_NAME,
                                "Refresh prices first so the calculator has a base price.")
            return
        top = tk.Toplevel(self.root, bg=C_BG3)
        top.title("What-if calculator")
        init_dialog(top, self.root)
        top.geometry("560x470")

        tk.Label(top, text="What-if  -  price move impact",
                 bg=C_BG3, fg=C_ACCENT, font=("Segoe UI", 13, "bold")).pack(pady=(14, 2))
        tk.Label(top, text="Pick a holding, then type a change in kronor OR percent.",
                 bg=C_BG3, fg=C_FG_DIM, font=FONT).pack()

        sel = tk.Frame(top, bg=C_BG3)
        sel.pack(pady=10)
        tk.Label(sel, text="Holding", bg=C_BG3, fg=C_FG, font=FONT).pack(side="left", padx=4)
        labels = [f"{r['company']}  [{r['ticker']} / {r['account']}]" for r in priced]
        v_sel = tk.StringVar(value=labels[0])
        cb = ttk.Combobox(sel, textvariable=v_sel, values=labels, state="readonly", width=42)
        cb.pack(side="left")

        inp = tk.Frame(top, bg=C_BG3)
        inp.pack(pady=6)
        tk.Label(inp, text="Change (kr/share)", bg=C_BG3, fg=C_FG, font=FONT).grid(row=0, column=0, padx=6, pady=4, sticky="e")
        e_kr = mk_entry(inp, width=12, bg=C_BG2, fg=C_FG, insertbackground=C_FG, relief="flat", font=FONT)
        e_kr.grid(row=0, column=1, padx=6)
        tk.Label(inp, text="Change (%)", bg=C_BG3, fg=C_FG, font=FONT).grid(row=1, column=0, padx=6, pady=4, sticky="e")
        e_pct = mk_entry(inp, width=12, bg=C_BG2, fg=C_FG, insertbackground=C_FG, relief="flat", font=FONT)
        e_pct.grid(row=1, column=1, padx=6)

        out = tk.Label(top, text="", bg=C_BG2, fg=C_FG, font=FONT_MONO,
                       justify="left", anchor="w", padx=16, pady=14)
        out.pack(fill="both", expand=True, padx=16, pady=12)

        state = {"lock": False}

        def current():
            i = labels.index(v_sel.get())
            return priced[i]

        def total_portfolio_value():
            return sum(r["value"] for r in priced if r["value"] is not None)

        def recompute(source):
            if state["lock"]:
                return
            r = current()
            price = r["price"]
            qty = r["qty"]
            try:
                if source == "kr":
                    kr = float(e_kr.get().replace(",", ".").strip())
                    pct = kr / price * 100 if price else 0
                    state["lock"] = True
                    e_pct.delete(0, "end")
                    e_pct.insert(0, f"{pct:.2f}")
                    state["lock"] = False
                else:
                    pct = float(e_pct.get().replace(",", ".").strip())
                    kr = price * pct / 100
                    state["lock"] = True
                    e_kr.delete(0, "end")
                    e_kr.insert(0, f"{kr:.2f}")
                    state["lock"] = False
            except ValueError:
                out.config(text="Enter a number.")
                return
            new_price = price + kr
            old_val = price * qty
            new_val = new_price * qty
            delta_val = new_val - old_val
            port = total_portfolio_value()
            port_pct = (delta_val / port * 100) if port else 0
            gav = r["gav"]
            new_pl = (new_price - gav) * qty
            txt = (
                f"{r['company']}  ({r['ticker']})\n"
                f"{'-'*46}\n"
                f"Shares held        : {fnum(qty,0)}\n"
                f"Current price      : {fnum(price)} kr\n"
                f"Avg cost (GAV)     : {fnum(gav)} kr\n\n"
                f"Move               : {kr:+.2f} kr   =   {pct:+.2f} %\n"
                f"New price          : {fnum(new_price)} kr\n\n"
                f"Position value     : {fnum(old_val)}  ->  {fnum(new_val)} kr\n"
                f"Change in value    : {delta_val:+,.0f} kr\n".replace(",", " ") +
                f"New total G/L      : {new_pl:+,.0f} kr\n".replace(",", " ") +
                f"\nImpact on whole portfolio ({fnum(port,0)} kr):\n"
                f"                     {delta_val:+,.0f} kr   =   {port_pct:+.3f} %".replace(",", " ")
            )
            out.config(text=txt)

        e_kr.bind("<KeyRelease>", lambda e: recompute("kr"))
        e_pct.bind("<KeyRelease>", lambda e: recompute("pct"))
        cb.bind("<<ComboboxSelected>>", lambda e: recompute("kr"))
        e_kr.insert(0, "1")
        recompute("kr")
        e_kr.focus_set()

        self._btn(top, "Close", top.destroy, BTN_DIALOG_CANCEL).pack(pady=(0, 12))


# ============================================================================
#  DEL 17 .... REFRESH PRICES  (threaded so the GUI never freezes)
# ============================================================================
    def refresh_prices(self):
        if self.busy:
            return
        tickers = self.pf.tickers()
        if not tickers:
            self.set_status("No tickers to fetch.")
            return
        self.busy = True
        self.refresh_btn.config(text="Refreshing...", state="disabled")
        self.set_status(f"Fetching {len(tickers)} prices from Yahoo...")
        done = {"n": 0}

        def on_each(tk_, ok):
            done["n"] += 1
            self.root.after(0, lambda: self.set_status(
                f"Fetching... {done['n']}/{len(tickers)}"))

        def work():
            result = fetch_many(tickers, on_each)

            def finish():
                self.prices.update(result)
                self.S["prices"] = self.prices
                save_settings(self.S)
                self.busy = False
                self.refresh_btn.config(text="Refresh prices", state="normal")
                stamp = _dt.datetime.now().strftime("%Y-%m-%d %H:%M")
                ok = len(result)
                self.set_status(f"Updated {ok}/{len(tickers)} at {stamp}")
                self.refresh_table()
                self.refresh_dividends_view()
                self.refresh_account_view()
                self._refresh_overview()
            self.root.after(0, finish)
        threading.Thread(target=work, daemon=True).start()

    def after_data_change(self):
        self.refresh_table()
        self.refresh_dividends_view()
        self.refresh_person_view()
        self.refresh_account_view()
        self.refresh_sold_view()
        self.update_warnings()
        self._refresh_overview()

    # ---- phone sync (the app "Issu's StockFolio"; the logic is in StockFolio_sync.py next to this file) ----
    def _attach_phone_sync(self):
        """# ToDo: DEL 22 - PHONE SYNC.  Without StockFolio_sync.py the program works exactly as before."""
        if PHONE is None:
            return
        try:
            PHONE.attach(self, HELP_DIR, {
                "bg": C_BG3, "fg": C_FG, "dim": C_FG_DIM, "accent": C_ACCENT, "warn": C_WARN,
                "ok": BTN_DIALOG_OK, "cancel": BTN_DIALOG_CANCEL, "font": FONT, "btn": self._btn,
                "init_dialog": init_dialog, "flash_ok": flash_ok}, log)
        except Exception as e:
            log(f"phone sync attach failed: {e}")

    def open_phone_sync(self):
        if PHONE is None:
            messagebox.showinfo(APP_NAME, "StockFolio_sync.py was not found next to StockFolio.py.")
            return
        PHONE.open_dialog(self, HELP_DIR)

    def phone_data_changed(self):
        """Called by StockFolio_sync after rows from the phone were put into the portfolio: save and redraw."""
        self.pf.save()
        try:
            save_price_history(self.price_history)
            self.S["accounts"] = self.accounts
            self.S["account_meta"] = self.account_meta
            save_settings(self.S)
        except Exception as e:
            log(f"phone_data_changed save failed: {e}")
        self.after_data_change()


# ============================================================================
#  DEL 17B ... GOOGLE SHEET  -  config, price refresh, one-time import
# ============================================================================
    def _gsheet_get_rows(self):
        """Fetch sheet rows; raise on error (caller handles)."""
        return read_gsheet_rows(self.gsheet.get("url", ""),
                                self.gsheet.get("gid", "0"))

    def open_gsheet(self):
        top = tk.Toplevel(self.root, bg=C_BG3)
        top.title("Google Sheet - import & live prices")
        init_dialog(top, self.root)
        top.geometry("640x640")

        tk.Label(top, text="Google Sheet connection",
                 bg=C_BG3, fg=C_ACCENT, font=("Segoe UI", 14, "bold")).pack(pady=(12, 2))
        tk.Label(top, text="The sheet must be shared as 'Anyone with the link can view'.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic")).pack()

        body = tk.Frame(top, bg=C_BG3)
        body.pack(fill="x", padx=16, pady=10)

        ents = {}

        def field(r, label, key, width=46):
            tk.Label(body, text=label, bg=C_BG3, fg=C_FG, font=FONT,
                     anchor="w", width=16).grid(row=r, column=0, sticky="w", pady=3)
            e = mk_entry(body, width=width, bg=C_BG2, fg=C_FG,
                         insertbackground=C_FG, relief="flat", font=FONT)
            e.grid(row=r, column=1, sticky="w", columnspan=3)
            e.insert(0, self.gsheet.get(key, ""))
            ents[key] = e
            return e

        field(0, "Sheet URL or ID", "url")
        field(1, "Tab gid (holdings)", "gid", width=14)
        if ents["gid"].get().strip() in ("", "0"):
            ents["gid"].delete(0, "end")
            ents["gid"].insert(0, "507464238")
        tk.Label(body, text="Your tabs:  Aktier=507464238  ·  Bolag=403105218  "
                 "·  Kurser=1255905222  ·  Sammanfattning=770601635",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8)).grid(
                 row=1, column=2, columnspan=2, sticky="w", padx=8)

        tk.Label(body, text="Column names (match your sheet headers):",
                 bg=C_BG3, fg=C_ACCENT, font=FONT_B).grid(
                 row=2, column=0, columnspan=4, sticky="w", pady=(10, 2))

        colmap = [
            ("Company", "col_name"), ("Code", "col_code"),
            ("Account", "col_account"), ("Shares", "col_shares"),
            ("Date", "col_date"), ("Buy price", "col_buyprice"),
            ("Brokerage", "col_courtage"), ("Current value", "col_value"),
            ("Dividend/share", "col_dividend"),
        ]
        for i, (lab, key) in enumerate(colmap):
            r = 3 + i // 2
            c = (i % 2) * 2
            tk.Label(body, text=lab, bg=C_BG3, fg=C_FG, font=FONT,
                     anchor="w", width=14).grid(row=r, column=c, sticky="w", pady=2)
            e = mk_entry(body, width=14, bg=C_BG2, fg=C_FG,
                         insertbackground=C_FG, relief="flat", font=FONT)
            e.grid(row=r, column=c + 1, sticky="w", padx=(0, 14))
            e.insert(0, self.gsheet.get(key, ""))
            ents[key] = e

        tk.Label(body, text="Note: the sheet's live price = Current value / Shares.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic")).grid(
                 row=20, column=0, columnspan=4, sticky="w", pady=(8, 0))

        # active price source
        src = tk.Frame(top, bg=C_BG3)
        src.pack(fill="x", padx=16, pady=(4, 6))
        tk.Label(src, text="Use this source for Value / Gain-Loss:",
                 bg=C_BG3, fg=C_FG, font=FONT_B).pack(side="left")
        v_src = tk.StringVar(value=self.price_source)
        for val, lab in (("yahoo", "Yahoo (auto)"), ("gsheet", "Google Sheet")):
            tk.Radiobutton(src, text=lab, variable=v_src, value=val, bg=C_BG3,
                           fg=C_FG, selectcolor=C_BG2, font=FONT,
                           activebackground=C_BG3, highlightthickness=0).pack(side="left", padx=6)

        info = tk.Label(top, text="", bg=C_BG3, fg=C_ACCENT, font=FONT, wraplength=600)
        info.pack(fill="x", padx=16, pady=4)

        def collect():
            for k, e in ents.items():
                self.gsheet[k] = e.get().strip()
            self.price_source = v_src.get()
            self.S["gsheet"] = self.gsheet
            self.S["price_source"] = self.price_source
            save_settings(self.S)

        def save_cfg():
            collect()
            self.refresh_table()
            flash_ok(self.root, "Saved")

        def do_refresh():
            collect()
            if not self.gsheet.get("url"):
                info.config(text="Enter the sheet URL or ID first.", fg=C_BAD)
                return
            info.config(text="Fetching from Google Sheet...", fg=C_FG_DIM)
            top.update_idletasks()

            def work():
                try:
                    _, rows = self._gsheet_get_rows()
                    prices = self._sheet_prices_from_rows(rows)

                    def done():
                        self.sheet_prices.update(prices)
                        self.S["sheet_prices"] = self.sheet_prices
                        save_settings(self.S)
                        stamp = _dt.datetime.now().strftime("%H:%M")
                        info.config(text=f"Updated {len(prices)} prices from sheet "
                                         f"at {stamp}.", fg=C_ACCENT)
                        self.refresh_table()
                        self.set_status(f"Sheet prices updated ({len(prices)}) at {stamp}")
                    self.root.after(0, done)
                except Exception as e:
                    log(f"sheet refresh failed: {e}")
                    self.root.after(0, lambda: info.config(
                        text=f"Could not read sheet: {e}", fg=C_BAD))
            threading.Thread(target=work, daemon=True).start()

        def do_import():
            collect()
            if not self.gsheet.get("url"):
                info.config(text="Enter the sheet URL or ID first.", fg=C_BAD)
                return
            self._import_dialog(top)

        btns = tk.Frame(top, bg=C_BG3)
        btns.pack(pady=10)
        def do_import_div():
            collect()
            if not self.gsheet.get("url"):
                info.config(text="Enter the sheet URL or ID first.", fg=C_BAD)
                return
            info.config(text="Reading dividend tab...", fg=C_FG_DIM)
            top.update_idletasks()
            self.import_bolag_dividends(info)

        self._btn(btns, "Save settings", save_cfg, BTN_DIALOG_OK).pack(side="left", padx=4)
        self._btn(btns, "Refresh prices from sheet", do_refresh, BTN_REFRESH).pack(side="left", padx=4)
        self._btn(btns, "Import holdings...", do_import, BTN_ADD).pack(side="left", padx=4)
        self._btn(btns, "Import dividends (Bolag)", do_import_div, BTN_ADD).pack(side="left", padx=4)
        self._btn(btns, "Close", top.destroy, BTN_DIALOG_CANCEL).pack(side="left", padx=4)
        ents["url"].focus_set()

    def _sheet_prices_from_rows(self, rows):
        """Compute per-share price (value/shares) per ticker, averaged."""
        g = self.gsheet
        acc = {}
        for r in rows:
            ticker = code_to_ticker(r.get(g["col_code"], ""))
            shares = to_float(r.get(g["col_shares"], ""))
            value = to_float(r.get(g["col_value"], ""))
            if not ticker or not shares or value is None:
                continue
            price = value / shares
            acc.setdefault(ticker, []).append(price)
        out = {}
        now = int(time.time())
        for tk_, vals in acc.items():
            out[tk_] = {"price": round(sum(vals) / len(vals), 4), "ts": now}
        return out

    def import_bolag_dividends(self, info=None):
        """Import forward dividends from the 'Bolag' tab.

        Dated rows -> one event.  Frequency rows (Kvartalsvis etc.) -> a
        forward series anchored on the latest historical dividend for that
        ticker (or today), through ~18 months ahead.
        """
        g = self.gsheet
        try:
            _, rows = read_gsheet_rows(g.get("url", ""), g.get("div_gid", "403105218"))
        except Exception as e:
            if info:
                info.config(text=f"Could not read dividend tab: {e}", fg=C_BAD)
            return (0, 0)
        today = _dt.date.today()
        horizon = today + _dt.timedelta(days=550)
        existing = {(d["ticker"], d["date"], round(float(d.get("per_share", 0)), 4))
                    for d in self.pf.dividends}
        # A day on which money was ACTUALLY received needs no forecast on top of
        # it - even if the sheet quotes a slightly different amount per share.
        received_days = {(d["ticker"], d["date"]) for d in self.pf.dividends
                         if d.get("amount")}
        # latest known historical dividend date per ticker (anchor for series)
        last_div = {}
        for d in self.pf.dividends:
            dd = parse_date(d.get("date", ""))
            if dd:
                t = d["ticker"]
                if t not in last_div or dd > last_div[t]:
                    last_div[t] = dd
        n_add = n_skip = 0
        for r in rows:
            ticker = code_to_ticker(r.get(g["div_col_code"], ""))
            ps = to_float(r.get(g["div_col_pershare"], ""))
            xval = (r.get(g["div_col_date"], "") or "").strip()
            if not ticker or not ps:           # need a ticker and a non-zero amount
                continue
            events = []
            ds_iso = parse_sheet_date(xval)
            if ds_iso:
                dobj = parse_date(ds_iso)
                events = [dobj] if dobj else []
            else:
                step = recognize_frequency(xval)
                if not step:
                    n_skip += 1
                    continue
                anchor = last_div.get(ticker, today)
                cur = add_months(anchor, step)
                guard = 0
                while cur <= horizon and guard < 36:
                    if cur >= today:
                        events.append(cur)
                    cur = add_months(cur, step)
                    guard += 1
            for ev in events:
                ds = ev.isoformat()
                sig = (ticker, ds, round(float(ps), 4))
                if sig in existing or (ticker, ds) in received_days:
                    continue
                existing.add(sig)
                self.pf.dividends.append({
                    "id": str(int(time.time() * 1e6)) + str(len(self.pf.dividends)),
                    "ticker": ticker, "date": ds, "per_share": ps,
                    "note": f"Bolag: {xval}" if xval else "Bolag"})
                n_add += 1
        self.pf.save()
        self.after_data_change()
        if info:
            info.config(text=f"Added {n_add} forward dividend events "
                             f"({n_skip} rows skipped - amount but no date/frequency).",
                        fg=C_ACCENT)
        return (n_add, n_skip)

    def _parse_import_rows(self, rows):
        """Turn sheet rows into transaction dicts (no ids yet)."""
        g = self.gsheet
        txs = []
        for r in rows:
            code = r.get(g["col_code"], "")
            ticker = code_to_ticker(code)
            shares = to_float(r.get(g["col_shares"], ""))
            if not ticker or not shares:
                continue
            price = to_float(r.get(g["col_buyprice"], ""))
            if price is None:
                continue
            txs.append({
                "ticker": ticker,
                "company": (r.get(g["col_name"], "") or "").strip(),
                "account": (r.get(g["col_account"], "") or "").strip(),
                "type": "BUY",
                "date": parse_sheet_date(r.get(g["col_date"], "")) or today_str(),
                "shares": shares,
                "price": price,
                "courtage": to_float(r.get(g["col_courtage"], "")) or 0.0,
                "note": "imported",
            })
        return txs

    def _sheet_dup_check(self, tx):
        """Classify ONE sheet row against the transactions already stored.

        The Google Sheet is a SUMMARY of the very same trades the broker CSV
        already delivered, but it carries the sheet's own account names
        ("N-Lars") while the CSV copy carries the broker's ("64352081").
        Matching on the account therefore proves nothing, so the check works
        from strict to loose and reports HOW sure it is:

            DUP     same ticker+type+date+shares+price  -> certainly the same
                    trade, only the account name differs
            LIKELY  same date+shares but another price, or same shares+price
                    on another date -> the sheet stores an AVERAGE price /
                    a settlement date, so this is still the same trade
            OWNED   nothing matches, but the ticker is already tracked, so
                    importing puts extra shares on top of a real holding
            NEW     the ticker is not in the portfolio at all

        Returns (status, matching_transaction_or_None).
        """
        rank = {"DUP": 3, "LIKELY": 2, "OWNED": 1, "NEW": 0}
        tick = (tx.get("ticker") or "").upper()
        kind = tx.get("type", "BUY") or "BUY"
        date = tx.get("date") or ""
        qty = round(float(tx.get("shares") or 0), 3)
        price = round(float(tx.get("price") or 0), 4)

        best, best_tx = "NEW", None

        def keep(status, other):
            nonlocal best, best_tx
            if rank[status] > rank[best]:
                best, best_tx = status, other

        for e in self.pf.transactions:
            if (e.get("ticker") or "").upper() != tick:
                continue
            keep("OWNED", e)
            if (e.get("type", "BUY") or "BUY") != kind:
                continue
            e_qty = round(float(e.get("shares") or 0), 3)
            e_price = round(float(e.get("price") or 0), 4)
            e_date = e.get("date") or ""
            if e_date == date and e_qty == qty and e_price == price:
                keep("DUP", e)
            elif e_date == date and e_qty == qty:
                keep("LIKELY", e)
            elif e_qty == qty and e_price == price:
                keep("LIKELY", e)
        return best, best_tx

    def _import_dialog(self, parent):
        try:
            _, rows = self._gsheet_get_rows()
        except Exception as e:
            messagebox.showerror(APP_NAME, f"Could not read sheet:\n{e}", parent=parent)
            return
        txs = self._parse_import_rows(rows)
        if not txs:
            messagebox.showinfo(APP_NAME, "No importable rows found. Check the "
                                "column-name mapping.", parent=parent)
            return

        # Classify BEFORE anything is shown.  Importing the sheet blindly on
        # top of the broker CSV is exactly what produced duplicate holdings,
        # so nothing that already looks stored is ticked by default.
        marks = [self._sheet_dup_check(t) for t in txs]
        picked = []
        for t, (status, _m) in zip(txs, marks):
            picked.append(status == "NEW" and bool((t.get("account") or "").strip()))

        top = tk.Toplevel(parent, bg=C_BG3)
        top.title("Import holdings - preview")
        init_dialog(top, parent)
        top.geometry("900x600")

        tk.Label(top, text=f"{len(txs)} rows in the sheet - only the TICKED ones are imported",
                 bg=C_BG3, fg=C_ACCENT, font=FONT_B).pack(pady=(12, 2))
        tk.Label(top, text="CLICK A ROW to switch it between  IMPORT  and  skip.",
                 bg=C_BG3, fg=C_WARN, font=FONT_B).pack(pady=(2, 2))
        tk.Label(top, text="The sheet repeats trades your broker CSV already delivered, "
                 "just under different account names. Those are marked and set to skip.",
                 bg=C_BG3, fg=C_FG_DIM, font=FONT, wraplength=860,
                 justify="left").pack(pady=(0, 6))

        wrap = tk.Frame(top, bg=C_BG3)
        wrap.pack(fill="both", expand=True, padx=12)
        cols = ("pick", "status", "date", "type", "ticker", "company",
                "account", "shares", "price", "match")
        tree = ttk.Treeview(wrap, columns=cols, show="headings", selectmode="browse")
        for c, t, w in (("pick", "Import / skip", 100), ("status", "Status", 70),
                        ("date", "Date", 88), ("type", "Type", 46),
                        ("ticker", "Ticker", 95), ("company", "Company", 135),
                        ("account", "Account", 78), ("shares", "Shares", 66),
                        ("price", "Buy price", 74),
                        ("match", "Already stored as", 190)):
            tree.heading(c, text=t)
            tree.column(c, width=w, anchor="w" if c in (
                "ticker", "company", "account", "type", "status", "match") else "e")
        tree.column("pick", anchor="center")
        vs = ttk.Scrollbar(wrap, orient="vertical", command=tree.yview)
        tree.configure(yscrollcommand=vs.set)
        tree.pack(side="left", fill="both", expand=True)
        vs.pack(side="right", fill="y")
        bind_mousewheel(tree)
        tree.tag_configure("DUP", foreground=C_FG_DIM)
        tree.tag_configure("LIKELY", foreground=C_WARN)
        tree.tag_configure("OWNED", foreground="#7fa8d0")
        tree.tag_configure("NEW", foreground=C_FG)
        tree.tag_configure("noacc", background="#3a2320")
        tree.tag_configure("take", foreground=C_ACCENT, font=FONT_B)

        info = tk.Label(top, text="", bg=C_BG3, fg=C_ACCENT, font=FONT)
        info.pack(pady=(6, 0))

        def redraw():
            tree.delete(*tree.get_children())
            n_take = 0
            counts = collections.Counter()
            for i, (t, (status, m)) in enumerate(zip(txs, marks)):
                counts[status] += 1
                if picked[i]:
                    n_take += 1
                tags = [status]
                acc = (t.get("account") or "").strip()
                if not acc:
                    tags.append("noacc")
                if picked[i]:
                    tags.append("take")      # last tag wins the colour
                match = ""
                if m is not None:
                    match = f"{m.get('date','')}  {self.account_short(m.get('account',''))}"
                tree.insert("", "end", iid=str(i), values=(
                    "IMPORT" if picked[i] else "skip",
                    status if acc else "NO ACCT",
                    t["date"], t["type"], t["ticker"], t["company"],
                    acc, fnum(t["shares"], 0), fnum(t["price"]), match), tags=tags)
            info.config(
                text=f"Importing {n_take} of {len(txs)} rows   |   "
                     f"{counts['NEW']} new, {counts['DUP']} already stored, "
                     f"{counts['LIKELY']} probably already stored, "
                     f"{counts['OWNED']} would add shares to a holding you already have.",
                fg=C_ACCENT if n_take else C_FG_DIM)

        def toggle(iid):
            if iid == "" or not iid.isdigit():
                return
            picked[int(iid)] = not picked[int(iid)]
            redraw()
            tree.selection_set(iid)
            tree.focus(iid)

        def on_click(event):
            # the whole row toggles - see the same note in open_duplicates
            if tree.identify_region(event.x, event.y) != "cell":
                return
            toggle(tree.identify_row(event.y))

        tree.bind("<Button-1>", on_click)
        tree.bind("<space>", lambda e: toggle(tree.focus()))
        tree.bind("<Return>", lambda e: toggle(tree.focus()))

        def set_all(pred):
            for i, (_t, (status, _m)) in enumerate(zip(txs, marks)):
                picked[i] = pred(status, txs[i])
            redraw()

        sel = tk.Frame(top, bg=C_BG3)
        sel.pack(pady=(6, 0))
        tk.Label(sel, text="Set to IMPORT:", bg=C_BG3, fg=C_FG_DIM, font=FONT).pack(side="left", padx=(0, 4))
        self._btn(sel, "Only new", lambda: set_all(
            lambda s, t: s == "NEW" and bool((t.get("account") or "").strip())),
            BTN_DIALOG_OK).pack(side="left", padx=3)
        self._btn(sel, "Nothing", lambda: set_all(lambda s, t: False),
                  BTN_DIALOG_CANCEL).pack(side="left", padx=3)
        self._btn(sel, "Everything (I know what I am doing)",
                  lambda: set_all(lambda s, t: True), BTN_DIALOG_CANCEL).pack(side="left", padx=3)

        v_replace = tk.BooleanVar(value=(len(self.pf.transactions) == 0))
        opt = tk.Frame(top, bg=C_BG3)
        opt.pack(fill="x", padx=12, pady=6)
        tk.Checkbutton(opt, text="Replace ALL existing transactions (otherwise add)",
                       variable=v_replace, bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG3, font=FONT,
                       highlightthickness=0).pack(anchor="w")

        def do_import():
            chosen = [t for t, p in zip(txs, picked) if p]
            if not chosen:
                messagebox.showinfo(APP_NAME, "No row says IMPORT, so nothing was "
                                    "imported.", parent=top)
                return
            risky = [t for t, p, (s, _m) in zip(txs, picked, marks)
                     if p and s in ("DUP", "LIKELY")]
            if risky and not messagebox.askyesno(APP_NAME,
                    f"{len(risky)} of the ticked rows already look stored under "
                    "another account name. Importing them creates DOUBLE "
                    "holdings.\n\nImport anyway?", parent=top):
                return
            if v_replace.get() and self.pf.transactions:
                if not messagebox.askyesno(APP_NAME,
                        "This will DELETE all existing transactions and replace "
                        "them with the import. Continue?", parent=top):
                    return
                self.pf.transactions = []
            for t in chosen:
                rec = dict(t)
                rec["id"] = self.pf._new_id() + str(len(self.pf.transactions))
                self.pf.transactions.append(rec)
                if rec["company"]:
                    self.pf.instruments.setdefault(rec["ticker"], {})["company"] = rec["company"]
            self.pf.save()
            top.destroy()
            self.after_data_change()
            flash_ok(self.root, f"Imported {len(chosen)} of {len(txs)} rows")

        btns = tk.Frame(top, bg=C_BG3)
        btns.pack(pady=10)
        self._btn(btns, "Do the import", do_import, BTN_DIALOG_OK).pack(side="left", padx=4)
        self._btn(btns, "Cancel", top.destroy, BTN_DIALOG_CANCEL).pack(side="left", padx=4)
        redraw()


# ============================================================================
#  DEL 17C ... IMPORT BROKER STATEMENTS  (Nordnet / Avanza CSV)
# ============================================================================
    def _norm_account(self, acc):
        """Normalise an account so the raw statement depot-id and the account
        name it is mapped to compare EQUAL.

        A statement says e.g. "64791502" while the portfolio may already store
        that same account as "Lars ON".  Without this, re-importing a file
        would create duplicates of rows that are already there.
        """
        a = (acc or "").strip()
        return (self.account_map.get(a, a) or a).strip().casefold()

    def _archive_statements(self, paths, summary):
        """Move statement files out of the way once they have been imported.

        A broker CSV is INPUT ONLY.  Everything it carries - date, account,
        share count, price, brokerage, ISIN and the broker's own reference -
        is written into the portfolio file, and the CSV is never opened
        again; the folder scan exists only to spot NEW exports.  So once a
        statement has been read it is pure clutter.

        It is MOVED, never deleted, into Helpfiles/StockFolio/imported/ with
        the import date in front of the name, and a line is appended to
        imported/import_log.txt - so there is always a record of what was
        read and when, and the file itself is still there if it is ever
        needed again.

        Returns (moved_paths, failures).
        """
        dest_dir = os.path.join(HELP_DIR, "imported")
        moved, failures = [], []
        try:
            os.makedirs(dest_dir, exist_ok=True)
        except Exception as e:
            return [], [f"could not create {dest_dir}: {e}"]
        stamp = _dt.date.today().isoformat()
        for p in paths:
            if not os.path.isfile(p):
                continue
            if os.path.normcase(os.path.abspath(os.path.dirname(p))) == \
                    os.path.normcase(os.path.abspath(dest_dir)):
                continue                      # already filed - leave it where it is
            base = os.path.basename(p)
            stem, ext = os.path.splitext(base)
            target = os.path.join(dest_dir, f"{stamp}_{base}")
            n = 1
            while os.path.exists(target):
                target = os.path.join(dest_dir, f"{stamp}_{stem}_{n}{ext}")
                n += 1
            try:
                shutil.move(p, target)        # handles a different drive too
                moved.append(target)
            except Exception as e:
                failures.append(f"{base}: {e}")
                log(f"archive statement failed {p}: {e}")
        try:
            with open(os.path.join(dest_dir, "import_log.txt"), "a",
                      encoding="utf-8") as f:
                f.write(f"{_dt.datetime.now():%Y-%m-%d %H:%M}  {summary}\n")
                for t in moved:
                    f.write(f"    filed: {os.path.basename(t)}\n")
                for x in failures:
                    f.write(f"    COULD NOT MOVE {x}\n")
        except Exception as e:
            log(f"import_log failed: {e}")
        return moved, failures

    def _tx_signature(self, acc, kind, date, isin, qty, price):
        """Stable signature to detect duplicates across imports."""
        return (self._norm_account(acc), kind, date, (isin or "").upper(),
                round(float(qty or 0), 3), round(float(price or 0), 4))

    def _existing_signatures(self):
        sigs = set()
        for t in self.pf.transactions:
            sigs.add(self._tx_signature(t.get("account", ""), t.get("type", "BUY"),
                                        t.get("date", ""), t.get("isin", ""),
                                        t.get("shares", 0), t.get("price", 0)))
        return sigs

    def _existing_tx_by_sig(self):
        """{signature: [stored transaction dicts]} - the same key as
        _existing_signatures(), but keeping the rows themselves, so an import
        that meets an already-stored trade can fill in its missing brokerage."""
        res = {}
        for t in self.pf.transactions:
            sig = self._tx_signature(t.get("account", ""), t.get("type", "BUY"),
                                     t.get("date", ""), t.get("isin", ""),
                                     t.get("shares", 0), t.get("price", 0))
            res.setdefault(sig, []).append(t)
        return res

    @staticmethod
    def _tx_courtage(t):
        try:
            return float(t.get("courtage") or 0)
        except Exception:
            return 0.0

    def _div_signature(self, acc, ticker, date, per_share, shares):
        """Duplicate key for a RECEIVED dividend.

        The ACCOUNT and the SHARE COUNT are part of the key.  Leaving them out
        was a real data-loss bug: when several accounts hold the same stock,
        they are all paid on the SAME date at the SAME amount per share, so
        every account after the first looked like a duplicate of the first and
        was silently dropped on import.  Forward (forecast) events from the
        "Bolag" tab carry no account/shares, so they can never mask a real
        payout either.
        """
        return (self._norm_account(acc), (ticker or "").upper(), date,
                round(float(per_share or 0), 4), round(float(shares or 0), 3))

    def _existing_div_signatures(self):
        return {self._div_signature(d.get("account", ""), d.get("ticker", ""),
                                    d.get("date", ""), d.get("per_share", 0),
                                    d.get("shares", 0))
                for d in self.pf.dividends}

    # ---- pasted orders: name -> ticker, and the placeholder rows they leave ----
    def _match_ticker_by_name(self, name, account, kind):
        """Find which company of the portfolio an order-view name means.

        The order view says "Öresund, Investment AB", the statements say
        "Öresund".  Words that carry no meaning (AB, ser., Investment ...) are
        dropped and the rest is compared as a set.  A SELL can only be about
        something held on that very account, so those are tried first.  Returns
        a ticker, or "" when nothing matches clearly."""
        want = name_tokens(name)
        if not want:
            return ""
        key = self._norm_account(account)
        held = {h["ticker"] for h in self.pf.holdings()
                if self._norm_account(h["account"]) == key}
        names = {}
        for t in self.pf.transactions:
            if t.get("company"):
                names.setdefault(t["ticker"], set()).add(t["company"])
        for tk_ in self.pf.tickers():
            names.setdefault(tk_, set()).add(self.pf._company_name(tk_))

        def best_in(pool):
            scored = []
            for tk_ in pool:
                sc = 0.0
                for nm in names.get(tk_, ()):
                    have = name_tokens(nm)
                    if have:
                        sc = max(sc, len(want & have) / len(want | have))
                scored.append((sc, tk_))
            scored.sort(reverse=True)
            if scored and scored[0][0] >= 0.6 and (
                    len(scored) == 1 or scored[0][0] - scored[1][0] >= 0.15):
                return scored[0][1]
            return ""
        if kind == "SELL" and held:
            hit = best_in(held)
            if hit:
                return hit
        return best_in(list(names))

    def _paste_on_file(self, acc, kind, ticker, date, qty):
        """True when real (not pasted) rows already cover this pasted order -
        i.e. the statement with it has been imported already."""
        key = self._norm_account(acc)
        tot = 0.0
        for t in self.pf.transactions:
            if (self._norm_account(t.get("account", "")) == key
                    and t.get("ticker") == ticker and t.get("date") == date
                    and t.get("type", "BUY") == kind
                    and not str(t.get("note", "")).startswith("pasted")):
                tot += float(t.get("shares") or 0)
        return tot >= float(qty or 0) - 0.001

    def _placeholders_replaced_by(self, entries):
        """The pasted-order rows that real statement rows now cover.

        entries = [(account, kind, ticker, date, qty)] of REAL statement rows.
        A pasted order has an average price and a guessed date, while the
        statement lists each fill, so they are matched on account, kind and
        company, within 3 days, and the shares must add up to the same total."""
        groups = {}
        for acc, kind, ticker, date, qty in entries:
            groups.setdefault((self._norm_account(acc), kind, ticker), []).append((date, qty))
        res = []
        for t in self.pf.transactions:
            if not str(t.get("note", "")).startswith("pasted"):
                continue
            k = (self._norm_account(t.get("account", "")), t.get("type", "BUY"),
                 t.get("ticker"))
            d0 = parse_date(t.get("date", ""))
            if k not in groups or not d0:
                continue
            tot = 0.0
            for date, qty in groups[k]:
                d1 = parse_date(date)
                if d1 and abs((d1 - d0).days) <= 3:
                    tot += float(qty or 0)
            if abs(tot - float(t.get("shares") or 0)) < 0.001:
                res.append(t)
        return res

    def open_import_csv(self):
        # auto-scan the program folder, Downloads and our own Helpfiles folder
        found, where_txt = scan_statement_folders()

        top = tk.Toplevel(self.root, bg=C_BG3)
        top.title("Import broker statements (CSV)")
        init_dialog(top, self.root)
        top.geometry("900x680")

        tk.Label(top, text="Import broker statements - Nordnet / Avanza",
                 bg=C_BG3, fg=C_ACCENT, font=("Segoe UI", 14, "bold")).pack(pady=(12, 2))
        tk.Label(top, text="Statements carry date, shares, price AND brokerage - "
                 "imported rows are marked Verified.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic")).pack()

        # ---- file list ----
        filebar = tk.Frame(top, bg=C_BG3)
        filebar.pack(fill="x", padx=12, pady=(8, 2))
        tk.Label(filebar, text="Files:", bg=C_BG3, fg=C_FG, font=FONT_B).pack(side="left")
        files_lbl = tk.Label(filebar, text=f"{len(found)} statement(s) found",
                             bg=C_BG3, fg=C_FG_DIM, font=FONT)
        files_lbl.pack(side="left", padx=8)
        where_lbl = tk.Label(top, text=where_txt, bg=C_BG3, fg=C_FG_DIM,
                             font=("Segoe UI", 8, "italic"), wraplength=860,
                             justify="left", anchor="w")
        where_lbl.pack(fill="x", padx=12)

        state = {"files": list(found), "rows": [], "acc_widgets": {},
                 "tickers": {}, "parsed": False,
                 "file_rows": [], "pasted": []}

        def pick(folder, title):
            try:
                os.makedirs(folder, exist_ok=True)
            except Exception:
                pass
            paths = filedialog.askopenfilenames(
                parent=top, title=title, initialdir=folder,
                filetypes=[("CSV files", "*.csv"), ("All files", "*.*")])
            for p in paths:
                if p not in state["files"]:
                    state["files"].append(p)
            files_lbl.config(text=f"{len(state['files'])} selected")

        def add_files():
            pick(downloads_dir(), "Choose statement CSV files")

        def from_imported():
            # statements that were already read are filed here; picking one
            # again is safe - everything already on file is skipped
            pick(os.path.join(HELP_DIR, "imported"),
                 "Choose an already-imported statement to read again")

        def look_again():
            files, where = scan_statement_folders()
            n0 = len(state["files"])
            for p in files:
                if p not in state["files"]:
                    state["files"].append(p)
            where_lbl.config(text=where)
            files_lbl.config(text=f"{len(state['files'])} selected "
                                  f"({len(state['files']) - n0} new found)")

        self._btn(filebar, "Add files...", add_files, BTN_REFRESH).pack(side="left", padx=4)
        self._btn(filebar, "From imported...", from_imported, BTN_REFRESH).pack(side="left", padx=4)
        self._btn(filebar, "Look again", look_again, BTN_REFRESH).pack(side="left", padx=4)

        # ---- account mapping frame ----
        accfr = tk.LabelFrame(top, text=" Account mapping (statement -> your account) ",
                              bg=C_BG3, fg=C_ACCENT, font=FONT_B, bd=1)
        accfr.pack(fill="x", padx=12, pady=6)

        # ---- preview tree ----
        prevwrap = tk.Frame(top, bg=C_BG3)
        prevwrap.pack(fill="both", expand=True, padx=12, pady=4)
        cols = ("status", "date", "kind", "account", "ticker", "name", "qty", "price", "courtage")
        tree = ttk.Treeview(prevwrap, columns=cols, show="headings", selectmode="none")
        for c, t, w in (("status", "", 44), ("date", "Date", 86), ("kind", "Type", 50),
                        ("account", "Account", 90), ("ticker", "Ticker", 95),
                        ("name", "Security", 170), ("qty", "Shares", 70),
                        ("price", "Price", 75), ("courtage", "Brokerage", 75)):
            tree.heading(c, text=t)
            tree.column(c, width=w, anchor="w" if c in ("name", "ticker", "account", "kind") else ("center" if c == "status" else "e"))
        vs = ttk.Scrollbar(prevwrap, orient="vertical", command=tree.yview)
        tree.configure(yscrollcommand=vs.set)
        tree.pack(side="left", fill="both", expand=True)
        vs.pack(side="right", fill="y")
        bind_mousewheel(tree)
        tree.tag_configure("dup", foreground=C_FG_DIM)
        tree.tag_configure("new", foreground=C_FG)
        tree.tag_configure("nobrok", background="#3a2320")

        info = tk.Label(top, text="", bg=C_BG3, fg=C_ACCENT, font=FONT, wraplength=860, justify="left")
        info.pack(fill="x", padx=12, pady=2)

        # options
        optfr = tk.Frame(top, bg=C_BG3)
        optfr.pack(fill="x", padx=12)
        v_buy = tk.BooleanVar(value=True)
        v_sell = tk.BooleanVar(value=True)
        v_div = tk.BooleanVar(value=True)
        for txt, var in (("Buys", v_buy), ("Sells", v_sell), ("Dividends", v_div)):
            tk.Checkbutton(optfr, text=txt, variable=var, bg=C_BG3, fg=C_FG,
                           selectcolor=C_BG2, activebackground=C_BG3, font=FONT,
                           highlightthickness=0).pack(side="left", padx=6)
        # A statement is INPUT ONLY - everything it carries (date, account,
        # shares, price, brokerage, ISIN, reference) is written into the
        # portfolio file, and the CSV is never read again.  So once it has
        # been imported it is just clutter: move it out of the way.
        v_archive = tk.BooleanVar(value=self.S.get("archive_imported_csv", True))
        tk.Checkbutton(optfr, text="Move the files to Helpfiles\\StockFolio\\imported\\ "
                       "when done (you never need them again)",
                       variable=v_archive, bg=C_BG3, fg=C_FG,
                       selectcolor=C_BG2, activebackground=C_BG3, font=FONT,
                       highlightthickness=0).pack(side="left", padx=(20, 6))

        def build_account_rows(account_ids):
            for w in accfr.winfo_children():
                w.destroy()
            state["acc_widgets"] = {}
            choices = list(self.accounts) or ["OA-Lars", "N-Lars", "A-Lars", "ON-Lars"]
            for i, aid in enumerate(sorted(account_ids)):
                tk.Label(accfr, text=aid, bg=C_BG3, fg=C_FG, font=FONT,
                         width=18, anchor="w").grid(row=i, column=0, sticky="w", padx=6, pady=2)
                e = mk_entry(accfr, width=18, bg=C_BG2, fg=C_FG,
                             insertbackground=C_FG, relief="flat", font=FONT)
                e.grid(row=i, column=1, sticky="w", padx=4)
                e.insert(0, self.account_map.get(aid, aid))
                var = tk.StringVar(value="(pick)")
                menu = tk.OptionMenu(accfr, var, *choices,
                                     command=lambda val, ent=e: (ent.delete(0, "end"), ent.insert(0, val)))
                menu.configure(bg=C_BG2, fg=C_FG, activebackground=C_SEP,
                               highlightthickness=0, relief="flat", font=FONT)
                menu["menu"].configure(bg=C_BG2, fg=C_FG)
                menu.grid(row=i, column=2, padx=4)
                state["acc_widgets"][aid] = e

        def real_entries(only_on=False):
            """(account, kind, ticker, date, qty) of the REAL statement rows -
            what pasted order placeholders get matched against."""
            out = []
            for row in state["rows"]:
                if row["kind"] == "DIV" or row.get("paste") or not row.get("qty"):
                    continue
                if only_on and ((row["kind"] == "BUY" and not v_buy.get())
                                or (row["kind"] == "SELL" and not v_sell.get())):
                    continue
                aid = row["account_id"]
                acc = (state["acc_widgets"][aid].get().strip()
                       if aid in state["acc_widgets"] else aid)
                tkr = state["tickers"].get(row["isin"], "")
                if tkr:
                    out.append((acc, row["kind"], tkr,
                                parse_sheet_date(row["date"]) or row["date"], row["qty"]))
            return out

        def refresh_preview():
            tree.delete(*tree.get_children())
            sigs = self._existing_signatures()
            by_sig = self._existing_tx_by_sig()
            filled = set()
            div_sigs = self._existing_div_signatures()
            n_new = n_dup = n_nobrok = n_fill = 0
            n_div_new = n_div_dup = 0
            swap_list = self._placeholders_replaced_by(real_entries())
            n_swap = len(swap_list)
            swap_set = {id(t) for t in swap_list}     # stand-ins that are about to go
            n_paste = 0
            for row in state["rows"]:
                aid = row["account_id"]
                acc = state["acc_widgets"][aid].get().strip() if aid in state["acc_widgets"] else aid
                ticker = state["tickers"].get(row["isin"], "") or code_to_ticker(row.get("name", ""))
                date = parse_sheet_date(row["date"]) or row["date"]
                tags = []
                if row["kind"] == "DIV":
                    # same per-share rule as the import itself, so the preview
                    # never disagrees with what actually gets stored
                    amt, qty = row.get("amount"), row.get("qty")
                    ps = (amt / qty) if (amt and qty) else row["price"]
                    is_dup = (ps is not None) and (
                        self._div_signature(acc, ticker, date, ps, qty) in div_sigs)
                    if is_dup:
                        status, n_div_dup = "dup", n_div_dup + 1
                        tags.append("dup")
                    else:
                        status, n_div_new = "DIV", n_div_new + 1
                        tags.append("new")
                else:
                    is_paste = bool(row.get("paste"))
                    isin_v = "" if str(row["isin"]).startswith("PASTE:") else row["isin"]
                    sig = self._tx_signature(acc, row["kind"], date,
                                             isin_v, row["qty"], row["price"])
                    is_dup = (sig in sigs
                              and not any(id(t) in swap_set for t in by_sig.get(sig, []))
                              ) or (is_paste and self._paste_on_file(
                                  acc, row["kind"], ticker, date, row["qty"]))
                    if is_paste and not is_dup:
                        n_paste += 1
                    if is_dup:
                        status, n_dup = "dup", n_dup + 1
                        tags.append("dup")
                        # already stored WITHOUT brokerage, and this statement has it
                        if row["courtage"]:
                            t_fill = next((t for t in by_sig.get(sig, [])
                                           if not self._tx_courtage(t)
                                           and id(t) not in filled), None)
                            if t_fill is not None:
                                filled.add(id(t_fill))
                                status, n_fill = "fill", n_fill + 1
                    else:
                        status, n_new = ("paste" if is_paste else "NEW"), n_new + 1
                        tags.append("new")
                    if not row["courtage"] and not is_dup and not is_paste:
                        n_nobrok += 1
                        tags.append("nobrok")
                tree.insert("", "end", values=(
                    status, date, row["kind"],
                    acc, ticker, row["name"], fnum(row["qty"], 0),
                    fnum(row["price"]), fnum(row["courtage"])), tags=tags)
            fill_txt = (f", {n_fill} of them get their brokerage filled in"
                        if n_fill else "")
            paste_txt = (f"  {n_paste} pasted order(s) - no brokerage until the statement arrives."
                         if n_paste else "")
            swap_txt = (f"  {n_swap} earlier pasted order(s) get replaced by the real rows."
                        if n_swap else "")
            info.config(text=f"{n_new} new buy/sell, {n_dup} duplicates (skipped{fill_txt})   |   "
                             f"{n_div_new} NEW dividends, {n_div_dup} already on file.  "
                             f"⚠ {n_nobrok} buy/sell rows have NO brokerage (check)."
                             f"{paste_txt}{swap_txt}",
                        fg=C_WARN if n_nobrok else C_ACCENT)

        def combine(errors=None):
            """rows = the statement rows + the pasted orders; rebuild mapping + preview."""
            allrows = state["file_rows"] + state["pasted"]
            account_ids = {r["account_id"] for r in allrows if r["account_id"]}
            isins = {r["isin"] for r in allrows
                     if r["isin"] and not str(r["isin"]).startswith("PASTE:")}
            keep = {aid: ent.get() for aid, ent in state["acc_widgets"].items()}
            state["rows"] = allrows
            state["parsed"] = True
            build_account_rows(account_ids)
            for aid, val in keep.items():          # keep what was typed in the mapping
                if aid in state["acc_widgets"] and val.strip():
                    state["acc_widgets"][aid].delete(0, "end")
                    state["acc_widgets"][aid].insert(0, val)
            # seed tickers from cache
            for isin in isins:
                if isin in self.pf.isin_map:
                    state["tickers"][isin] = self.pf.isin_map[isin]
            msg = (f"Parsed {len(allrows)} rows ({len(state['pasted'])} pasted), "
                   f"{len(account_ids)} accounts, {len(isins)} securities.")
            if errors:
                msg += "  Errors: " + "; ".join(errors)
            info.config(text=msg, fg=C_ACCENT)
            refresh_preview()
            # resolve missing tickers in background
            missing = [i for i in isins if i not in state["tickers"]]
            if missing:
                resolve_tickers(missing)

        def parse_files():
            if not state["files"] and not state["pasted"]:
                info.config(text="No CSV files. Use 'Add files...', drop them in the "
                                 "folder, or 'Paste orders...'.", fg=C_BAD)
                return
            allrows = []
            errors = []
            for p in state["files"]:
                try:
                    broker, rows = read_statement(p)
                    if not broker:
                        errors.append(os.path.basename(p) + " (unrecognised)")
                        continue
                    allrows.extend(rows)
                except Exception as e:
                    errors.append(f"{os.path.basename(p)}: {e}")
            state["file_rows"] = allrows
            combine(errors)

        def paste_orders():
            pt = tk.Toplevel(top, bg=C_BG3)
            pt.title("Paste orders - Nordnet order view")
            init_dialog(pt, top)
            pt.geometry("640x580")
            tk.Label(pt, text="Paste finished orders", bg=C_BG3, fg=C_ACCENT,
                     font=("Segoe UI", 14, "bold")).pack(pady=(12, 2))
            tk.Label(pt, text="For a trade the statement does not list yet. In Nordnet open the "
                     "order view, copy the finished orders (Säljorder / Köporder ... Avslutad) "
                     "and paste them below. Only finished orders count. The text has no date "
                     "and no brokerage: set the trade date here; the real rows replace the "
                     "pasted ones when the statement arrives.",
                     bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                     wraplength=600, justify="left").pack(padx=14)
            txt = mk_text(pt, height=14, bg=C_BG2, fg=C_FG, insertbackground=C_FG,
                          relief="flat", font=FONT_MONO, wrap="word")
            txt.pack(fill="both", expand=True, padx=14, pady=6)
            drow = tk.Frame(pt, bg=C_BG3)
            drow.pack(fill="x", padx=14)
            tk.Label(drow, text="Trade date (YYYY-MM-DD):", bg=C_BG3, fg=C_FG,
                     font=FONT).pack(side="left")
            e_date = mk_entry(drow, width=12, bg=C_BG2, fg=C_FG, insertbackground=C_FG,
                              relief="flat", font=FONT)
            e_date.insert(0, today_str())
            e_date.pack(side="left", padx=6)
            res = tk.Label(pt, text="", bg=C_BG3, fg=C_FG_DIM, font=FONT,
                           wraplength=600, justify="left", anchor="w")
            res.pack(fill="x", padx=14, pady=4)

            def from_clip():
                try:
                    txt.delete("1.0", "end")
                    txt.insert("1.0", pt.clipboard_get())
                except Exception:
                    res.config(text="The clipboard has no text.", fg=C_BAD)

            def add():
                date = parse_sheet_date(e_date.get().strip())
                if not date:
                    res.config(text="The date must look like 2026-11-24.", fg=C_BAD)
                    return
                orders, problems = parse_order_paste(txt.get("1.0", "end"))
                if not orders and not problems:
                    res.config(text="Found no orders in that text. Paste the order view "
                                    "(it starts with 'Säljorder' or 'Köporder').", fg=C_BAD)
                    return
                added = 0
                for o in orders:
                    tkr = self._match_ticker_by_name(o["name"], o["account_id"], o["kind"])
                    if not tkr:
                        problems.append(f"{o['name']}: no clear match among your companies "
                                        f"- import a statement that mentions it first")
                        continue
                    isin = self.isin_of(tkr) or ("PASTE:" + tkr)
                    state["tickers"][isin] = tkr
                    new = {"broker": "nordnet", "date": date, "account_id": o["account_id"],
                           "kind": o["kind"], "name": o["name"], "isin": isin,
                           "qty": o["qty"], "price": o["price"], "courtage": 0.0,
                           "amount": None, "ref": "paste", "paste": True}
                    same = lambda r: all(r.get(k) == new[k] for k in
                                         ("date", "account_id", "kind", "isin", "qty", "price"))
                    if any(same(r) for r in state["pasted"]):
                        problems.append(f"{o['name']}: already in the list")
                        continue
                    state["pasted"].append(new)
                    added += 1
                if added:
                    combine()
                    info.config(text=f"{added} pasted order(s) added - check the rows marked "
                                     f"'paste', then Import.  " + info.cget("text"),
                                fg=C_ACCENT)
                if problems:
                    res.config(text="Left out:  " + "  |  ".join(problems), fg=C_WARN)
                if added and not problems:
                    pt.destroy()

            bb2 = tk.Frame(pt, bg=C_BG3)
            bb2.pack(pady=8)
            self._btn(bb2, "Paste from clipboard", from_clip, BTN_REFRESH).pack(side="left", padx=4)
            self._btn(bb2, "Add to import", add, BTN_DIALOG_OK).pack(side="left", padx=4)
            self._btn(bb2, "Close", pt.destroy, BTN_DIALOG_CANCEL).pack(side="left", padx=4)
            txt.focus_set()

        def resolve_tickers(missing):
            info.config(text=f"Resolving {len(missing)} tickers from ISIN...", fg=C_FG_DIM)

            def work():
                for isin in missing:
                    try:
                        t = yahoo_isin_to_ticker(isin)
                        if t:
                            state["tickers"][isin] = t
                            self.pf.isin_map[isin] = t
                    except Exception as e:
                        log(f"isin resolve failed {isin}: {e}")
                def done():
                    self.pf.save()
                    refresh_preview()
                    info.config(text="Tickers resolved. Review the preview, then Import. "
                                     "(Foreign dual-listings may need a manual fix later.)",
                                fg=C_ACCENT)
                self.root.after(0, done)
            threading.Thread(target=work, daemon=True).start()

        def do_import():
            if not state["parsed"]:
                info.config(text="Click 'Scan / parse' first.", fg=C_BAD)
                return
            # persist account mapping
            for aid, ent in state["acc_widgets"].items():
                val = ent.get().strip()
                if val:
                    self.account_map[aid] = val
                    if val not in self.accounts:
                        self.accounts.append(val)
            self.S["account_map"] = self.account_map
            self.S["accounts"] = self.accounts
            # auto-set each account's broker from the statement source (so the
            # Nordnet depot is never mislabelled). Keep an owner/broker the user
            # has already set.
            for row in state["rows"]:
                aid = row["account_id"]
                acc = state["acc_widgets"][aid].get().strip() if aid in state["acc_widgets"] else aid
                if not acc:
                    continue
                meta = self.account_meta.setdefault(acc, {})
                if not meta.get("broker"):
                    meta["broker"] = "Nordnet" if row["broker"] == "nordnet" else "Avanza"
            self.S["account_meta"] = self.account_meta
            save_settings(self.S)

            # Pasted orders from an earlier session are only stand-ins: once the
            # real statement rows for the same trade are here, the stand-in goes.
            gone = self._placeholders_replaced_by(real_entries(only_on=True))
            n_swap = len(gone)
            if gone:
                gone_ids = {id(t) for t in gone}
                self.pf.transactions = [t for t in self.pf.transactions
                                        if id(t) not in gone_ids]

            sigs = self._existing_signatures()
            by_sig = self._existing_tx_by_sig()
            div_sigs = self._existing_div_signatures()
            n_tx = n_div = n_div_dup = n_fill = n_paste = n_paste_skip = 0
            for row in state["rows"]:
                aid = row["account_id"]
                acc = state["acc_widgets"][aid].get().strip() if aid in state["acc_widgets"] else aid
                ticker = state["tickers"].get(row["isin"], "")
                date = parse_sheet_date(row["date"]) or row["date"]
                if not ticker or row["qty"] is None:
                    continue
                if row["kind"] == "DIV":
                    if not v_div.get():
                        continue
                    amt = row.get("amount")
                    qty = row.get("qty")
                    # amount/shares is the reliable per-share; the broker's
                    # "Kurs" column is not always the dividend per share.
                    ps = (amt / qty) if (amt and qty) else row["price"]
                    if ps is None:
                        continue
                    dsig = self._div_signature(acc, ticker, date, ps, qty)
                    if dsig in div_sigs:
                        n_div_dup += 1
                        continue
                    self.pf.dividends.append({
                        "id": str(int(time.time() * 1e6)) + str(len(self.pf.dividends)),
                        "ticker": ticker, "date": date, "per_share": ps,
                        "shares": qty, "account": acc, "amount": amt,
                        "note": f"imported ({row['broker']})", "verified": True})
                    div_sigs.add(dsig)
                    n_div += 1
                    continue
                if row["kind"] == "BUY" and not v_buy.get():
                    continue
                if row["kind"] == "SELL" and not v_sell.get():
                    continue
                is_paste = bool(row.get("paste"))
                isin_v = "" if str(row["isin"]).startswith("PASTE:") else row["isin"]
                if is_paste and self._paste_on_file(acc, row["kind"], ticker, date,
                                                    row["qty"]):
                    n_paste_skip += 1        # the real statement rows are already here
                    continue
                sig = self._tx_signature(acc, row["kind"], date, isin_v,
                                         row["qty"], row["price"])
                if sig in sigs:
                    # Already stored.  If it was stored WITHOUT brokerage (the
                    # broker had not booked the fee yet) and this newer
                    # statement carries it, fill it in on the existing row.
                    if row["courtage"]:
                        for t in by_sig.get(sig, []):
                            if not self._tx_courtage(t):
                                t["courtage"] = row["courtage"]
                                if row.get("ref") and not t.get("ref"):
                                    t["ref"] = row["ref"]
                                t["verified"] = True
                                n_fill += 1
                                break
                    continue
                new_tx = {
                    "id": self.pf._new_id() + str(len(self.pf.transactions)),
                    "ticker": ticker, "company": row["name"], "account": acc,
                    "type": row["kind"], "date": date, "shares": row["qty"],
                    "price": row["price"] or 0.0, "courtage": row["courtage"] or 0.0,
                    "isin": isin_v,
                    "note": ("pasted (nordnet order) - no brokerage yet" if is_paste
                             else f"imported ({row['broker']})"),
                    "verified": not is_paste, "ref": row.get("ref", "")}
                self.pf.transactions.append(new_tx)
                by_sig.setdefault(sig, []).append(new_tx)
                if row["name"] and not is_paste:    # the order view's name is not the statement's
                    self.pf.instruments.setdefault(ticker, {})["company"] = row["name"]
                sigs.add(sig)
                n_tx += 1
                n_paste += 1 if is_paste else 0
            self.pf.save()
            self.after_data_change()
            msg = (f"Imported {n_tx} transactions and {n_div} dividends "
                   f"({n_div_dup} dividends were already on file).")
            if n_fill:
                msg += (f"  {n_fill} stored trade(s) had no brokerage - it was "
                        f"filled in from this statement.")
            if n_paste:
                msg += (f"  {n_paste} of them are pasted orders (no brokerage yet) - "
                        f"they are replaced when the statement arrives.")
            if n_swap:
                msg += f"  {n_swap} earlier pasted order(s) replaced by the real rows."
            if n_paste_skip:
                msg += f"  {n_paste_skip} pasted order(s) skipped - already on file."

            self.S["archive_imported_csv"] = v_archive.get()
            save_settings(self.S)
            if v_archive.get() and state["files"]:
                moved, failures = self._archive_statements(state["files"], msg)
                state["files"] = []
                files_lbl.config(text="0 - the files were filed away")
                if moved:
                    msg += (f"  {len(moved)} statement file(s) moved to "
                            f"Helpfiles\\StockFolio\\imported\\ - the data is in "
                            f"the portfolio now, you do not need them again.")
                if failures:
                    msg += "  COULD NOT MOVE: " + "; ".join(failures)
            info.config(text=msg, fg=C_BAD if "COULD NOT MOVE" in msg else C_ACCENT)
            flash_ok(self.root, f"Imported {n_tx} tx, {n_div} div")

        def edit_tickers():
            # collect ISIN -> name from parsed rows
            seen = {}
            for r in state["rows"]:
                if r["isin"] and r["isin"] not in seen:
                    seen[r["isin"]] = r["name"]
            if not seen:
                info.config(text="Parse the files first.", fg=C_BAD)
                return
            etop = tk.Toplevel(top, bg=C_BG3)
            etop.title("Edit tickers (ISIN -> Yahoo symbol)")
            init_dialog(etop, top)
            etop.geometry("520x520")
            tk.Label(etop, text="Fix any wrong tickers (e.g. AZN.L -> AZN.ST). "
                     "Stockholm uses .ST", bg=C_BG3, fg=C_FG_DIM,
                     font=("Segoe UI", 8, "italic")).pack(pady=(10, 4))
            cv = tk.Canvas(etop, bg=C_BG3, highlightthickness=0)
            sb = ttk.Scrollbar(etop, orient="vertical", command=cv.yview)
            inner = tk.Frame(cv, bg=C_BG3)
            cv.configure(yscrollcommand=sb.set)
            cv.pack(side="left", fill="both", expand=True, padx=(12, 0), pady=6)
            sb.pack(side="right", fill="y")
            cv.create_window((0, 0), window=inner, anchor="nw")
            inner.bind("<Configure>", lambda e: cv.configure(scrollregion=cv.bbox("all")))
            bind_mousewheel(cv, cv)
            ents = {}
            for i, (isin, name) in enumerate(sorted(seen.items(), key=lambda x: x[1])):
                tk.Label(inner, text=name[:26], bg=C_BG3, fg=C_FG, font=FONT,
                         width=26, anchor="w").grid(row=i, column=0, sticky="w", pady=2)
                tk.Label(inner, text=isin, bg=C_BG3, fg=C_FG_DIM, font=("Consolas", 8),
                         width=14, anchor="w").grid(row=i, column=1, sticky="w")
                e = mk_entry(inner, width=14, bg=C_BG2, fg=C_FG,
                             insertbackground=C_FG, relief="flat", font=FONT)
                e.grid(row=i, column=2, padx=6)
                e.insert(0, state["tickers"].get(isin, ""))
                ents[isin] = e

            def save_tickers():
                for isin, e in ents.items():
                    t = e.get().strip().upper()
                    if t:
                        state["tickers"][isin] = t
                        self.pf.isin_map[isin] = t
                self.pf.save()
                refresh_preview()
                etop.destroy()
                flash_ok(self.root, "Tickers saved")
            self._btn(etop, "Save", save_tickers, BTN_DIALOG_OK).pack(pady=8)

        btns = tk.Frame(top, bg=C_BG3)
        btns.pack(pady=10)
        self._btn(btns, "Scan / parse", parse_files, BTN_REFRESH).pack(side="left", padx=4)
        self._btn(btns, "Paste orders...", paste_orders, BTN_REFRESH).pack(side="left", padx=4)
        self._btn(btns, "Edit tickers...", edit_tickers, BTN_REFRESH).pack(side="left", padx=4)
        self._btn(btns, "Import (verified)", do_import, BTN_DIALOG_OK).pack(side="left", padx=4)
        self._btn(btns, "Open imported folder", self._open_imported_folder,
                  BTN_REFRESH).pack(side="left", padx=4)
        self._btn(btns, "Close", top.destroy, BTN_DIALOG_CANCEL).pack(side="left", padx=4)

        # auto-parse if files were found in the folder
        if found:
            top.after(150, parse_files)


# ============================================================================
#  DEL 17F ... DUPLICATE FINDER  (clean up after an import that doubled rows)
# ============================================================================
    def _dup_score(self, r):
        """How trustworthy a record is - the highest score is kept.

        A row that came from a broker statement carries an ISIN, a brokerage
        fee and verified=True.  A row that came from the Google Sheet carries
        none of that, so when the same trade exists twice the broker copy is
        always the one worth keeping.
        """
        s = 0
        if r.get("verified"):
            s += 8
        if r.get("isin"):
            s += 4
        if "(" in (r.get("note") or ""):      # "imported (avanza)" / "(nordnet)"
            s += 2
        if r.get("courtage"):
            s += 1
        if (r.get("account") or "").strip():
            s += 1
        return s

    def _dup_scan(self):
        """Find records that look like the SAME thing stored twice.

        Accounts are deliberately IGNORED in the keys.  The duplicates this
        has to catch come from importing the Google Sheet on top of the
        broker CSV, where one copy carries the sheet's account name and the
        other the broker's - so an account-aware key would never see them.

        Returns a list of groups, each  {kind, level, title, items} , with
        items sorted best-first (the first one is the suggested keeper).
        """
        groups = []

        def add(kind, level, title, items):
            items = sorted(items, key=self._dup_score, reverse=True)
            groups.append({"kind": kind, "level": level, "title": title,
                           "items": items})

        # ---- transactions: identical ticker/type/date/shares/price ----------
        strict = collections.defaultdict(list)
        for t in self.pf.transactions:
            strict[((t.get("ticker") or "").upper(), t.get("type", "BUY"),
                    t.get("date", ""), round(float(t.get("shares") or 0), 3),
                    round(float(t.get("price") or 0), 4))].append(t)
        seen = set()
        for k, items in strict.items():
            if len(items) < 2:
                continue
            for t in items:
                seen.add(id(t))
            add("tx", "certain",
                f"{k[0]}  {k[1]}  {k[2]}   {fnum(k[3], 0)} sh @ {fnum(k[4])}"
                f"   -  {len(items)} identical rows", items)

        # ---- transactions: same trade, different price or date -------------
        loose = collections.defaultdict(list)
        for t in self.pf.transactions:
            if id(t) in seen:
                continue
            loose[((t.get("ticker") or "").upper(), t.get("type", "BUY"),
                   t.get("date", ""),
                   round(float(t.get("shares") or 0), 3))].append(t)
        for k, items in loose.items():
            if len(items) < 2:
                continue
            add("tx", "likely",
                f"{k[0]}  {k[1]}  {k[2]}   {fnum(k[3], 0)} sh"
                f"   -  {len(items)} rows, prices differ", items)

        # ---- transactions with no account at all ---------------------------
        orphans = [t for t in self.pf.transactions
                   if not (t.get("account") or "").strip()]
        for t in orphans:
            tick = (t.get("ticker") or "").upper()
            same_day = sum(1 for o in self.pf.transactions
                           if o is not t
                           and (o.get("ticker") or "").upper() == tick
                           and o.get("date", "") == t.get("date", ""))
            add("tx", "orphan",
                f"{tick}  {t.get('type','BUY')}  {t.get('date','')}   "
                f"{fnum(t.get('shares') or 0, 0)} sh   -  NO ACCOUNT, "
                f"{same_day} other row(s) that day - tick it yourself if it is "
                f"a leftover", [t])

        # ---- dividends -----------------------------------------------------
        dstrict = collections.defaultdict(list)
        for d in self.pf.dividends:
            dstrict[self._div_signature(d.get("account", ""), d.get("ticker", ""),
                                        d.get("date", ""), d.get("per_share", 0),
                                        d.get("shares", 0))].append(d)
        for k, items in dstrict.items():
            if len(items) < 2:
                continue
            add("div", "certain",
                f"{(items[0].get('ticker') or '').upper()}  {items[0].get('date','')}"
                f"   {fnum(items[0].get('per_share') or 0)} /share"
                f"   -  {len(items)} identical dividend rows", items)
        return groups

    def open_duplicates(self):
        """Show duplicate rows and let the user delete the extra copies."""
        top = tk.Toplevel(self.root, bg=C_BG3)
        top.title("Find duplicates")
        init_dialog(top, self.root)
        top.geometry("1000x680")

        tk.Label(top, text="Find duplicates", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 14, "bold")).pack(pady=(12, 2))
        tk.Label(top, text="CLICK A ROW to switch it between  keep  and  DELETE.",
                 bg=C_BG3, fg=C_WARN, font=FONT_B).pack(pady=(2, 2))
        tk.Label(top, text="Rows that look like the same trade stored twice - typically "
                 "a Google Sheet import landing on top of the broker CSV. Identical rows "
                 "(green heading) are already set to DELETE for you, and the broker copy - "
                 "the one with an ISIN and a brokerage fee - is kept. Groups where only "
                 "the PRICE differs (amber) and rows with NO account (red) are left on "
                 "keep: those can also be two real trades on the same day, so you decide.",
                 bg=C_BG3, fg=C_FG_DIM, font=FONT, wraplength=950,
                 justify="left").pack(pady=(0, 6), padx=12)

        wrap = tk.Frame(top, bg=C_BG3)
        wrap.pack(fill="both", expand=True, padx=12)
        cols = ("del", "date", "type", "ticker", "account", "shares", "price",
                "courtage", "source")
        tree = ttk.Treeview(wrap, columns=cols, show="tree headings", selectmode="browse")
        tree.heading("#0", text="Duplicate group")
        tree.column("#0", width=330, anchor="w")
        for c, t, w in (("del", "Keep / Delete", 100), ("date", "Date", 88),
                        ("type", "Type", 50), ("ticker", "Ticker", 95),
                        ("account", "Account", 150), ("shares", "Shares", 70),
                        ("price", "Price", 74), ("courtage", "Brokerage", 74),
                        ("source", "Source", 120)):
            tree.heading(c, text=t)
            tree.column(c, width=w, anchor="w" if c in (
                "ticker", "account", "type", "source") else "e")
        tree.column("del", anchor="center")
        vs = ttk.Scrollbar(wrap, orient="vertical", command=tree.yview)
        hs = ttk.Scrollbar(wrap, orient="horizontal", command=tree.xview)
        tree.configure(yscrollcommand=vs.set, xscrollcommand=hs.set)
        vs.grid(row=0, column=1, sticky="ns")
        hs.grid(row=1, column=0, sticky="ew")
        tree.grid(row=0, column=0, sticky="nsew")
        wrap.rowconfigure(0, weight=1)
        wrap.columnconfigure(0, weight=1)
        bind_mousewheel(tree)
        tree.tag_configure("certain", foreground=C_ACCENT, font=FONT_B)
        tree.tag_configure("likely", foreground=C_WARN, font=FONT_B)
        tree.tag_configure("orphan", foreground=C_BAD, font=FONT_B)
        tree.tag_configure("keep", foreground=C_FG_DIM)
        tree.tag_configure("drop", foreground=C_BAD, font=FONT_B)

        info = tk.Label(top, text="", bg=C_BG3, fg=C_ACCENT, font=FONT)
        info.pack(pady=(6, 0))

        state = {"groups": [], "marked": {}, "rec": {}}

        def suggest(levels=("certain",)):
            """Tick every copy except the best one, in the chosen group levels.

            Only "certain" (byte-for-byte the same trade) is ticked by
            default.  A "prices differ" group CAN be two real purchases made
            the same day for two different people, so that one is left to the
            user - the "Also tick 'prices differ'" button does it in one go.
            """
            state["marked"].clear()
            for gi, g in enumerate(state["groups"]):
                for ii, r in enumerate(g["items"]):
                    state["marked"][f"M:{gi}:{ii}"] = (ii > 0 and g["level"] in levels)
            redraw()

        def source_of(r):
            n = (r.get("note") or "").strip()
            if r.get("verified") or "(" in n:
                return n or "broker"
            return n or "manual"

        def redraw(rescan=False):
            if rescan:
                state["groups"] = self._dup_scan()
            tree.delete(*tree.get_children())
            state["rec"].clear()
            n_marked = 0
            for gi, g in enumerate(state["groups"]):
                gid = f"G:{gi}"
                tree.insert("", "end", iid=gid, text=g["title"], open=True,
                            tags=(g["level"],))
                for ii, r in enumerate(g["items"]):
                    iid = f"M:{gi}:{ii}"
                    state["rec"][iid] = (g["kind"], r)
                    marked = state["marked"].get(iid, False)
                    if marked:
                        n_marked += 1
                    mark = "DELETE" if marked else "keep"
                    if g["kind"] == "div":
                        vals = (mark, r.get("date", ""),
                                "DIV", (r.get("ticker") or "").upper(),
                                self.account_short(r.get("account", "")) or "(none)",
                                fnum(r.get("shares") or 0, 0),
                                fnum(r.get("per_share") or 0), "",
                                source_of(r))
                    else:
                        vals = (mark, r.get("date", ""),
                                r.get("type", "BUY"), (r.get("ticker") or "").upper(),
                                self.account_short(r.get("account", "")) or "(none)",
                                fnum(r.get("shares") or 0, 0),
                                fnum(r.get("price") or 0),
                                fnum(r.get("courtage") or 0), source_of(r))
                    tree.insert(gid, "end", iid=iid, text="", values=vals,
                                tags=("drop" if marked else "keep",))
            lv = collections.Counter(g["level"] for g in state["groups"])
            n_groups = len(state["groups"])
            if not n_groups:
                info.config(text="No duplicates found - the portfolio is clean.", fg=C_ACCENT)
            elif n_marked:
                info.config(text=f"{lv['certain']} identical, {lv['likely']} where the "
                                 f"price differs, {lv['orphan']} without an account   |   "
                                 f"{n_marked} rows set to DELETE", fg=C_WARN)
            else:
                info.config(text=f"{lv['certain']} identical, {lv['likely']} where the "
                                 f"price differs, {lv['orphan']} without an account   |   "
                                 "nothing is set to DELETE - click the rows you want gone",
                            fg=C_ACCENT)

        def toggle(iid):
            if not iid.startswith("M:"):
                return
            state["marked"][iid] = not state["marked"].get(iid, False)
            redraw()
            tree.see(iid)
            tree.selection_set(iid)
            tree.focus(iid)

        def on_click(event):
            # the WHOLE row toggles, not just the mark - a 46-pixel "[ ]" in
            # the middle of the table is not something anyone finds
            if tree.identify_region(event.x, event.y) not in ("cell", "tree"):
                return
            toggle(tree.identify_row(event.y))

        tree.bind("<Button-1>", on_click)
        tree.bind("<space>", lambda e: toggle(tree.focus()))
        tree.bind("<Return>", lambda e: toggle(tree.focus()))

        def untick():
            state["marked"].clear()
            redraw()

        def do_delete():
            drop_tx, drop_div = [], []
            for iid, marked in state["marked"].items():
                if not marked or iid not in state["rec"]:
                    continue
                kind, r = state["rec"][iid]
                (drop_div if kind == "div" else drop_tx).append(r)
            if not drop_tx and not drop_div:
                messagebox.showinfo(APP_NAME, "No row is marked DELETE.", parent=top)
                return
            if not messagebox.askyesno(APP_NAME,
                    f"Delete {len(drop_tx)} transactions and {len(drop_div)} "
                    "dividends?\n\nA timestamped backup of the portfolio is "
                    "written first, so this can be undone with "
                    "File > Restore from backup.", parent=top):
                return
            drop_tx_ids = {id(r) for r in drop_tx}
            drop_div_ids = {id(r) for r in drop_div}
            self.pf.transactions = [t for t in self.pf.transactions
                                    if id(t) not in drop_tx_ids]
            self.pf.dividends = [d for d in self.pf.dividends
                                 if id(d) not in drop_div_ids]
            self.pf.save()
            self.after_data_change()
            state["marked"].clear()
            redraw(rescan=True)
            flash_ok(self.root, f"Deleted {len(drop_tx) + len(drop_div)} rows")

        btns = tk.Frame(top, bg=C_BG3)
        btns.pack(pady=10)
        self._btn(btns, "Suggest (keep the broker copy)", suggest, BTN_DIALOG_OK).pack(side="left", padx=4)
        self._btn(btns, "Also delete 'prices differ'",
                  lambda: suggest(("certain", "likely")), BTN_DIALOG_CANCEL).pack(side="left", padx=4)
        self._btn(btns, "Keep everything", untick, BTN_DIALOG_CANCEL).pack(side="left", padx=4)
        self._btn(btns, "Delete the marked rows", do_delete, BTN_DIALOG_OK).pack(side="left", padx=4)
        self._btn(btns, "Rescan", lambda: redraw(rescan=True), BTN_DIALOG_CANCEL).pack(side="left", padx=4)
        self._btn(btns, "Close", top.destroy, BTN_DIALOG_CANCEL).pack(side="left", padx=4)

        state["groups"] = self._dup_scan()
        suggest()


# ============================================================================
#  DEL 17D ... PRICE HISTORY  ("Kurser" tab -> own JSON, low/high per stock)
# ============================================================================
    def open_price_history(self):
        top = tk.Toplevel(self.root, bg=C_BG3)
        top.title("Price history")
        init_dialog(top, self.root)
        top.geometry("960x620")

        tk.Label(top, text="Price history (accumulated)",
                 bg=C_BG3, fg=C_ACCENT, font=("Segoe UI", 14, "bold")).pack(pady=(12, 0))
        tk.Label(top, text="Dates are kept permanently here even if you delete "
                 "them from the sheet. Double-click a row to see every date.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic")).pack()

        bar = tk.Frame(top, bg=C_BG3)
        bar.pack(fill="x", padx=12, pady=8)
        info = tk.Label(bar, text="", bg=C_BG3, fg=C_ACCENT, font=FONT)
        info.pack(side="right")

        wrap = tk.Frame(top, bg=C_BG3)
        wrap.pack(fill="both", expand=True, padx=12, pady=4)
        cols = ("company", "ticker", "n", "first", "last", "low", "high", "latest")
        heads = {"company": "Company", "ticker": "Ticker", "n": "Days",
                 "first": "First", "last": "Last", "low": "Lowest (date)",
                 "high": "Highest (date)", "latest": "Latest"}
        widths = {"company": 180, "ticker": 110, "n": 55, "first": 90,
                  "last": 90, "low": 165, "high": 165, "latest": 80}
        tree = ttk.Treeview(wrap, columns=cols, show="headings", selectmode="browse")
        for c in cols:
            tree.heading(c, text=heads[c])
            tree.column(c, width=widths[c],
                        anchor="w" if c in ("company", "ticker", "low", "high") else "e")
        vs = ttk.Scrollbar(wrap, orient="vertical", command=tree.yview)
        tree.configure(yscrollcommand=vs.set)
        tree.pack(side="left", fill="both", expand=True)
        vs.pack(side="right", fill="y")
        bind_mousewheel(tree)

        def fill():
            tree.delete(*tree.get_children())
            rows = []
            for t, dmap in self.price_history.items():
                st = history_stats(dmap)
                if st:
                    rows.append((t, st))
            rows.sort(key=lambda x: self.pf.company_for(x[0], self.prices).lower())
            for t, st in rows:
                tree.insert("", "end", iid=t, values=(
                    self.pf.company_for(t, self.prices), t, st["n"],
                    st["first"], st["last"],
                    f"{fnum(st['low'])}  ({st['low_date']})",
                    f"{fnum(st['high'])}  ({st['high_date']})",
                    fnum(st["latest"])))
            total_days = sum(len(d) for d in self.price_history.values())
            info.config(text=f"{len(rows)} tickers, {total_days} stored data points")

        fill()

        def update_from_sheet():
            url = self.gsheet.get("url", "")
            if not url:
                info.config(text="Set the sheet URL in 'Google Sheet' first.", fg=C_BAD)
                return
            info.config(text="Reading 'Kurser' tab...", fg=C_FG_DIM)
            top.update_idletasks()

            def work():
                try:
                    rows = read_gsheet_csv(url, self.gsheet.get("hist_gid", "1255905222"))
                    new = parse_kurser_history(rows)

                    def done():
                        added = merge_price_history(self.price_history, new)
                        save_price_history(self.price_history)
                        fill()
                        info.config(text=f"Added {added} new data points "
                                         f"({len(new)} tickers in sheet).", fg=C_ACCENT)
                    self.root.after(0, done)
                except Exception as e:
                    log(f"history update failed: {e}")
                    self.root.after(0, lambda: info.config(
                        text=f"Could not read sheet: {e}", fg=C_BAD))
            threading.Thread(target=work, daemon=True).start()

        def show_detail(event=None):
            sel = tree.selection()
            if not sel:
                return
            t = sel[0]
            dmap = self.price_history.get(t, {})
            st = history_stats(dmap)
            if not st:
                return
            dtop = tk.Toplevel(top, bg=C_BG3)
            dtop.title(f"Price history - {t}")
            init_dialog(dtop, top)
            dtop.geometry("620x620")
            tk.Label(dtop, text=self.pf.company_for(t, self.prices),
                     bg=C_BG3, fg=C_ACCENT, font=FONT_B).pack(pady=(10, 0))
            tk.Label(dtop, text=f"Low {fnum(st['low'])} ({st['low_date']})   "
                     f"High {fnum(st['high'])} ({st['high_date']})",
                     bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8)).pack()
            self._price_chart(dtop, t).pack(pady=(6, 4))
            dw = tk.Frame(dtop, bg=C_BG3)
            dw.pack(fill="both", expand=True, padx=10, pady=8)
            dt = ttk.Treeview(dw, columns=("d", "p"), show="headings", selectmode="none")
            dt.heading("d", text="Date")
            dt.heading("p", text="Price")
            dt.column("d", width=130, anchor="w")
            dt.column("p", width=110, anchor="e")
            dvs = ttk.Scrollbar(dw, orient="vertical", command=dt.yview)
            dt.configure(yscrollcommand=dvs.set)
            dt.pack(side="left", fill="both", expand=True)
            dvs.pack(side="right", fill="y")
            bind_mousewheel(dt)
            dt.tag_configure("lo", foreground=C_BAD)
            dt.tag_configure("hi", foreground=C_GOOD)
            for d, p in sorted(dmap.items()):
                tag = "lo" if d == st["low_date"] else ("hi" if d == st["high_date"] else "")
                dt.insert("", "end", values=(d, fnum(p)), tags=(tag,) if tag else ())
            self._btn(dtop, "Close", dtop.destroy, BTN_DIALOG_CANCEL).pack(pady=(0, 10))

        tree.bind("<Double-1>", show_detail)

        self._btn(bar, "Update from 'Kurser' tab", update_from_sheet, BTN_REFRESH).pack(side="left")
        self._btn(bar, "Show all dates", show_detail, BTN_REFRESH).pack(side="left", padx=6)

        btns = tk.Frame(top, bg=C_BG3)
        btns.pack(pady=8)
        self._btn(btns, "Close", top.destroy, BTN_DIALOG_CANCEL).pack()


# ============================================================================
#  DEL 17E ... ACCOUNTS / PEOPLE / COMPANY INFO
# ============================================================================
    def known_tickers(self):
        """Tickers from transactions plus any registered instrument."""
        out = list(self.pf.tickers())
        for t in self.pf.instruments:
            if t not in out:
                out.append(t)
        return out

    def isin_of(self, ticker):
        for t in self.pf.transactions:
            if t.get("ticker") == ticker and t.get("isin"):
                return t["isin"]
        for isin, tk_ in self.pf.isin_map.items():
            if tk_ == ticker:
                return isin
        return ""

    # ---- attention: compare the Google Sheet against the (correct) CSV data ----
    def open_attention(self):
        if not self.gsheet.get("url"):
            messagebox.showinfo(APP_NAME, "Set the Google Sheet URL first "
                                "(Tools > Google Sheet).")
            return
        top = tk.Toplevel(self.root, bg=C_BG3)
        top.title("Attention - sheet vs your data")
        init_dialog(top, self.root)
        top.geometry("820x560")
        tk.Label(top, text="Attention - the sheet disagrees with your data",
                 bg=C_BG3, fg=C_ACCENT, font=("Segoe UI", 14, "bold")).pack(pady=(12, 0))
        tk.Label(top, text="Your imported CSV data is treated as CORRECT. "
                 "These sheet values differ - you may have a typo in the sheet.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic")).pack()

        wrap = tk.Frame(top, bg=C_BG3)
        wrap.pack(fill="both", expand=True, padx=12, pady=8)
        cols = ("type", "ticker", "company", "yours", "sheet", "note")
        tree = ttk.Treeview(wrap, columns=cols, show="headings", selectmode="browse")
        for c, t, w in (("type", "Check", 90), ("ticker", "Ticker", 100),
                        ("company", "Company", 170), ("yours", "Your data (CSV)", 110),
                        ("sheet", "Sheet", 110), ("note", "Note", 200)):
            tree.heading(c, text=t)
            tree.column(c, width=w, anchor="w" if c in ("type", "ticker", "company", "note") else "e")
        vs = ttk.Scrollbar(wrap, orient="vertical", command=tree.yview)
        tree.configure(yscrollcommand=vs.set)
        tree.pack(side="left", fill="both", expand=True)
        vs.pack(side="right", fill="y")
        bind_mousewheel(tree)
        info = tk.Label(top, text="Reading the sheet...", bg=C_BG3, fg=C_FG_DIM, font=FONT)
        info.pack(pady=2)
        tree.bind("<Double-1>", lambda e: (tree.selection() and tree.item(
            tree.selection()[0], "values")[1] and self._show_company(
            tree.item(tree.selection()[0], "values")[1])))

        g = self.gsheet

        def work():
            problems = []
            try:
                # --- shares: program (truth) vs sheet "Aktier" tab ---
                prog_sh = {}
                for h in self.pf.holdings():
                    prog_sh[h["ticker"]] = prog_sh.get(h["ticker"], 0) + h["qty"]
                _, arows = read_gsheet_rows(g.get("url", ""), g.get("gid", "507464238"))
                sheet_sh = {}
                for r in arows:
                    t = code_to_ticker(r.get(g["col_code"], ""))
                    q = to_float(r.get(g["col_shares"], ""))
                    if t and q:
                        sheet_sh[t] = sheet_sh.get(t, 0) + q
                for t in sorted(set(prog_sh) | set(sheet_sh)):
                    pv, sv = prog_sh.get(t, 0), sheet_sh.get(t, 0)
                    if abs(pv - sv) > 0.5:
                        problems.append(("Shares", t, pv, sv,
                                         "Sheet missing this holding" if sv == 0 else
                                         ("Not in sheet" if pv == 0 else "Share count differs")))
                # --- dividend per-share: program received vs "Bolag" tab ---
                _, brows = read_gsheet_rows(g.get("url", ""), g.get("div_gid", "403105218"))
                for r in brows:
                    t = code_to_ticker(r.get(g["div_col_code"], ""))
                    sps = to_float(r.get(g["div_col_pershare"], ""))
                    if not t or sps is None or sps == 0:
                        continue
                    pps, consistent = self._inferred_per_share(t)
                    if pps and consistent and abs(pps - sps) > max(0.02 * pps, 0.01):
                        problems.append(("Dividend/share", t, pps, sps,
                                         "Your last paid differs from sheet"))

                def done():
                    tree.delete(*tree.get_children())
                    for typ, t, pv, sv, note in problems:
                        tree.insert("", "end", values=(
                            typ, t, self.pf.company_for(t, self.prices),
                            fnum(pv, 0) if typ == "Shares" else fnum(pv, 2),
                            fnum(sv, 0) if typ == "Shares" else fnum(sv, 2), note))
                    info.config(text=(f"{len(problems)} difference(s) found. "
                                      "Double-click to open a company.") if problems
                                else "✓ The sheet matches your data. Nothing to fix.",
                                fg=C_WARN if problems else C_ACCENT)
                self.root.after(0, done)
            except Exception as e:
                log(f"attention failed: {e}")
                self.root.after(0, lambda: info.config(text=f"Could not read sheet: {e}", fg=C_BAD))
        threading.Thread(target=work, daemon=True).start()
        self._btn(top, "Close", top.destroy, BTN_DIALOG_CANCEL).pack(pady=(0, 12))

    # ---- account manager: owner / broker / code ----
    def open_account_manager(self):
        top = tk.Toplevel(self.root, bg=C_BG3)
        top.title("Manage accounts")
        init_dialog(top, self.root)
        top.geometry("760x540")

        tk.Label(top, text="Accounts - owner, broker & section",
                 bg=C_BG3, fg=C_ACCENT, font=("Segoe UI", 14, "bold")).pack(pady=(12, 0))
        tk.Label(top, text="Owner = whose shares they are.  Section = the real broker account "
                 "they sit in, when that differs (e.g. Lars's and Benjamin's shares both sit in "
                 "the section \"Olga Avanza\"). Accounts with the same section are shown together "
                 "in Per account, but kept apart. Leave Section empty for an account of its own.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                 wraplength=700, justify="center").pack(pady=(0, 4))

        head = tk.Frame(top, bg=C_BG3)
        head.pack(fill="x", padx=14, pady=(8, 0))
        for txt, w in (("Account (from import)", 22), ("Owner / person", 13),
                       ("Broker", 12), ("Code", 6), ("Section", 17)):
            tk.Label(head, text=txt, bg=C_BG3, fg=C_ACCENT, font=FONT_B,
                     width=w, anchor="w").pack(side="left", padx=4)

        bb = tk.Frame(top, bg=C_BG3)
        bb.pack(side="bottom", pady=10)

        cv = tk.Canvas(top, bg=C_BG3, highlightthickness=0)
        sb = ttk.Scrollbar(top, orient="vertical", command=cv.yview)
        inner = tk.Frame(cv, bg=C_BG3)
        cv.configure(yscrollcommand=sb.set)
        cv.pack(side="left", fill="both", expand=True, padx=(14, 0), pady=6)
        sb.pack(side="right", fill="y")
        cv.create_window((0, 0), window=inner, anchor="nw")
        inner.bind("<Configure>", lambda e: cv.configure(scrollregion=cv.bbox("all")))
        bind_mousewheel(cv, cv)

        rows = []

        def add_row(acc, name_entry=None):
            fr = tk.Frame(inner, bg=C_BG3)
            fr.pack(fill="x", pady=2)
            m = self.account_meta.get(acc, {})
            if name_entry:
                e_name = mk_entry(fr, width=22, bg=C_BG2, fg=C_FG, insertbackground=C_FG,
                                  relief="flat", font=FONT)
                e_name.pack(side="left", padx=4)
            else:
                e_name = None
                tk.Label(fr, text=acc, bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 9),
                         width=22, anchor="w").pack(side="left", padx=4)
            ents = []
            for key, w in (("owner", 13), ("broker", 12), ("code", 6), ("section", 17)):
                e = mk_entry(fr, width=w, bg=C_BG2, fg=C_FG, insertbackground=C_FG,
                             relief="flat", font=FONT)
                e.insert(0, m.get(key, ""))
                e.pack(side="left", padx=4)
                ents.append(e)
            rows.append((acc, e_name, *ents))
            return e_name

        # accounts that are in use, plus any already given metadata (also prepared ones)
        accs = set(t.get("account", "") for t in self.pf.transactions if t.get("account"))
        accs |= set(self.account_meta.keys())
        for acc in sorted(accs):
            add_row(acc)

        def new_account():
            e = add_row("", name_entry=True)
            cv.update_idletasks()
            cv.yview_moveto(1.0)
            e.focus_set()

        def save():
            used = set(t.get("account", "") for t in self.pf.transactions if t.get("account"))
            for acc, e_name, e_owner, e_broker, e_code, e_sec in rows:
                if e_name is not None:
                    acc = e_name.get().strip()
                    if not acc:
                        continue
                    if acc not in self.accounts:
                        self.accounts.append(acc)
                meta = {"owner": e_owner.get().strip(),
                        "broker": e_broker.get().strip(),
                        "code": e_code.get().strip()}
                if e_sec.get().strip():
                    meta["section"] = e_sec.get().strip()
                self.account_meta[acc] = meta
            self.S["account_meta"] = self.account_meta
            self.S["accounts"] = self.accounts
            save_settings(self.S)
            top.destroy()
            self.after_data_change()
            flash_ok(self.root, "Accounts saved")

        self._btn(bb, "+ New account", new_account, BTN_DIALOG_OK).pack(side="left", padx=6)
        self._btn(bb, "Save", save, BTN_DIALOG_OK).pack(side="left", padx=6)
        self._btn(bb, "Close", top.destroy, BTN_DIALOG_CANCEL).pack(side="left", padx=6)
    # ---- quick overview: total value of the accounts you tick ----
    # First time only, the ticked accounts are this owner's accounts except
    # the ones with these codes; after that the choice is the user's own and is
    # kept in settings ("overview_accounts").
    OVERVIEW_DEFAULT_OWNER = "Lars"
    OVERVIEW_DEFAULT_SKIP = ("on", "oa")

    def _overview_accounts_in_use(self):
        accs = {t.get("account", "") for t in self.pf.transactions if t.get("account")}
        return sorted(accs, key=lambda a: (self.owner_of(a).casefold(),
                                           self.broker_of(a).casefold(),
                                           self.code_of(a).casefold(), a.casefold()))

    def _overview_default_accounts(self):
        return [a for a in self._overview_accounts_in_use()
                if self.owner_of(a).casefold() == self.OVERVIEW_DEFAULT_OWNER.casefold()
                and (self.account_meta.get(a, {}).get("code") or "").strip().casefold()
                not in self.OVERVIEW_DEFAULT_SKIP]

    def _overview_label(self, acc):
        m = self.account_meta.get(acc, {})
        parts = [self.owner_of(acc)]
        broker, code = (m.get("broker") or "").strip(), (m.get("code") or "").strip()
        if broker:
            parts.append(broker)
        txt = " - ".join(parts)
        if code:
            txt += f" ({code})"
        if acc != self.owner_of(acc):
            txt += f"   [{acc}]"
        return txt

    def open_overview(self):
        ui = getattr(self, "_ov_ui", None)
        if ui:
            try:
                if ui["top"].winfo_exists():
                    ui["top"].lift()
                    ui["top"].focus_force()
                    self._refresh_overview()
                    return
            except Exception:
                pass
        if self.S.get("overview_accounts") is None:
            self.S["overview_accounts"] = self._overview_default_accounts()
            save_settings(self.S)
        chosen = set(self.S.get("overview_accounts") or [])

        top = tk.Toplevel(self.root, bg=C_BG3)
        top.title("Quick overview - total value")
        top.transient(self.root)
        top.geometry("780x600")

        def close():
            self._ov_ui = None
            top.destroy()
        top.protocol("WM_DELETE_WINDOW", close)
        top.bind("<Escape>", lambda e: close())

        tk.Label(top, text="Quick overview", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 14, "bold")).pack(pady=(12, 0))
        total_lbl = tk.Label(top, text="", bg=C_BG3, fg=C_ACCENT,
                             font=("Segoe UI", 24, "bold"))
        total_lbl.pack()
        sub_lbl = tk.Label(top, text="", bg=C_BG3, fg=C_FG_DIM, font=FONT,
                           wraplength=740, justify="center")
        sub_lbl.pack(pady=(0, 6))

        # ---- which accounts count ----
        pick = tk.LabelFrame(top, text=" Accounts included - tick the ones you want ",
                             bg=C_BG3, fg=C_ACCENT, font=FONT_B, bd=1)
        pick.pack(fill="x", padx=14, pady=4)
        vars_ = {}

        def on_toggle():
            self.S["overview_accounts"] = [a for a, v in vars_.items() if v.get()]
            save_settings(self.S)
            self._refresh_overview()

        for i, acc in enumerate(self._overview_accounts_in_use()):
            var = tk.BooleanVar(value=acc in chosen)
            vars_[acc] = var
            tk.Checkbutton(pick, text=self._overview_label(acc), variable=var,
                           command=on_toggle, bg=C_BG3, fg=C_FG, selectcolor=C_BG2,
                           activebackground=C_BG3, font=FONT, highlightthickness=0,
                           anchor="w").grid(row=i // 2, column=i % 2, sticky="w",
                                            padx=8, pady=1)
        pick.grid_columnconfigure(0, weight=1)
        pick.grid_columnconfigure(1, weight=1)

        def set_all(val):
            for v in vars_.values():
                v.set(val)
            on_toggle()

        bb = tk.Frame(top, bg=C_BG3)
        bb.pack(pady=4)
        self._btn(bb, "Refresh prices", self.refresh_prices, BTN_REFRESH).pack(side="left", padx=4)
        self._btn(bb, "Tick all", lambda: set_all(True), BTN_REFRESH).pack(side="left", padx=4)
        self._btn(bb, "Tick none", lambda: set_all(False), BTN_REFRESH).pack(side="left", padx=4)
        self._btn(bb, "Close", close, BTN_DIALOG_CANCEL).pack(side="left", padx=4)

        # ---- result: broker -> account ----
        wrap = tk.Frame(top, bg=C_BG3)
        wrap.pack(fill="both", expand=True, padx=14, pady=(2, 4))
        cols = ("value", "invested", "pl", "plpct", "n")
        heads = {"value": "Value", "invested": "Invested", "pl": "Price +/-",
                 "plpct": "%", "n": "Holdings"}
        widths = {"value": 110, "invested": 110, "pl": 100, "plpct": 70, "n": 70}
        tree = ttk.Treeview(wrap, columns=cols, show="tree headings", selectmode="browse")
        tree.heading("#0", text="Broker login / account")
        tree.column("#0", width=300, anchor="w")
        for c in cols:
            tree.heading(c, text=heads[c])
            tree.column(c, width=widths[c], anchor="e")
        vs = ttk.Scrollbar(wrap, orient="vertical", command=tree.yview)
        tree.configure(yscrollcommand=vs.set)
        tree.pack(side="left", fill="both", expand=True)
        vs.pack(side="right", fill="y")
        bind_mousewheel(tree)
        tree.tag_configure("broker", background=C_BG2, foreground=C_ACCENT, font=FONT_B)
        tree.tag_configure("gain", foreground=C_GOOD)
        tree.tag_configure("loss", foreground=C_BAD)
        tree.tag_configure("total", background=C_BG2, foreground=C_ACCENT, font=FONT_B)

        tk.Label(top, text="Value = shares x current price (the price source you chose). "
                 "Cash balances are not tracked here. 'Invested' only counts holdings "
                 "that have a price, so Price +/- always compares like with like.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                 wraplength=740, justify="left").pack(padx=14, pady=(0, 10))

        self._ov_ui = {"top": top, "tree": tree, "total": total_lbl, "sub": sub_lbl}
        self._refresh_overview()

    def _refresh_overview(self):
        ui = getattr(self, "_ov_ui", None)
        if not ui:
            return
        try:
            if not ui["top"].winfo_exists():
                return
        except Exception:
            return
        sel = set(self.S.get("overview_accounts") or [])
        per = {}
        for h in self.pf.holdings():
            acc = h["account"]
            if acc not in sel:
                continue
            a = per.setdefault(acc, {"value": 0.0, "cost": 0.0, "n": 0, "missing": 0})
            a["n"] += 1
            price = self.active_price(h["ticker"])
            if price is None:
                a["missing"] += 1
            else:
                a["value"] += price * h["qty"]
                a["cost"] += h["cost"]

        def vals(v, c, n):
            pl = v - c
            pct = f"{pl / c * 100:+.1f}%" if c else "-"
            return (fnum(v, 0), fnum(c, 0), fnum(pl, 0), pct, str(n))

        def tag(v, c):
            return "gain" if v - c >= 0 else "loss"

        tree = ui["tree"]
        tree.delete(*tree.get_children())
        by_broker = {}
        for acc in per:
            sec = (self.account_meta.get(acc, {}).get("section") or "").strip()
            by_broker.setdefault(sec or self._overview_label(acc), []).append(acc)
        tv = tc = nh = missing = 0
        for broker in sorted(by_broker, key=str.casefold):
            accs = sorted(by_broker[broker], key=str.casefold)
            bv = sum(per[a]["value"] for a in accs)
            bc = sum(per[a]["cost"] for a in accs)
            bn = sum(per[a]["n"] for a in accs)
            node = tree.insert("", "end", open=True, text=broker,
                               values=vals(bv, bc, bn), tags=("broker",))
            for acc in accs:
                p = per[acc]
                tree.insert(node, "end", text="   " + self._overview_label(acc),
                            values=vals(p["value"], p["cost"], p["n"]),
                            tags=(tag(p["value"], p["cost"]),))
            tv += bv
            tc += bc
            nh += bn
            missing += sum(per[a]["missing"] for a in accs)
        if per:
            tree.insert("", "end", text="TOTAL", values=vals(tv, tc, nh), tags=("total",))

        ui["total"].config(text=f"{fnum(tv, 0)} kr")
        if not per:
            ui["sub"].config(text="No accounts ticked - tick the accounts you want "
                                  "in the total.", fg=C_FG_DIM)
        else:
            txt = (f"{len(per)} account(s), {nh} holdings   |   price +/- "
                   f"{fnum(tv - tc, 0)} kr")
            if missing:
                txt += (f"   |   {missing} holding(s) have no price yet and are "
                        f"NOT in the value - press Refresh prices")
            ui["sub"].config(text=txt, fg=C_WARN if missing else C_FG_DIM)

    # ---- add a company (instrument) without owning it ----
    def add_company(self):
        top = tk.Toplevel(self.root, bg=C_BG3)
        top.title("Add company")
        init_dialog(top, self.root)
        form = tk.Frame(top, bg=C_BG3)
        form.pack(padx=16, pady=14)
        tk.Label(form, text="Ticker (Yahoo)", bg=C_BG3, fg=C_FG, font=FONT,
                 width=14, anchor="w").grid(row=0, column=0, pady=4, sticky="w")
        e_t = mk_entry(form, width=18, bg=C_BG2, fg=C_FG, insertbackground=C_FG, relief="flat", font=FONT)
        e_t.grid(row=0, column=1)
        tk.Label(form, text="Company", bg=C_BG3, fg=C_FG, font=FONT,
                 width=14, anchor="w").grid(row=1, column=0, pady=4, sticky="w")
        e_c = mk_entry(form, width=28, bg=C_BG2, fg=C_FG, insertbackground=C_FG, relief="flat", font=FONT)
        e_c.grid(row=1, column=1)
        lbl = tk.Label(form, text="", bg=C_BG3, fg=C_ACCENT, font=FONT)
        lbl.grid(row=2, column=1, sticky="w", pady=(6, 0))

        def lookup():
            t = e_t.get().strip().upper()
            if not t:
                return
            lbl.config(text="Looking up...", fg=C_FG_DIM)
            top.update_idletasks()

            def work():
                try:
                    info = fetch_one(t)
                    def done():
                        if not e_c.get().strip():
                            e_c.insert(0, info["name"])
                        lbl.config(text=f"{info['name']} - {fnum(info['price'])} {info['currency']}", fg=C_ACCENT)
                    self.root.after(0, done)
                except Exception:
                    self.root.after(0, lambda: lbl.config(text="Not found on Yahoo.", fg=C_BAD))
            threading.Thread(target=work, daemon=True).start()

        def save():
            t = e_t.get().strip().upper()
            if not t:
                messagebox.showwarning(APP_NAME, "Ticker is required.")
                return
            self.pf.instruments.setdefault(t, {})["company"] = e_c.get().strip() or t
            self.pf.save()
            top.destroy()
            self.after_data_change()
            flash_ok(self.root, "Company added")
        self._btn(form, "Look up", lookup, BTN_REFRESH).grid(row=0, column=2, padx=6)
        bb = tk.Frame(top, bg=C_BG3)
        bb.pack(pady=(0, 14))
        self._btn(bb, "Save", save, BTN_DIALOG_OK).pack(side="left", padx=6)
        self._btn(bb, "Cancel", top.destroy, BTN_DIALOG_CANCEL).pack(side="left", padx=6)
        top.bind("<Return>", lambda e: save())
        e_t.focus_set()

    # ---- reusable price-history line chart ----
    def _price_chart(self, parent, ticker, w=580, h=190):
        cv = tk.Canvas(parent, width=w, height=h, bg=C_BG2, highlightthickness=0)
        items = sorted(self.price_history.get(ticker, {}).items())
        if len(items) < 2:
            cv.create_text(w // 2, h // 2, fill=C_FG_DIM, font=FONT,
                           text="No price history yet  -  History ▸ Update from 'Kurser' tab")
            return cv
        prices = [p for _, p in items]
        lo, hi = min(prices), max(prices)
        rng = (hi - lo) or 1
        padL, padR, padT, padB = 56, 12, 12, 22
        pw, ph, n = w - padL - padR, h - padT - padB, len(items)

        def X(i):
            return padL + pw * i / (n - 1)

        def Y(p):
            return padT + ph * (1 - (p - lo) / rng)

        for frac, val in ((0.0, hi), (0.5, (hi + lo) / 2), (1.0, lo)):
            yy = padT + ph * frac
            cv.create_line(padL, yy, w - padR, yy, fill=C_SEP)
            cv.create_text(padL - 6, yy, text=fnum(val), fill=C_FG_DIM,
                           anchor="e", font=("Segoe UI", 7))
        coords = []
        for i, (d, p) in enumerate(items):
            coords += [X(i), Y(p)]
        up = items[-1][1] >= items[0][1]
        cv.create_line(*coords, fill=C_GOOD if up else C_BAD, width=2)
        li, hii = prices.index(lo), prices.index(hi)
        cv.create_oval(X(li) - 3, Y(lo) - 3, X(li) + 3, Y(lo) + 3, fill=C_BAD, outline="")
        cv.create_oval(X(hii) - 3, Y(hi) - 3, X(hii) + 3, Y(hi) + 3, fill=C_GOOD, outline="")
        cv.create_text(padL, h - 8, text=items[0][0], fill=C_FG_DIM, anchor="w", font=("Segoe UI", 7))
        cv.create_text(w - padR, h - 8, text=items[-1][0], fill=C_FG_DIM, anchor="e", font=("Segoe UI", 7))
        return cv

    # ---- company information popup ----
    def _show_company(self, ticker, account=None):
        top = tk.Toplevel(self.root, bg=C_BG3)
        top.title(f"{ticker} - company information")
        init_dialog(top, self.root)
        top.geometry("640x760")

        name = self.pf.company_for(ticker, self.prices)
        isin = self.isin_of(ticker)
        yp = self.prices.get(ticker, {}).get("price")
        gp = self.sheet_prices.get(ticker, {}).get("price")

        hdr = tk.Frame(top, bg=C_BG3)
        hdr.pack(fill="x", padx=16, pady=(14, 6))
        tk.Label(hdr, text=name, bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 15, "bold")).pack(anchor="w")
        sub = f"{ticker}" + (f"   ·   ISIN {isin}" if isin else "")
        tk.Label(hdr, text=sub, bg=C_BG3, fg=C_FG_DIM, font=FONT).pack(anchor="w")
        prev = self.prices.get(ticker, {}).get("prev")
        pr = []
        if yp is not None:
            pr.append(f"Yahoo {fnum(yp)}")
            if prev:
                dkr = yp - prev
                pr.append(f"vs yesterday {dkr:+.2f} kr ({dkr / prev * 100:+.1f}%)")
        if gp is not None:
            pr.append(f"Sheet {fnum(gp)}")
        st = history_stats(self.price_history.get(ticker, {}))
        if st:
            pr.append(f"Low {fnum(st['low'])} ({st['low_date']})")
            pr.append(f"High {fnum(st['high'])} ({st['high_date']})")
        day_color = C_FG
        if yp is not None and prev:
            day_color = C_GOOD if yp >= prev else C_BAD
        tk.Label(hdr, text="   ·   ".join(pr) or "No price yet",
                 bg=C_BG3, fg=day_color, font=FONT).pack(anchor="w", pady=(4, 0))

        # price-history chart
        self._price_chart(top, ticker).pack(padx=16, pady=(6, 2))

        # holdings across accounts
        tk.Label(top, text="Holdings by account", bg=C_BG3, fg=C_ACCENT,
                 font=FONT_B).pack(anchor="w", padx=16, pady=(8, 0))
        hf = tk.Frame(top, bg=C_BG3)
        hf.pack(fill="x", padx=16)
        hcols = ("account", "owner", "qty", "gav", "value", "pl", "div", "net")
        htree = ttk.Treeview(hf, columns=hcols, show="headings", height=5, selectmode="none")
        for c, t, w in (("account", "Broker", 90), ("owner", "Owner", 70),
                        ("qty", "Shares", 60), ("gav", "Avg", 70), ("value", "Value", 80),
                        ("pl", "G/L", 80), ("div", "Div.", 70), ("net", "Net+/-", 80)):
            htree.heading(c, text=t)
            htree.column(c, width=w, anchor="w" if c in ("account", "owner") else "e")
        htree.pack(fill="x")
        div_recv = self.dividends_received()
        price = self.active_price(ticker)
        tot = {"v": 0.0, "pl": 0.0, "d": 0.0, "net": 0.0}
        for h in self.pf.holdings():
            if h["ticker"] != ticker:
                continue
            acc = h["account"]
            value = price * h["qty"] if price is not None else 0.0
            pl = value - h["cost"] if price is not None else 0.0
            dr = div_recv.get((ticker, acc), 0.0)
            net = pl + dr + h.get("realized", 0.0)
            htree.insert("", "end", values=(self.broker_display(acc), self.owner_of(acc),
                         fnum(h["qty"], 0), fnum(h["gav"]), fnum(value), fnum(pl),
                         fnum(dr) if dr else "0", fnum(net)))
            tot["v"] += value; tot["pl"] += pl; tot["d"] += dr; tot["net"] += net
        htree.insert("", "end", values=("TOTAL", "", "", "", fnum(tot["v"]),
                     fnum(tot["pl"]), fnum(tot["d"]) if tot["d"] else "0", fnum(tot["net"])))

        # transactions (buys & sells) with show-sold toggle + brokerage total
        lhdr = tk.Frame(top, bg=C_BG3)
        lhdr.pack(fill="x", padx=16, pady=(10, 0))
        tk.Label(lhdr, text="Transactions (buys & sells)", bg=C_BG3, fg=C_ACCENT,
                 font=FONT_B).pack(side="left")
        show_sold = tk.BooleanVar(value=True)
        tk.Checkbutton(lhdr, text="Show sold", variable=show_sold, bg=C_BG3, fg=C_FG,
                       selectcolor=C_BG2, activebackground=C_BG3, font=("Segoe UI", 8),
                       highlightthickness=0).pack(side="left", padx=10)
        court_lbl = tk.Label(lhdr, text="", bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8))
        court_lbl.pack(side="right")
        lf = tk.Frame(top, bg=C_BG3)
        lf.pack(fill="both", expand=True, padx=16)
        lcols = ("date", "type", "account", "qty", "price", "courtage")
        ltree = ttk.Treeview(lf, columns=lcols, show="headings", selectmode="none")
        for c, t, w in (("date", "Date", 90), ("type", "Type", 50),
                        ("account", "Account", 120), ("qty", "Shares", 70),
                        ("price", "Price", 75), ("courtage", "Brokerage", 75)):
            ltree.heading(c, text=t)
            ltree.column(c, width=w, anchor="w" if c in ("account", "type") else "e")
        lvs = ttk.Scrollbar(lf, orient="vertical", command=ltree.yview)
        ltree.configure(yscrollcommand=lvs.set)
        ltree.pack(side="left", fill="both", expand=True)
        lvs.pack(side="right", fill="y")
        bind_mousewheel(ltree)
        ltree.tag_configure("sell", foreground=C_BAD)
        ltree.tag_configure("buy", foreground=C_FG)
        txs_t = sorted([x for x in self.pf.transactions if x.get("ticker") == ticker],
                       key=lambda x: x.get("date", ""))
        court_total = sum(float(t.get("courtage") or 0) for t in txs_t)

        def reload_lots():
            ltree.delete(*ltree.get_children())
            for t in txs_t:
                kind = t.get("type", "BUY")
                if kind == "SELL" and not show_sold.get():
                    continue
                ltree.insert("", "end", values=(
                    t.get("date"), kind, self.account_label(t.get("account", "")),
                    fnum(t.get("shares"), 0), fnum(t.get("price")), fnum(t.get("courtage"))),
                    tags=("sell" if kind == "SELL" else "buy",))
        reload_lots()
        show_sold.trace_add("write", lambda *a: reload_lots())
        court_lbl.config(text=f"Total brokerage paid: {fnum(court_total)} kr")

        # dividends - received breakdown (date, shares, per share, amount)
        tk.Label(top, text="Dividends received", bg=C_BG3, fg=C_ACCENT,
                 font=FONT_B).pack(anchor="w", padx=16, pady=(10, 0))
        df = tk.Frame(top, bg=C_BG3)
        df.pack(fill="x", padx=16)
        dcols = ("date", "account", "per", "shares", "amount")
        dtree = ttk.Treeview(df, columns=dcols, show="headings", height=5, selectmode="none")
        for c, t, w in (("date", "Date", 95), ("account", "Account", 95),
                        ("per", "Per share", 75), ("shares", "Shares", 65),
                        ("amount", "Amount", 90)):
            dtree.heading(c, text=t)
            dtree.column(c, width=w, anchor="w" if c == "account" else "e")
        dvs = ttk.Scrollbar(df, orient="vertical", command=dtree.yview)
        dtree.configure(yscrollcommand=dvs.set)
        dtree.pack(side="left", fill="x", expand=True)
        dvs.pack(side="right", fill="y")
        recv = 0.0
        for d in sorted([x for x in self.pf.dividends if x["ticker"] == ticker
                         and x.get("amount")], key=lambda x: x.get("date", "")):
            amt = float(d.get("amount") or 0)
            ps = d.get("per_share")
            shares = d.get("shares")
            if shares is None:
                shares = (amt / ps) if (amt and ps) else None
            recv += amt
            dtree.insert("", "end", values=(
                d.get("date"), self.account_short(d.get("account", "")), fnum(ps),
                fnum(shares, 0) if shares is not None else "-", fnum(amt)))
        nd = self.pf.next_dividend(ticker)
        line = f"Total received: {fnum(recv)} kr"
        if nd:
            line += f"        Next scheduled: {nd['date']}  ({fnum(nd.get('per_share'))}/share)"
        tk.Label(top, text=line, bg=C_BG3, fg=C_FG, font=FONT).pack(anchor="w", padx=16, pady=(4, 4))

        # links + settings
        inst = self.pf.instruments.get(ticker, {})
        av_url = inst.get("avanza_url") or (
            "https://www.avanza.se/sok/?query=" + urllib.parse.quote(name))
        link_fr = tk.Frame(top, bg=C_BG3)
        link_fr.pack(pady=(4, 0))
        av_lbl = tk.Label(link_fr, text="🔗  Avanza page", fg=C_ACCENT, bg=C_BG3,
                          cursor="hand2", font=("Segoe UI", 9, "underline"))
        av_lbl.pack(side="left", padx=8)
        av_lbl.bind("<Button-1>", lambda e: open_url(av_url))
        ya_lbl = tk.Label(link_fr, text="🔗  Yahoo page", fg=C_ACCENT, bg=C_BG3,
                          cursor="hand2", font=("Segoe UI", 9, "underline"))
        ya_lbl.pack(side="left", padx=8)
        ya_lbl.bind("<Button-1>", lambda e: open_url(
            "https://finance.yahoo.com/quote/" + urllib.parse.quote(ticker)))
        self._btn(link_fr, "Buys, sells & dividends...",
                  lambda: (top.destroy(), self._show_trade_detail(ticker, account)),
                  BTN_REFRESH).pack(side="left", padx=8)
        self._btn(link_fr, "Company settings...",
                  lambda: (top.destroy(), self._company_settings(ticker)), BTN_REFRESH).pack(side="left", padx=8)

        self._btn(top, "Close", top.destroy, BTN_DIALOG_CANCEL).pack(pady=(8, 12))

    # ---- ledger popup: every purchase, sale and dividend of one company ----
    def _show_trade_detail(self, ticker, account=None):
        """One chronological list of ALL buys, sells and received dividends of
        a company, with the shares held after each event and the realised
        result of every sale, plus a summary of money in / money out.

        `account` pre-selects one account (e.g. the account of the sale that
        was double-clicked in 'Sold / realized'); the drop-down switches to
        another account or to all of them.
        """
        name = self.pf.company_for(ticker, self.prices)
        accs = sorted({t.get("account", "") for t in self.pf.transactions
                       if t.get("ticker") == ticker}, key=str.casefold)
        top = tk.Toplevel(self.root, bg=C_BG3)
        top.title(f"{name} - purchases, sales & dividends")
        init_dialog(top, self.root)
        top.geometry("900x640")

        tk.Label(top, text=name, bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 15, "bold")).pack(pady=(12, 0))
        tk.Label(top, text=ticker, bg=C_BG3, fg=C_FG_DIM, font=FONT).pack()

        ALL = "All accounts"
        labels = {ALL: None}
        for a in accs:
            labels[self._overview_label(a)] = a
        start = ALL
        if account is not None:
            for lab, a in labels.items():
                if a is not None and self._norm_account(a) == self._norm_account(account):
                    start = lab
        v_acc = tk.StringVar(value=start)
        bar = tk.Frame(top, bg=C_BG3)
        bar.pack(fill="x", padx=16, pady=(6, 2))
        tk.Label(bar, text="Account:", bg=C_BG3, fg=C_FG, font=FONT_B).pack(side="left")
        om = tk.OptionMenu(bar, v_acc, *labels.keys())
        om.configure(bg=C_BG2, fg=C_FG, activebackground=C_SEP, highlightthickness=0,
                     relief="flat", font=FONT)
        om["menu"].configure(bg=C_BG2, fg=C_FG)
        om.pack(side="left", padx=6)

        wrap = tk.Frame(top, bg=C_BG3)
        wrap.pack(fill="both", expand=True, padx=16, pady=4)
        cols = ("date", "event", "account", "qty", "price", "courtage",
                "amount", "held", "result")
        heads = {"date": "Date", "event": "Event", "account": "Account",
                 "qty": "Shares", "price": "Price / share", "courtage": "Brokerage",
                 "amount": "Money", "held": "Held after", "result": "Result"}
        widths = {"date": 88, "event": 70, "account": 120, "qty": 65, "price": 85,
                  "courtage": 75, "amount": 95, "held": 75, "result": 95}
        tree = ttk.Treeview(wrap, columns=cols, show="headings", selectmode="browse")
        for c in cols:
            tree.heading(c, text=heads[c])
            tree.column(c, width=widths[c],
                        anchor="w" if c in ("event", "account") else "e")
        vs = ttk.Scrollbar(wrap, orient="vertical", command=tree.yview)
        tree.configure(yscrollcommand=vs.set)
        tree.pack(side="left", fill="both", expand=True)
        vs.pack(side="right", fill="y")
        bind_mousewheel(tree)
        tree.tag_configure("buy", foreground=C_FG)
        tree.tag_configure("sell", foreground=C_WARN)
        tree.tag_configure("div", foreground=C_GOOD)

        summ = tk.Label(top, text="", bg=C_BG3, fg=C_FG, font=FONT,
                        justify="left", anchor="w")
        summ.pack(fill="x", padx=16, pady=(4, 0))
        res_lbl = tk.Label(top, text="", bg=C_BG3, fg=C_ACCENT, font=("Segoe UI", 12, "bold"),
                           anchor="w")
        res_lbl.pack(fill="x", padx=16, pady=(2, 4))

        def build():
            acc = labels.get(v_acc.get())
            key = self._norm_account(acc) if acc is not None else None

            def sel(a):
                return key is None or self._norm_account(a) == key
            tree.delete(*tree.get_children())
            # realised result of each sale, matched back to its row
            real = {}
            for s in self.pf.realized_sales():
                if s["ticker"] == ticker and sel(s["account"]):
                    real.setdefault((self._norm_account(s["account"]), s["date"],
                                     round(s["qty"], 3), round(s["price"], 4)),
                                    []).append(s["realized"])
            events = []
            for t in self.pf.transactions:
                if t.get("ticker") == ticker and sel(t.get("account", "")):
                    events.append((t.get("date", ""),
                                   0 if t.get("type", "BUY") == "BUY" else 2, t, None))
            for d in self.pf.dividends:
                if d.get("ticker") == ticker and d.get("amount") and sel(d.get("account", "")):
                    events.append((d.get("date", ""), 1, None, d))
            events.sort(key=lambda e: (e[0], e[1]))
            held = bought = sold = divs = 0.0
            n_buy = n_sell = n_div = 0
            for date, _o, t, d in events:
                if t is not None:
                    sh = float(t.get("shares") or 0)
                    pr = float(t.get("price") or 0)
                    cg = float(t.get("courtage") or 0)
                    a_txt = self.account_short(t.get("account", ""))
                    if t.get("type", "BUY") == "BUY":
                        money = -(sh * pr + cg)
                        held += sh
                        bought += -money
                        n_buy += 1
                        tree.insert("", "end", tags=("buy",), values=(
                            date, "Buy", a_txt, fnum(sh, 0), fnum(pr), fnum(cg),
                            fnum(money), fnum(held, 0), ""))
                    else:
                        money = sh * pr - cg
                        held -= sh
                        sold += money
                        n_sell += 1
                        lst = real.get((self._norm_account(t.get("account", "")),
                                        date, round(sh, 3), round(pr, 4)), [])
                        r = lst.pop(0) if lst else None
                        tree.insert("", "end", tags=("sell",), values=(
                            date, "Sell", a_txt, fnum(sh, 0), fnum(pr), fnum(cg),
                            fnum(money), fnum(held, 0), fnum(r) if r is not None else ""))
                else:
                    amt = float(d.get("amount") or 0)
                    ps = d.get("per_share")
                    shares = d.get("shares")
                    if shares is None and amt and ps:
                        shares = amt / ps
                    divs += amt
                    n_div += 1
                    tree.insert("", "end", tags=("div",), values=(
                        date, "Dividend", self.account_short(d.get("account", "")),
                        fnum(shares, 0) if shares is not None else "-",
                        fnum(ps) if ps is not None else "-", "", fnum(amt),
                        fnum(held, 0), ""))
            realized = sum(s["realized"] for s in self.pf.realized_sales()
                           if s["ticker"] == ticker and sel(s["account"]))
            value = cost = 0.0
            qty = 0.0
            priced = True
            price = self.active_price(ticker)
            for h in self.pf.holdings():
                if h["ticker"] == ticker and sel(h["account"]):
                    qty += h["qty"]
                    cost += h["cost"]
            if qty and price is None:
                priced = False
            if qty and price is not None:
                value = price * qty
            unreal = (value - cost) if (qty and priced) else 0.0
            lines = [f"Bought: {n_buy} x, {fnum(bought)} kr (brokerage included)      "
                     f"Sold: {n_sell} x, {fnum(sold)} kr (after brokerage)      "
                     f"Dividends: {n_div} x, {fnum(divs)} kr",
                     f"Realised on sales: {fnum(realized)} kr"]
            if qty:
                lines.append(f"Still held: {fnum(qty, 0)} shares"
                             + (f", worth {fnum(value)} kr now, unrealised {fnum(unreal)} kr"
                                if priced else " (no price yet)"))
            summ.config(text="\n".join(lines))
            total = realized + divs + unreal
            res_lbl.config(text=f"Result so far (sales + dividends"
                                f"{' + unrealised' if qty else ''}): {fnum(total)} kr",
                           fg=C_GOOD if total >= 0 else C_BAD)

        v_acc.trace_add("write", lambda *a: build())
        build()

        bb = tk.Frame(top, bg=C_BG3)
        bb.pack(pady=(4, 12))
        self._btn(bb, "Company info...",
                  lambda: (top.destroy(), self._show_company(ticker, account=account)),
                  BTN_REFRESH).pack(side="left", padx=6)
        self._btn(bb, "Close", top.destroy, BTN_DIALOG_CANCEL).pack(side="left", padx=6)

    # ---- per-company settings: dividend frequency, Avanza link ----
    def _company_settings(self, ticker):
        inst = self.pf.instruments.setdefault(ticker, {})
        top = tk.Toplevel(self.root, bg=C_BG3)
        top.title(f"Company settings - {ticker}")
        init_dialog(top, self.root)
        form = tk.Frame(top, bg=C_BG3)
        form.pack(padx=16, pady=14)

        def fld(r, label):
            tk.Label(form, text=label, bg=C_BG3, fg=C_FG, font=FONT, width=18,
                     anchor="w").grid(row=r, column=0, sticky="w", pady=4)

        fld(0, "Company name")
        e_name = mk_entry(form, width=30, bg=C_BG2, fg=C_FG, insertbackground=C_FG, relief="flat", font=FONT)
        e_name.insert(0, inst.get("company", ""))
        e_name.grid(row=0, column=1, sticky="w")

        fld(1, "Dividend frequency")
        v_freq = tk.StringVar(value=inst.get("freq", "None"))
        ff = tk.Frame(form, bg=C_BG3)
        ff.grid(row=1, column=1, sticky="w")
        for val in ("None", "Monthly", "Quarterly", "Semi-annual", "Yearly"):
            tk.Radiobutton(ff, text=val, variable=v_freq, value=val, bg=C_BG3,
                           fg=C_FG, selectcolor=C_BG2, activebackground=C_BG3,
                           font=("Segoe UI", 8), highlightthickness=0).pack(side="left")

        fld(2, "Avanza URL")
        e_av = mk_entry(form, width=40, bg=C_BG2, fg=C_FG, insertbackground=C_FG, relief="flat", font=FONT)
        e_av.insert(0, inst.get("avanza_url", ""))
        e_av.grid(row=2, column=1, sticky="w")
        tk.Label(form, text="e.g. https://www.avanza.se/aktier/om-aktien.html/5264/handelsbanken-a",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 7)).grid(row=3, column=1, sticky="w")

        def save():
            inst["company"] = e_name.get().strip() or ticker
            inst["freq"] = v_freq.get()
            inst["avanza_url"] = e_av.get().strip()
            self.pf.save()
            top.destroy()
            self.after_data_change()
            flash_ok(self.root, "Saved")
        bb = tk.Frame(top, bg=C_BG3)
        bb.pack(pady=(0, 14))
        self._btn(bb, "Save", save, BTN_DIALOG_OK).pack(side="left", padx=6)
        self._btn(bb, "Cancel", top.destroy, BTN_DIALOG_CANCEL).pack(side="left", padx=6)
        top.bind("<Return>", lambda e: save())


# ============================================================================
#  DEL 18 .... HELP DIALOG  (ESC to close)
# ============================================================================
    def show_help(self):
        top = tk.Toplevel(self.root, bg=C_BG3)
        top.title("Help - StockFolio")
        init_dialog(top, self.root)
        top.geometry("720x600")

        head = tk.Frame(top, bg=C_BG3)
        head.pack(fill="x")
        tk.Label(head, text="StockFolio - Help", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 16, "bold")).pack(pady=(14, 2))
        tk.Label(head, text="Press ESC to close", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 8, "italic")).pack()

        wrap = tk.Frame(top, bg=C_BG3)
        wrap.pack(fill="both", expand=True, padx=12, pady=10)
        txt = mk_text(wrap, wrap="word", bg=C_BG2, fg=C_FG, font=FONT,
                      relief="flat", padx=12, pady=12)
        vs = ttk.Scrollbar(wrap, orient="vertical", command=txt.yview)
        txt.configure(yscrollcommand=vs.set)
        txt.pack(side="left", fill="both", expand=True)
        vs.pack(side="right", fill="y")
        bind_mousewheel(txt)

        HELP = """WHAT STOCKFOLIO DOES
StockFolio tracks a stock portfolio and fetches live prices from the \
Stockholm exchange (and others) directly from Yahoo Finance - free, with \
no account or API key. Prices are typically delayed about 15 minutes, which \
is plenty for a long-term portfolio.

TICKERS
Use the Yahoo ticker. For Stockholm-listed shares this is the symbol plus \
".ST". Examples:
   Swedbank A      ->  SWED-A.ST
   Volvo B         ->  VOLV-B.ST
   FastPartner D   ->  FPAR-D.ST
   ALM Equity pref ->  ALM-PREF.ST
In the Add-transaction dialog, click "Look up ticker" to verify the symbol \
and auto-fill the company name and current price.

ADDING TRANSACTIONS
Everything is entered manually so you stay in control:
   +Add transaction  ->  ticker, company, account, BUY/SELL, date, shares, \
price/share, brokerage, note.
Buy and sell are both supported. The program aggregates each ticker+account \
into a holding using the average-cost method (your GAV), so selling part of \
a position is handled correctly.
   Edit / Delete     ->  select a holding, then pick the individual \
transaction to change or remove. Double-click a holding to edit.

THE PORTFOLIO TABLE
Shows shares, average cost, last price, market value, and TWO profit columns: \
"Price +/-" is the pure price gain/loss (value minus what you paid, brokerage \
included), while "Net +/- (inc. div)" ALSO adds the dividends you have \
received and any realised gains - so Net is your true result on the holding. \
There is also a "Day %" column (change vs yesterday) and the next dividend \
date/amount. The bottom TOTAL row sums the whole portfolio. Click any column \
header to sort; click again to reverse. Green = gain, red = loss. An amber \
row means a dividend is near. Double-click a company name for full details.

DIVIDENDS
Open "Dividends" to record dividend events (a date + amount per share). \
You can add them one by one, or use "Generate series..." to create a whole \
schedule (e.g. quarterly x 4) in one click - handy for 2026, 2027 planning.
The "Dividend calendar" tab lists every event sorted by date, and a running \
total of upcoming income. A payout you have ALREADY received shows the \
account that got it, together with the exact share count and amount from the \
statement - so when several accounts own the same stock you get one line per \
account, not one merged line. A future, not-yet-paid event has no account and \
is estimated from the shares you currently hold. Events within the warning \
window are highlighted, and a warning banner appears at the bottom of the \
main window when a dividend is approaching (default 14 days).

SOLD / REALIZED
The "Sold / realized" tab lists every sell you have made with its realised \
profit or loss, worked out with the average-cost method (brokerage \
included): sell price minus your average cost at the time, times the number \
of shares. Owner and account are shown, and the bottom row totals your \
realised result. Double-click a row to open that company. This is your \
"closed trades" history.

WHAT-IF CALCULATOR
Pick a holding and type a price change in kronor OR in percent - the other \
field fills in automatically (so you instantly see "1 kr = X %"). It shows \
the new price, the new position value, the change in kronor, your new total \
gain/loss, and what that move means for the whole portfolio in kronor and \
percent. Great for "what happens if this stock moves a bit".

REFRESH PRICES (YAHOO)
Click "Refresh (Yahoo)" any time. It also runs automatically at startup. \
Fetching happens in the background so the window never freezes. The last \
prices are remembered, so the table is populated even before a refresh. The \
"Day %" column shows each share's change versus yesterday's close. A price \
chart of the stored history is shown when you open a company (double-click a \
company name) or open a stock in History.

GOOGLE SHEET  (second price source + one-time import)
Click "Google Sheet" to connect an existing Google Sheet (or a new one). \
The sheet must be shared as "Anyone with the link can view". Paste the sheet \
URL (or just its ID) and the tab's gid, then map your column names. Two uses:
   * IMPORT HOLDINGS - reads every row once and creates the matching buy \
transactions (company, ticker, account, shares, date, price, brokerage), so \
you do not have to type your portfolio in by hand. You get a preview first, \
and can choose to replace or add to what you already have.
     WARNING, and how the preview protects you: the sheet is a SUMMARY of \
the same trades your broker CSV already delivered, but it names the accounts \
its own way ("N-Lars") while the CSV uses the broker's ("64352081"). Nothing \
looks equal, so importing everything doubles your holdings. The preview \
therefore marks every row and ticks ONLY the safe ones:
        NEW     - the ticker is not in the portfolio at all (ticked)
        DUP     - same ticker, date, share count and price already stored, \
just under another account name (not ticked)
        LIKELY  - same date and share count but another price, or the same \
share count and price on another date; the sheet keeps an average price, so \
this is still the same trade (not ticked)
        OWNED   - nothing matches, but you already hold this ticker, so the \
row would add shares on top of a real position (not ticked)
     Only rows that say IMPORT are imported. CLICK A ROW to switch it \
between IMPORT and skip, or use the "Only new" / "Nothing" / "Everything" buttons. If \
you set a DUP or LIKELY row to IMPORT you are asked to confirm once more.
   * LIVE PRICES FROM THE SHEET - reads the sheet's current value column and \
divides by the share count to get a per-share price. This gives you a SECOND \
price next to Yahoo: Yahoo is the steady automatic value, the sheet is the \
one you can update more often. Both appear as their own columns ("Yahoo" and \
"Sheet"); a dot marks which one currently drives Value and Gain/Loss, and you \
choose that with the radio buttons. The Stockholm code STO:XXX is converted \
to the Yahoo ticker XXX.ST automatically.

FIND DUPLICATES  (Tools menu)
If a position shows twice as many shares as you really own, one import has \
landed on top of another. "Find duplicates" scans the whole portfolio for \
the same trade stored twice. It deliberately IGNORES the account name, \
because that is exactly what differs between a sheet copy and a broker copy. \
Three kinds of group are shown:
   * identical rows - same ticker, type, date, share count and price
   * prices differ - same ticker, type, date and share count, but another \
price (the sheet stores an average)
   * no account - a row that carries no account at all
The copy that came from the broker (it has an ISIN, a brokerage fee and is \
marked Verified) is kept, and the extra copies are set to DELETE. CLICK A \
ROW to switch it between keep and DELETE. Only the identical groups are set \
to DELETE for you: "prices differ" needs the "Also delete 'prices differ'" \
button, because two people CAN buy the same number of shares on the same day \
at slightly different prices, and a row with no account is left alone \
entirely - it may be a real holding that simply lost its account, in which \
case give it one with Edit on the Portfolio tab instead of deleting it. \
Deleting writes a timestamped backup first, so File > Restore from backup \
always gets you back.

IMPORT CSV  (broker statements: Nordnet / Avanza)
Click "Import CSV" to read transaction statements exported from Nordnet or \
Avanza. Statements are picked up automatically from three places: your \
Downloads folder (so just download them from the broker), the program folder \
and StockFolio's own Helpfiles folder. Only .csv files that really look like \
a Nordnet or Avanza statement are listed, so other CSV files in Downloads are \
ignored. A line under the file list says which folders were searched and how \
many statements each held, so an empty list is explained. "Look again" \
rescans while the window is open; "Add files..." opens your Downloads folder \
to pick a file; "From imported..." opens the archive of statements that were \
already read, to read one again (safe - everything already on file is \
skipped). The statements contain date, account, \
shares, price AND brokerage, so importing fills your portfolio with verified \
data - far less typing than by hand.
   * Account mapping - each statement account id (e.g. a depot number or \
"Lars ISK") is mapped to one of your own account names; the mapping is \
remembered.
   * Tickers - the security's ISIN is resolved to a Yahoo ticker \
automatically (Stockholm .ST preferred). Use "Edit tickers..." to fix any \
foreign dual-listing (e.g. AZN.L to AZN.ST); your choice is cached.
   * You do NOT have to keep the CSV files. A statement is input only - the \
date, account, share count, price, brokerage, ISIN and the broker's own \
reference are all written into the portfolio file, and the CSV is never read \
again. The folder scan only exists to spot NEW exports. So the import ends by \
MOVING the files it used into Helpfiles\\StockFolio\\imported\\ (dated, never \
deleted) and appending a line to import_log.txt there, which keeps the \
program folder clean and gives you a record of what was read and when. Untick \
"Move the files..." if you would rather leave them where they are, and use \
"Open imported folder" to see what has been filed.
   * Duplicates are detected and skipped, so you can re-import an updated \
statement safely. A row counts as a duplicate only when the ACCOUNT, date, \
security, share count and price/amount per share all match - so two accounts \
that own the same stock keep their own separate rows even though they are \
paid on the same day for the same amount per share. The preview marks every \
row "NEW" or "dup" before you import anything, dividends included, and the \
summary line counts both. Buys, sells and dividends can each be toggled. \
Rows with no brokerage are highlighted so you can check them. Imported rows \
are marked Verified.
   * If dividends look like they are missing for one of your accounts, just \
re-run this import on the same statements: everything already on file is \
skipped and only the genuinely missing payouts are added.
   * Brokerage that arrives later: a trade that is already stored but has NO \
brokerage is still a duplicate - it is not added twice - but if the newer \
statement carries the brokerage, it is filled in on the existing row (the \
preview marks such rows "fill"). A row that already has a brokerage is never \
changed.

BY ACCOUNT  (tab next to "By person")
One block per broker account - Lars' Avanza, Lars' Nordnet, the O accounts, \
Benjamin's and so on, your own accounts first - so you can hold it next to \
the holdings list at the broker and see at a glance whether something was \
missed. Each block shows the shares, average cost, value and result per \
company, the date of the last trade (how fresh the data is) and a "Check" \
column: trades without brokerage, trades that did not come from a statement \
(typed in or from the sheet) and pasted orders still waiting for their \
statement. If the shares do not match the broker, double-click the company \
to see every purchase, sale and dividend that make up the number. "Owner" at \
the top limits the view to one person.
   * Two views: "Per account" (as above) and "Per broker (all owners)" - one \
block per broker (Avanza, Nordnet), everything held there in one list sorted \
per company, with the owner in brackets, e.g. "Handelsbanken A (Lars OA)". \
Tick "Owners as headings" (off by default) to get an owner heading with that \
person's companies underneath instead.
   * SECTIONS: Lars's and Benjamin's shares can sit in Olga's broker accounts. \
In Manage accounts give those accounts the Section "Olga Avanza" / "Olga \
Nordnet": Per account then shows one heading per section, with each owner's \
account kept apart underneath. "+ New account" prepares a new account (for \
example Benjamin's own Avanza) before its first statement; it then also shows \
in the import window's account list.

CHECK AGAINST BROKER  (button in the By account tab)
When something looks wrong, type in what the broker's own holdings list says. \
Pick the account, then either paste the rows copied from the broker (Nordnet: \
company, SEK, shares, average cost GAV ...) and click "Read text above" - \
several companies at once are fine - or choose a company and type "I have N" \
and the average cost. For each company the program tells you:
   * shares and average cost match - fine;
   * the broker has FEWER shares: that many shares were SOLD without being \
recorded. The sale price cannot be worked out, so you are told to look it up \
at the broker (price and date) and then use "Add missing sale...";
   * the broker has MORE shares: that many were BOUGHT without being \
recorded. Their average price is worked out from the broker's total cost (an \
average if they were bought in several periods), and "Add missing purchase..." \
adds them with that price and a date you set;
   * same shares but another average cost: brokerage missing on a purchase, a \
typed-in price or an old difference - the amount is shown.
Tick "This is the COMPLETE list" if you pasted everything the account holds: a \
company you have but the broker does not then counts as 0 at the broker. \
"Save this check" remembers the broker's numbers; the By account tab then marks \
every company with a green tick when it still matches, or a warning (broker \
had N on that date) when it does not. Added trades are marked "pasted \
(reconcile)" and are replaced by the real rows if a statement later covers the \
same trade.

PASTE ORDERS  ("Paste orders..." in the Import CSV window)
A broker statement often lags: a sale made today may not be in the export \
until tomorrow, but it is already in Nordnet's order view. Copy the finished \
orders from there (Säljorder / Köporder ... Avslutad), click "Paste orders...", \
paste them, check the trade date (the text has none - it defaults to today) \
and click "Add to import". The account number, company, shares and average \
price are read from the text; the company is matched against the ones you \
already have (a sale must be something held on that account). The rows are \
marked "paste" in the preview and stored with no brokerage, as "pasted" rows. \
Only finished ("Avslutad") orders in SEK are used; anything left out is \
listed with the reason.
   * When the real statement arrives, the pasted rows are REPLACED by the \
statement's rows (same account, buy/sell and company within 3 days, and the \
shares add up to the same total) - so nothing is counted twice, the real \
prices and brokerage come in, and the preview tells you how many are replaced.
   * If the statement was already imported, a pasted order for the same trade \
is skipped. Pasting the same text twice is also harmless.

BUYS, SELLS & DIVIDENDS  (popup)
Double-click a sale in the "Sold / realized" tab, or right-click a holding on \
the Portfolio tab, to see everything that happened in that company in one \
list: every purchase, every sale and every received dividend in date order, \
with the shares held after each event and the realised result of each sale. \
Below the list: total bought (brokerage included), total sold, dividends, \
realised result, what is still held (value and unrealised result) and the \
result so far. The Account drop-down switches between one account and all \
accounts. The company info window has a button for the same popup.

QUICK OVERVIEW  ("Overview" button, after Import CSV)
Shows the total value of just the accounts you choose, for a quick answer to \
"how much do I have at Avanza and Nordnet?". Tick the accounts you want in \
the list at the top; the choice is remembered. The result is grouped broker \
by broker, account by account, with value, invested amount, price +/- and a \
grand total. The first time, your own accounts are ticked except the ones \
with code ON and OA - change that any time. The window can stay open: it \
updates after "Refresh prices", an import or an edit. Value = shares x \
current price; cash balances are not tracked.

PRICE HISTORY  ("History" button, from the 'Kurser' tab)
Click "History" then "Update from 'Kurser' tab" to pull the daily closing \
prices you keep in the sheet's Kurser tab. The program reads it by the code \
row (so columns may move and temp columns are fine) and stores every \
date/price in its own file. Dates are KEPT PERMANENTLY here even after you \
delete them from the sheet, so the history only ever grows. The table shows, \
per company, how many days are stored, the first/last date, and the LOWEST \
and HIGHEST price with the date each occurred - so you can keep those peak \
dates permanently in your sheet if you wish. Double-click a row (or "Show all \
dates") to see every stored date, with the low in red and the high in green.

PORTFOLIO FILES  (File menu)
The program always reopens the portfolio you used last. Use File ▸ New \
portfolio to start a fresh one in its own file, File ▸ Open to switch to \
another, and File ▸ Save As to copy the current one to a new file. The \
current file name is shown in the window title. Each file holds its own \
transactions, dividends and instruments.
   Your data is protected: every save first copies the previous version into \
a "backups" folder (timestamped, the last 60 kept) and then writes safely, so \
nothing can be half-written. If the file is ever damaged it is restored from \
the newest backup automatically. Use File ▸ Restore from backup to go back to \
an earlier version yourself, or File ▸ Open backups folder to see them.

ACCOUNTS, OWNER & BROKER
Tools ▸ Manage accounts (also on the "By person" tab) lets you rename an \
account, and set its owner (person, e.g. Björn) and broker (e.g. Nordnet). \
The main table shows an Owner column next to the Account column, and the "By \
person" tab groups everything by person and broker.

DATA & SETTINGS
Everything is stored under the program folder in \
Helpfiles/StockFolio (portfolio.json and settings.json). The window size, \
sort order and last prices are remembered between sessions. Logs go to \
Helpfiles/0---Empty. Because all paths are relative to the program, it keeps \
working if you turn it into an EXE and move it elsewhere.
"""
        txt.insert("1.0", HELP)
        txt.config(state="disabled")
        self._btn(top, "Close", top.destroy, BTN_DIALOG_CANCEL).pack(pady=(0, 12))


# ============================================================================
#  DEL 19 .... ABOUT DIALOG  (ESC to close)
# ============================================================================
    def show_about(self):
        top = tk.Toplevel(self.root)
        top.title("About StockFolio")
        top.configure(bg=C_BG3)
        top.resizable(False, False)
        init_dialog(top, self.root)

        hdr = tk.Frame(top, bg=C_BG3)
        hdr.pack(fill="x")
        tk.Label(hdr, text="\U0001F4C8", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 36)).pack(pady=(18, 0))
        tk.Label(hdr, text="StockFolio", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 20, "bold")).pack()
        tk.Label(hdr, text="Your personal Stockholm-exchange portfolio tracker",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 9, "italic")).pack(pady=(2, 10))

        tk.Frame(top, bg=C_SEP, height=1).pack(fill="x", padx=20)
        tk.Label(top, text='Created by  Lars "Issu" Olsson',
                 bg=C_BG3, fg=C_FG, font=("Segoe UI", 10, "bold")).pack(pady=(14, 0))
        tk.Label(top, text=f"Version {APP_VERSION}", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 8)).pack()

        DOC_URL = ("https://docs.google.com/document/d/"
                   "1B6y3CP-DafUKoXF9Apg4BpEl2m1j0kghRgD7lweF41s/edit?usp=sharing")
        doc_lbl = tk.Label(top, text="\U0001F4C4  View documentation",
                           bg=C_BG3, fg=C_ACCENT, font=("Segoe UI", 9, "underline"),
                           cursor="hand2")
        doc_lbl.pack(pady=(8, 2))
        doc_lbl.bind("<Button-1>", lambda e: open_url(DOC_URL))
        doc_lbl.bind("<Enter>", lambda e: doc_lbl.configure(fg="#b4d4ff"))
        doc_lbl.bind("<Leave>", lambda e: doc_lbl.configure(fg=C_ACCENT))

        tk.Frame(top, bg=C_SEP, height=1).pack(fill="x", padx=20, pady=(14, 0))
        tk.Label(top, text="☕  If you enjoy StockFolio, a small gift is always welcome!",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                 wraplength=300, justify="center").pack(pady=(10, 6))

        donate = tk.Frame(top, bg=C_PANEL, padx=16, pady=10)
        donate.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"
        for name, url in (("Revolut", REVOLUT_URL), ("PayPal", PAYPAL_URL),
                          ("Wise", WISE_URL)):
            lbl = tk.Label(donate, text=f"→  {name}", bg=C_PANEL, fg=C_ACCENT,
                           font=("Segoe UI", 9, "underline"), cursor="hand2")
            lbl.pack(anchor="w", pady=1)
            lbl.bind("<Button-1>", lambda e, u=url: open_url(u))

        tk.Label(top, text="Press ESC to close", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 8, "italic")).pack(pady=(8, 4))
        self._btn(top, "Close", top.destroy, BTN_DIALOG_CANCEL).pack(pady=(0, 14))


# ============================================================================
#  DEL 19B ... PORTFOLIO FILES  (New / Open / Save / Save As - remembers last)
# ============================================================================
    def _set_portfolio_path(self, path):
        self.pf.path = path
        self.S["last_portfolio"] = path
        save_settings(self.S)
        self._update_title()

    def portfolio_save(self):
        self.pf.save()
        flash_ok(self.root, "Saved")

    def portfolio_save_as(self):
        path = filedialog.asksaveasfilename(
            parent=self.root, title="Save portfolio as",
            initialdir=HELP_DIR, defaultextension=".json",
            filetypes=[("StockFolio portfolio", "*.json"), ("All files", "*.*")])
        if not path:
            return
        self._set_portfolio_path(path)
        self.pf.save()
        flash_ok(self.root, "Saved as " + os.path.basename(path))

    def portfolio_open(self):
        path = filedialog.askopenfilename(
            parent=self.root, title="Open portfolio",
            initialdir=HELP_DIR,
            filetypes=[("StockFolio portfolio", "*.json"), ("All files", "*.*")])
        if not path:
            return
        # save current first
        self.pf.save()
        self.pf = Portfolio(path)
        self.S["last_portfolio"] = path
        save_settings(self.S)
        self._update_title()
        self.after_data_change()
        flash_ok(self.root, "Opened " + os.path.basename(path))

    def _open_imported_folder(self):
        """The statements that have already been read, plus import_log.txt."""
        d = os.path.join(HELP_DIR, "imported")
        try:
            os.makedirs(d, exist_ok=True)
            open_path(d)                  # whatever DefaultHub says opens a folder
        except Exception as e:
            messagebox.showinfo(APP_NAME, f"Imported statements are in:\n{d}\n\n({e})")

    def _open_backups_folder(self):
        bdir = _backup_dir(self.pf.path)
        try:
            os.makedirs(bdir, exist_ok=True)
            open_path(bdir)               # whatever DefaultHub says opens a folder
        except Exception as e:
            messagebox.showinfo(APP_NAME, f"Backups are in:\n{bdir}\n\n({e})")

    def portfolio_restore_backup(self):
        backups = list_backups(self.pf.path)
        if not backups:
            messagebox.showinfo(APP_NAME, "No backups found yet. A backup is "
                                "made automatically every time the portfolio is saved.")
            return
        top = tk.Toplevel(self.root, bg=C_BG3)
        top.title("Restore from backup")
        init_dialog(top, self.root)
        top.geometry("520x460")
        tk.Label(top, text="Pick a backup to restore", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 13, "bold")).pack(pady=(12, 2))
        tk.Label(top, text="The current portfolio is itself backed up first, "
                 "so nothing is lost.", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 8, "italic")).pack()
        lb = tk.Listbox(top, width=64, height=16, bg=C_BG2, fg=C_FG,
                        font=FONT_MONO, selectbackground=C_SEP,
                        highlightthickness=0, bd=0, activestyle="none")
        lb.pack(padx=14, pady=8, fill="both", expand=True)
        meta = []
        for b in backups:
            cnt = "?"
            try:
                with open(b, "r", encoding="utf-8") as f:
                    d = json.load(f)
                cnt = f"{len(d.get('transactions', []))} tx, {len(d.get('dividends', []))} div"
            except Exception:
                pass
            parts = os.path.basename(b)[:-5].split("_")
            if len(parts) >= 3:
                dp, tp = parts[-3], parts[-2]
                ts = f"{dp[:4]}-{dp[4:6]}-{dp[6:8]} {tp[:2]}:{tp[2:4]}:{tp[4:6]}"
            else:
                ts = os.path.basename(b)
            lb.insert("end", f"{ts}   ({cnt})")
            meta.append(b)
        if meta:
            lb.selection_set(0)

        def restore():
            sel = lb.curselection()
            if not sel:
                return
            path = meta[sel[0]]
            try:
                with open(path, "r", encoding="utf-8") as f:
                    d = json.load(f)
            except Exception as e:
                messagebox.showerror(APP_NAME, f"Could not read backup:\n{e}", parent=top)
                return
            self.pf.save()                   # back up current state first
            self.pf._apply(d)
            self.pf.save()
            top.destroy()
            self.after_data_change()
            flash_ok(self.root, "Restored")
        bb = tk.Frame(top, bg=C_BG3)
        bb.pack(pady=10)
        self._btn(bb, "Restore selected", restore, BTN_DIALOG_OK).pack(side="left", padx=6)
        self._btn(bb, "Cancel", top.destroy, BTN_DIALOG_CANCEL).pack(side="left", padx=6)
        lb.bind("<Double-1>", lambda e: restore())

    def portfolio_new(self):
        if self.pf.transactions and not messagebox.askyesno(
                APP_NAME, "Start a NEW empty portfolio?\n\nYour current portfolio "
                "stays saved in its own file - this just creates a fresh one."):
            return
        path = filedialog.asksaveasfilename(
            parent=self.root, title="New portfolio - choose a file name",
            initialdir=HELP_DIR, defaultextension=".json",
            filetypes=[("StockFolio portfolio", "*.json"), ("All files", "*.*")])
        if not path:
            return
        self.pf.save()                       # keep the old one intact
        self.pf = Portfolio(path)            # loads empty (new file)
        self.pf.transactions, self.pf.dividends = [], []
        self.pf.instruments, self.pf.isin_map = {}, {}
        self.pf.broker_checks = {}
        self.pf.save()
        self.S["last_portfolio"] = path
        save_settings(self.S)
        self._update_title()
        self.after_data_change()
        flash_ok(self.root, "New portfolio")


# ============================================================================
#  DEL 20 .... CLOSE / PERSIST
# ============================================================================
    def on_close(self):
        try:
            self.pf.save()                       # autosave portfolio on exit
            self.S["geometry"] = self.root.geometry()
            self.S["prices"] = self.prices
            self.S["sheet_prices"] = self.sheet_prices
            self.S["gsheet"] = self.gsheet
            self.S["price_source"] = self.price_source
            self.S["accounts"] = self.accounts
            self.S["account_map"] = self.account_map
            self.S["account_meta"] = self.account_meta
            self.S["last_portfolio"] = self.pf.path
            save_settings(self.S)
        except Exception as e:
            log(f"on_close save failed: {e}")
        self.root.destroy()


# ============================================================================
#  DEL 21 .... MAIN
# ============================================================================
def main():
    log(f"--- {APP_NAME} {APP_VERSION} starting ---")
    root = tk.Tk()
    root.title(APP_NAME)

    # crash catcher for tkinter callbacks too
    def _tk_report(exc, val, tb):
        _crash(exc, val, tb)
    root.report_callback_exception = _tk_report

    app = App(root)
    root.after(0, lambda: set_window_icon(root))
    root.mainloop()


if __name__ == "__main__":
    main()
