import AppKit
import CommanderCore
import UniformTypeIdentifiers

enum Side { case left, right }

/// Una scheda: cartella, cronologia, ordinamento, posizione del cursore.
final class PanelTab {
    var url: URL
    var history: [URL]
    var historyIndex = 0
    var cursorName: String?
    var sort = FileSort()

    init(url: URL, sort: FileSort = FileSort()) {
        self.url = url
        self.history = [url]
        self.sort = sort
    }

    func visit(_ u: URL) {
        if history.indices.contains(historyIndex), history[historyIndex] == u { return }
        history = Array(history.prefix(historyIndex + 1)) + [u]
        if history.count > 60 { history.removeFirst(history.count - 60) }
        historyIndex = history.count - 1
    }
}

protocol FilePanelDelegate: AnyObject {
    func panelDidBecomeActive(_ panel: FilePanel)
    func panelOpenFile(_ panel: FilePanel, item: FileItem)
    func panelShowLocations(_ panel: FilePanel)
    func panelCursorChanged(_ panel: FilePanel)
    /// Tasto destro: il menu per gli elementi selezionati (`items` vuoto = la cartella del pannello).
    func panelContextMenu(_ panel: FilePanel, items: [FileItem]) -> NSMenu?
}

final class FilePanel: NSView, NSTableViewDataSource, NSTableViewDelegate, NSTextFieldDelegate {
    weak var delegate: FilePanelDelegate?
    let side: Side

    var tabs: [PanelTab]
    var activeTabIndex = 0
    var tab: PanelTab { tabs[activeTabIndex] }
    var currentURL: URL { tab.url }

    private(set) var allItems: [FileItem] = []
    private(set) var items: [FileItem] = []
    private(set) var marked = Set<URL>()
    private var savedSelection = Set<String>()
    private var dirSizes: [URL: Int64] = [:]
    /// Cambia a ogni cartella: ferma il calcolo di Option+Shift+Invio se si esce.
    private var sizeJob = 0
    /// Ricerca rapida come in TC: il cursore salta al primo nome che inizia con le lettere scritte.
    private(set) var search = ""
    private var watcher: DirectoryWatcher?
    private var reloadPending = false

    /// Ctrl+B (tutti i file delle sottocartelle) e "Apri pannello" della ricerca mostrano un elenco
    /// che non è una cartella. Qualsiasi spostamento torna all'elenco normale.
    enum ListMode { case normal, branch, results }
    private(set) var mode: ListMode = .normal
    /// Option+↓: le cartelle visitate in questo pannello, dalla più recente, senza doppioni (come TC).
    var visited: [URL] = []
    /// Cartelle scelte con Ctrl+Shift+B (vuoto = la cartella del pannello).
    private var branchRoots: [URL] = []
    private final class Cancel { var cancelled = false }
    private var branchJob: Cancel?

    var isActive = false { didSet { refreshActiveLook() } }

    private let tabBar = NSStackView()
    private let locationButton = NSButton(title: "", target: nil, action: nil)
    private let pathLabel = PathBar()
    private let freeLabel = NSTextField(labelWithString: "")
    private let scroll = NSScrollView()
    let table = PanelTableView()
    private let filterLabel = NSTextField(labelWithString: "")
    private let statusLabel = NSTextField(labelWithString: "")

    private var pathBar: NSView?
    private var renameField: NSTextField?
    private var renamingItem: FileItem?

    init(side: Side, tabs: [PanelTab], activeTab: Int) {
        self.side = side
        self.tabs = tabs.isEmpty ? [PanelTab(url: FileManager.default.homeDirectoryForCurrentUser)] : tabs
        self.activeTabIndex = min(max(activeTab, 0), self.tabs.count - 1)
        super.init(frame: .zero)
        build()
        NotificationCenter.default.addObserver(forName: Settings.changed, object: nil, queue: .main) { [weak self] _ in
            self?.applySettings()
        }
    }

    /// Colori, testo e file nascosti cambiati nelle Impostazioni.
    private func applySettings() {
        layer?.backgroundColor = Theme.background.cgColor
        table.backgroundColor = Theme.background
        scroll.backgroundColor = Theme.background
        table.rowHeight = Theme.rowHeight
        filterLabel.textColor = Theme.filterText
        refreshActiveLook()
        applyFilterAndSort(select: tab.cursorName)
    }

    required init?(coder: NSCoder) { fatalError() }

    // MARK: - Costruzione

    private func build() {
        wantsLayer = true
        layer?.backgroundColor = Theme.background.cgColor

        tabBar.orientation = .horizontal
        tabBar.spacing = 2
        tabBar.alignment = .centerY

        locationButton.bezelStyle = .push
        locationButton.controlSize = .small
        locationButton.font = Theme.small
        locationButton.target = self
        locationButton.action = #selector(locationClicked)
        locationButton.toolTip = side == .left ? "Posizione (Option+F1)" : "Posizione (Option+F2)"
        for l in [freeLabel, filterLabel, statusLabel] {
            l.font = Theme.small
            l.textColor = .secondaryLabelColor
            l.lineBreakMode = .byTruncatingHead
            // Un testo lungo (il percorso del file sotto il cursore) si accorcia: la finestra non deve allargarsi.
            l.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
            l.cell?.truncatesLastVisibleLine = true
        }
        pathLabel.textColor = .white
        pathLabel.onClick = { [weak self] in
            guard let self else { return }
            self.delegate?.panelDidBecomeActive(self)
        }
        pathLabel.onNavigate = { [weak self] url in
            guard let self else { return }
            self.navigate(to: url, select: self.currentURL.path.hasPrefix(url.path) ? self.childName(of: url) : nil)
            self.window?.makeFirstResponder(self.table)
        }
        pathLabel.onSubmit = { [weak self] text in self?.goToTypedPath(text) }
        freeLabel.alignment = .right
        freeLabel.setContentHuggingPriority(.required, for: .horizontal)
        freeLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
        filterLabel.textColor = Theme.filterText
        filterLabel.isHidden = true

        let header = NSStackView(views: [locationButton, pathLabel, freeLabel])
        header.orientation = .horizontal
        header.spacing = 8
        header.edgeInsets = NSEdgeInsets(top: 2, left: 4, bottom: 2, right: 6)
        header.wantsLayer = true
        pathBar = header
        pathLabel.setContentHuggingPriority(.defaultLow, for: .horizontal)
        pathLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)

        table.panel = self
        table.dataSource = self
        table.delegate = self
        table.backgroundColor = Theme.background
        table.rowHeight = Theme.rowHeight
        table.intercellSpacing = NSSize(width: 6, height: 0)
        table.allowsTypeSelect = false
        table.allowsEmptySelection = false
        table.allowsMultipleSelection = false
        table.focusRingType = .none
        table.style = .plain
        table.gridStyleMask = []
        table.columnAutoresizingStyle = .firstColumnOnlyAutoresizingStyle
        table.target = self
        table.doubleAction = #selector(doubleClicked)
        for (id, title, width, align) in [("name", "Nome", 300.0, NSTextAlignment.left), ("ext", "Estensione", 75.0, .left),
                                          ("size", "Dimens.", 110.0, .right), ("date", "Data/ora", 130.0, .left)] {
            let c = NSTableColumn(identifier: NSUserInterfaceItemIdentifier(id))
            c.title = title
            c.width = width
            c.minWidth = 40
            c.headerCell.alignment = align
            if id == "name" { c.resizingMask = .autoresizingMask } else { c.resizingMask = .userResizingMask }
            table.addTableColumn(c)
        }
        scroll.documentView = table
        scroll.hasVerticalScroller = true
        scroll.drawsBackground = true
        scroll.backgroundColor = Theme.background
        scroll.borderType = .noBorder

        let stack = NSStackView(views: [tabBar, header, scroll, filterLabel, statusLabel])
        stack.orientation = .vertical
        stack.alignment = .leading
        stack.spacing = 3
        stack.edgeInsets = NSEdgeInsets(top: 4, left: 4, bottom: 4, right: 4)
        stack.translatesAutoresizingMaskIntoConstraints = false
        addSubview(stack)
        NSLayoutConstraint.activate([
            stack.leadingAnchor.constraint(equalTo: leadingAnchor),
            stack.trailingAnchor.constraint(equalTo: trailingAnchor),
            stack.topAnchor.constraint(equalTo: topAnchor),
            stack.bottomAnchor.constraint(equalTo: bottomAnchor),
            scroll.widthAnchor.constraint(equalTo: stack.widthAnchor, constant: -8),
            header.widthAnchor.constraint(equalTo: stack.widthAnchor, constant: -8),
            statusLabel.widthAnchor.constraint(lessThanOrEqualTo: stack.widthAnchor, constant: -8),
            filterLabel.widthAnchor.constraint(lessThanOrEqualTo: stack.widthAnchor, constant: -8),
        ])
        scroll.setContentHuggingPriority(.defaultLow, for: .vertical)
    }

    // MARK: - Navigazione

    /// Apre una cartella. La lettura avviene in sottofondo (NAS lenti, server FTP, richieste di permesso
    /// di macOS): se finisce entro un attimo si vede subito, altrimenti compare "Caricamento…" e l'app
    /// resta usabile. Vince sempre l'ultima cartella chiesta. `completion(false)` se non si può leggere.
    func navigate(to url: URL, select: String? = nil, record: Bool = true, quiet: Bool = false,
                  completion: ((Bool) -> Void)? = nil) {
        cancelRename()
        branchJob?.cancelled = true
        let remote = FtpRegistry.isRemote(url)
        let url = remote ? url : url.standardizedFileURL
        loadToken += 1
        let token = loadToken
        let state = LoadState()
        let apply: (Result<[FileItem], Error>) -> Void = { [weak self] result in
            guard let self, token == self.loadToken, !state.applied else { return }
            state.applied = true
            self.isLoading = false
            switch result {
            case .success(let list):
                self.show(url, list: list, select: select, record: record)
                completion?(true)
            case .failure(let error):
                self.updateStatus()
                if !quiet { self.reportOpenError(url, error) }
                completion?(false)
            }
        }
        let done = DispatchSemaphore(value: 0)
        DispatchQueue.global(qos: .userInitiated).async {
            let result = Result { remote ? try FilePanel.listRemote(url) : try DirectoryLister.list(url) }
            state.result = result
            done.signal()
            DispatchQueue.main.async { apply(result) }
        }
        // Le cartelle normali rispondono in pochi millisecondi: si aspettano, così non c'è sfarfallio.
        if done.wait(timeout: .now() + .milliseconds(150)) == .success, let r = state.result {
            apply(r)
            return
        }
        isLoading = true
        statusLabel.stringValue = "Caricamento di \(Format.path(url))…"
    }

    private final class LoadState {
        var applied = false
        var result: Result<[FileItem], Error>?
    }

    private var loadToken = 0
    private(set) var isLoading = false

    private func reportOpenError(_ url: URL, _ error: Error) {
        var info = error.localizedDescription
        // Permesso negato da macOS (es. Google Drive, Dropbox, Scrivania): si riattiva nelle Impostazioni.
        let ns = error as NSError
        let posix = (ns.userInfo[NSUnderlyingErrorKey] as? NSError).flatMap { $0.domain == NSPOSIXErrorDomain ? $0.code : nil }
        if ns.code == NSFileReadNoPermissionError || posix == Int(EPERM) || posix == Int(EACCES) {
            info += "\n\nSe prima hai risposto \"Non consentire\": Impostazioni di Sistema › Privacy e sicurezza › File e cartelle › Mac Commander."
        }
        Dialogs.message("Non riesco ad aprire \(Format.path(url))", info: info, style: .warning)
    }

    /// Mostra un elenco già letto (da disco o dal server).
    private func show(_ url: URL, list: [FileItem], select: String?, record: Bool) {
        if url != currentURL || record {
            marked.removeAll()
            dirSizes.removeAll()
            sizeJob += 1
        }
        if url != currentURL { search = "" }
        mode = .normal
        branchJob?.cancelled = true
        tab.url = url
        if record { tab.visit(url) }
        visited.removeAll { $0.path == url.path }
        visited.insert(url, at: 0)
        if visited.count > 40 { visited.removeLast(visited.count - 40) }
        allItems = list
        applyFilterAndSort(select: select ?? (url == currentURL ? tab.cursorName : nil))
        watcher = url.isFileURL ? DirectoryWatcher(url: url) { [weak self] in self?.scheduleReload() } : nil
        updateHeader()
        updateTabBar()
    }

    // MARK: - FTP

    var isRemote: Bool { FtpRegistry.isRemote(currentURL) }

    static func listRemote(_ url: URL) throws -> [FileItem] {
        guard let s = FtpRegistry.session(for: url) else { throw TransferError("La connessione FTP è stata chiusa") }
        return try s.list(url.path).map { e in
            FileItem(url: url.appendingPathComponent(e.name), name: e.name, isDirectory: e.isDirectory || e.isLink,
                     isHidden: e.name.hasPrefix("."), isSymlink: e.isLink, size: e.size, modified: e.modified)
        }
    }

    /// L'elenco del server arriva in un secondo momento: intanto si vede "Caricamento…".
    /// Rilegge la cartella tenendo cursore, selezione e filtro.
    func refresh() {
        switch mode {
        case .branch: loadBranch(keepCursor: true); return
        case .results: refreshResults(); return
        case .normal: break
        }
        if isRemote {
            let url = currentURL, row = table.selectedRow
            DispatchQueue.global(qos: .userInitiated).async {
                let list = try? FilePanel.listRemote(url)
                DispatchQueue.main.async { [weak self] in
                    guard let self, let list, self.currentURL == url, self.mode == .normal else { return }
                    self.allItems = list
                    let existing = Set(list.map(\.url))
                    self.marked = self.marked.filter { existing.contains($0) }
                    self.applyFilterAndSort(select: self.tab.cursorName, fallbackRow: row)
                }
            }
            return
        }
        guard !isLoading else { return }
        let url = currentURL
        DispatchQueue.global(qos: .userInitiated).async {
            let list = try? DirectoryLister.list(url)
            // La cartella non c'è più (disco scollegato, cancellata): si cerca la prima che esiste risalendo.
            var parent = url.deletingLastPathComponent()
            if list == nil {
                while parent.path != "/" && !FileManager.default.fileExists(atPath: parent.path) { parent = parent.deletingLastPathComponent() }
            }
            DispatchQueue.main.async { [weak self] in
                guard let self, self.currentURL == url, !self.isLoading, self.mode == .normal else { return }
                guard let list else { self.navigate(to: parent, quiet: true); return }
                let row = self.table.selectedRow
                self.allItems = list
                let existing = Set(list.map(\.url))
                self.marked = self.marked.filter { existing.contains($0) }
                self.applyFilterAndSort(select: self.tab.cursorName, fallbackRow: row)
                self.updateHeader()
            }
        }
    }

    private func scheduleReload() {
        guard !reloadPending else { return }
        reloadPending = true
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) { [weak self] in
            self?.reloadPending = false
            self?.refresh()
        }
    }

    private func applyFilterAndSort(select: String?, fallbackRow: Int = 0) {
        let visible = Settings.shared.showHidden ? allItems : allItems.filter { !$0.isHidden }
        var list = DirectoryLister.sorted(visible, by: tab.sort) { [dirSizes] in dirSizes[$0] }
        // Nella vista con le sottocartelle ".." torna all'elenco normale; nei risultati non c'è (come in TC).
        if mode != .results, let p = FileItem.parent(of: currentURL) { list.insert(p, at: 0) }
        items = list
        table.reloadData()
        updateSortIndicator()
        var row = min(fallbackRow, max(items.count - 1, 0))
        if let select, let i = items.firstIndex(where: { $0.name == select }) { row = i }
        setCursor(row)
        updateSearchLabel()
    }

    var cursorRow: Int { table.selectedRow }
    var cursorItem: FileItem? { items.indices.contains(cursorRow) ? items[cursorRow] : nil }

    func setCursor(_ row: Int) {
        guard !items.isEmpty else { updateStatus(); return }
        let r = min(max(row, 0), items.count - 1)
        table.selectRowIndexes(IndexSet(integer: r), byExtendingSelection: false)
        table.scrollRowToVisible(r)
        tab.cursorName = items[r].name
        updateStatus()
    }

    func moveCursor(by delta: Int) {
        endSearch()
        setCursor(cursorRow + delta)
    }

    var pageSize: Int { max(Int(scroll.contentView.bounds.height / Theme.rowHeight) - 1, 1) }

    func open() {
        guard let item = cursorItem else { return }
        if item.isParent { goParent(); return }
        if item.showsAsFolder { navigate(to: item.url); return }
        if enterArchive(item) { return }
        delegate?.panelOpenFile(self, item: item)
    }

    /// Come in TC: Invio su uno zip, rar, 7z… ci entra come in una cartella.
    /// I file compressi da soli (.gz, .xz…) che non sono archivi si aprono normalmente.
    private func enterArchive(_ item: FileItem) -> Bool {
        guard !isRemote, ArchivePath.isArchiveName(item.name), !ArchivePath.isInside(item.url) else { return false }
        let plain: Set<String> = ["gz", "bz2", "xz", "z", "lz", "lzma"]
        let mayBePlain = plain.contains(item.ext.lowercased()) && !item.name.lowercased().contains(".tar.")
        navigate(to: item.url, quiet: mayBePlain) { [weak self] ok in
            guard let self, !ok, mayBePlain else { return }
            self.delegate?.panelOpenFile(self, item: item)
        }
        return true
    }

    /// Ctrl+PgGiù: entra nella cartella, nel pacchetto (.app) o nell'archivio sotto il cursore.
    func enterAnyFolder() {
        guard let item = cursorItem else { return }
        if item.isParent { goParent(); return }
        if item.isDirectory { navigate(to: item.url); return }
        _ = enterArchive(item)
    }

    /// Il pannello mostra il contenuto di un archivio.
    var isInArchive: Bool { mode == .normal && ArchivePath.isBrowsable(currentURL) }

    func goParent() {
        if mode != .normal { leaveSpecialMode(); return }
        let cur = currentURL
        guard cur.path != "/" else { return }
        navigate(to: cur.deletingLastPathComponent(), select: cur.lastPathComponent)
    }

    func goRoot() {
        if isRemote, let id = currentURL.host {
            navigate(to: FtpRegistry.url(id: id, path: "/"))
            return
        }
        let vol = (try? currentURL.resourceValues(forKeys: [.volumeURLKey]))?.volume ?? URL(fileURLWithPath: "/")
        navigate(to: vol.standardizedFileURL.path == currentURL.path ? URL(fileURLWithPath: "/") : vol)
    }

    func historyMove(_ delta: Int) {
        // Dalla vista con le sottocartelle o dai risultati si torna prima all'elenco normale.
        if mode != .normal && delta < 0 { leaveSpecialMode(); return }
        let i = tab.historyIndex + delta
        guard tab.history.indices.contains(i) else { NSSound.beep(); return }
        tab.historyIndex = i
        navigate(to: tab.history[i], record: false)
    }

    func historyJump(_ index: Int) {
        guard tab.history.indices.contains(index) else { return }
        tab.historyIndex = index
        navigate(to: tab.history[index], record: false)
    }

    // MARK: - Vista con le sottocartelle (Ctrl+B) e risultati della ricerca

    /// Ctrl+B: tutti i file della cartella e delle sottocartelle; ripremuto torna all'elenco normale.
    /// Ctrl+Shift+B: solo le cartelle selezionate.
    func toggleBranchView(selectedOnly: Bool) {
        if mode == .branch && !selectedOnly { leaveSpecialMode(); return }
        guard !isRemote else { showMessage("Sulle cartelle FTP non c'è"); NSSound.beep(); return }
        var roots: [URL] = []
        if selectedOnly {
            roots = items.filter { marked.contains($0.url) && $0.showsAsFolder }.map(\.url)
            if roots.isEmpty, let c = cursorItem, c.showsAsFolder, !c.isParent { roots = [c.url] }
            guard !roots.isEmpty else { NSSound.beep(); return }
        }
        branchRoots = roots
        loadBranch(keepCursor: false)
    }

    private func loadBranch(keepCursor: Bool) {
        branchJob?.cancelled = true
        let job = Cancel()
        branchJob = job
        let roots = branchRoots.isEmpty ? [currentURL] : branchRoots
        let hidden = Settings.shared.showHidden
        let row = cursorRow
        let wasBranch = mode == .branch
        if !keepCursor { showMessage("Leggo le sottocartelle…") }
        DispatchQueue.global(qos: .userInitiated).async {
            let result = Result { try DirectoryLister.listBranch(roots, includeHidden: hidden) { job.cancelled } }
            DispatchQueue.main.async { [weak self] in
                guard let self, !job.cancelled else { return }
                switch result {
                case .success(let list):
                    if !keepCursor || !wasBranch {
                        self.marked.removeAll()
                        self.search = ""
                    } else {
                        let existing = Set(list.map(\.url))
                        self.marked = self.marked.filter { existing.contains($0) }
                    }
                    self.mode = .branch
                    self.watcher = nil
                    self.allItems = list
                    self.applyFilterAndSort(select: keepCursor ? self.tab.cursorName : nil, fallbackRow: keepCursor ? row : 0)
                    self.updateHeader()
                case .failure(let e):
                    self.updateStatus()
                    self.reportOpenError(roots[0], e)
                }
            }
        }
    }

    /// "Apri pannello" della ricerca: i file trovati, con il percorso intero nel nome.
    func showResults(_ list: [FileItem]) {
        cancelRename()
        branchJob?.cancelled = true
        loadToken += 1
        isLoading = false
        mode = .results
        watcher = nil
        marked.removeAll()
        search = ""
        allItems = list
        applyFilterAndSort(select: nil)
        updateHeader()
    }

    /// I file dei risultati spostati o cancellati spariscono dall'elenco.
    private func refreshResults() {
        let urls = allItems.map(\.url)
        let row = cursorRow
        DispatchQueue.global(qos: .userInitiated).async {
            let list = urls.compactMap { DirectoryLister.item(at: $0) }
            DispatchQueue.main.async { [weak self] in
                guard let self, self.mode == .results else { return }
                self.allItems = list
                let existing = Set(list.map(\.url))
                self.marked = self.marked.filter { existing.contains($0) }
                self.applyFilterAndSort(select: self.tab.cursorName, fallbackRow: row)
            }
        }
    }

    /// Torna all'elenco normale della cartella, col cursore sul file su cui era (se è lì).
    func leaveSpecialMode() {
        let here = cursorItem.flatMap { $0.url.deletingLastPathComponent().path == currentURL.path ? $0.name : nil }
        branchJob?.cancelled = true
        marked.removeAll()
        navigate(to: currentURL, select: here, record: false)
    }

    // MARK: - Ricerca rapida

    var quickSearchActive: Bool { !search.isEmpty }

    /// Aggiunge lettere alla ricerca. Se nessun nome inizia così, la lettera non entra (come in TC).
    func appendSearch(_ s: String) {
        let candidate = search + s
        guard let row = firstMatch(candidate) else {
            NSSound.beep()
            return
        }
        search = candidate
        setCursor(row)
        updateSearchLabel()
    }

    /// ↑/↓ durante la ricerca: nome precedente o successivo che corrisponde.
    func searchNext(_ dir: Int) {
        let n = items.count
        guard n > 0 else { return }
        var r = cursorRow
        for _ in 0..<n {
            r = (r + dir + n) % n
            if matches(items[r], search) { setCursor(r); return }
        }
    }

    /// ⌫: toglie una lettera dalla ricerca, oppure sale di una cartella.
    func backspace() {
        if search.isEmpty { goParent(); return }
        search.removeLast()
        if !search.isEmpty, let row = firstMatch(search), !matches(cursorItem, search) { setCursor(row) }
        updateSearchLabel()
    }

    func endSearch() {
        guard !search.isEmpty else { return }
        search = ""
        updateSearchLabel()
    }

    private func matches(_ item: FileItem?, _ text: String) -> Bool {
        guard let item, !item.isParent else { return false }
        return Matcher.quickFilter(item.name, filter: text)
    }

    private func firstMatch(_ text: String) -> Int? {
        if matches(cursorItem, text) && text.count > 1 { return cursorRow }
        return items.firstIndex { matches($0, text) }
    }

    private func updateSearchLabel() {
        filterLabel.isHidden = search.isEmpty
        filterLabel.stringValue = "Cerca: \(search)▏"
    }

    // MARK: - Selezione

    /// Elementi su cui agire: quelli selezionati, altrimenti quello sotto il cursore.
    func selectedItems() -> [FileItem] {
        let m = items.filter { marked.contains($0.url) }
        if !m.isEmpty { return m }
        if let c = cursorItem, !c.isParent { return [c] }
        return []
    }

    func toggleMark(row: Int) {
        guard items.indices.contains(row), !items[row].isParent else { return }
        let item = items[row]
        if marked.contains(item.url) { marked.remove(item.url) } else {
            marked.insert(item.url)
            if item.showsAsFolder && dirSizes[item.url] == nil && item.url.isFileURL && Settings.shared.markedFolderSize { computeSize(item.url) }
        }
        table.reloadData(forRowIndexes: IndexSet(integer: row), columnIndexes: IndexSet(integersIn: 0..<4))
        updateStatus()
    }

    func markAndMove(_ delta: Int) {
        toggleMark(row: cursorRow)
        moveCursor(by: delta)
    }

    func markRange(to row: Int) {
        let from = cursorRow
        for r in min(from, row)...max(from, row) where items.indices.contains(r) && !items[r].isParent {
            marked.insert(items[r].url)
        }
        table.reloadData()
        setCursor(row)
    }

    func setMarks(where predicate: (FileItem) -> Bool, on: Bool) {
        for i in items where !i.isParent && predicate(i) {
            if on { marked.insert(i.url) } else { marked.remove(i.url) }
        }
        reloadKeepingCursor()
    }

    func invertMarks() {
        for i in items where !i.isParent {
            if marked.contains(i.url) { marked.remove(i.url) } else { marked.insert(i.url) }
        }
        reloadKeepingCursor()
    }

    /// Ricorda la selezione (per Num /) e la toglie: si fa dopo copia, sposta, elimina.
    func clearMarksAfterOperation() {
        guard !marked.isEmpty else { return }
        savedSelection = Set(items.filter { marked.contains($0.url) }.map(\.name))
        marked.removeAll()
        reloadKeepingCursor()
    }

    func restoreSelection() {
        for i in items where savedSelection.contains(i.name) { marked.insert(i.url) }
        reloadKeepingCursor()
    }

    private func reloadKeepingCursor() {
        let r = cursorRow
        table.reloadData()
        setCursor(r)
    }

    /// Option+Shift+Invio (come in TC): calcola lo spazio di tutte le cartelle qui, una alla volta.
    func computeAllFolderSizes() {
        let urls = allItems.filter { $0.showsAsFolder && !$0.isParent && dirSizes[$0.url] == nil }.map(\.url)
        guard currentURL.isFileURL, !urls.isEmpty else { return }
        sizeJob += 1
        let job = sizeJob
        showMessage("Calcolo lo spazio di \(urls.count) cartelle…")
        DispatchQueue.global(qos: .userInitiated).async { [weak self] in
            for u in urls {
                guard let self, self.sizeJob == job else { return }
                let s = DirectoryLister.totalSize(of: u) { self.sizeJob != job }
                DispatchQueue.main.async {
                    guard self.sizeJob == job else { return }
                    self.dirSizes[u] = s.bytes
                    if let r = self.items.firstIndex(where: { $0.url == u }) {
                        self.table.reloadData(forRowIndexes: IndexSet(integer: r), columnIndexes: IndexSet(integersIn: 0..<self.table.numberOfColumns))
                    }
                    self.updateStatus()
                }
            }
            DispatchQueue.main.async {
                guard let self, self.sizeJob == job else { return }
                if self.tab.sort.key == .size { self.applyFilterAndSort(select: self.tab.cursorName) }
                self.updateStatus()
            }
        }
    }

    func computeSize(_ url: URL, done: ((Int64, Int, Int) -> Void)? = nil) {
        DispatchQueue.global(qos: .userInitiated).async { [weak self] in
            let s = DirectoryLister.totalSize(of: url)
            DispatchQueue.main.async {
                guard let self else { return }
                if self.allItems.contains(where: { $0.url == url }) {
                    self.dirSizes[url] = s.bytes
                    self.reloadKeepingCursor()
                }
                done?(s.bytes, s.files, s.folders)
            }
        }
    }

    // MARK: - Schede

    func newTab(url: URL? = nil, activate: Bool = true) {
        let t = PanelTab(url: url ?? currentURL, sort: tab.sort)
        tabs.insert(t, at: activeTabIndex + 1)
        if activate { switchTab(activeTabIndex + 1) } else { updateTabBar() }
    }

    func closeTab() {
        guard tabs.count > 1 else { NSSound.beep(); return }
        tabs.remove(at: activeTabIndex)
        switchTab(min(activeTabIndex, tabs.count - 1))
    }

    func closeOtherTabs() {
        tabs = [tab]
        activeTabIndex = 0
        updateTabBar()
    }

    func switchTab(_ i: Int) {
        guard tabs.indices.contains(i) else { return }
        activeTabIndex = i
        search = ""
        navigate(to: tab.url, select: tab.cursorName, record: false, quiet: true) { [weak self] ok in
            if !ok { self?.navigate(to: FileManager.default.homeDirectoryForCurrentUser) }
        }
    }

    func cycleTab(_ delta: Int) {
        guard tabs.count > 1 else { return }
        switchTab((activeTabIndex + delta + tabs.count) % tabs.count)
    }

    private func updateTabBar() {
        tabBar.arrangedSubviews.forEach { $0.removeFromSuperview() }
        tabBar.isHidden = tabs.count < 2
        guard tabs.count > 1 else { return }
        for (i, t) in tabs.enumerated() {
            let name = t.url.path == "/" ? "/" : t.url.lastPathComponent
            let b = ActionButton(name) { [weak self] in
                guard let self else { return }
                self.delegate?.panelDidBecomeActive(self)
                self.switchTab(i)
            }
            b.bezelStyle = .push
            b.controlSize = .small
            b.font = Theme.small
            b.setButtonType(.pushOnPushOff)
            b.state = i == activeTabIndex ? .on : .off
            b.toolTip = Format.path(t.url)
            tabBar.addArrangedSubview(b)
        }
    }

    // MARK: - Intestazione e stato

    private func updateHeader() {
        switch mode {
        case .branch:
            pathLabel.show(currentURL)
            freeLabel.stringValue = branchRoots.isEmpty ? "Con tutte le sottocartelle (Ctrl+B)" : "Cartelle selezionate (Ctrl+Shift+B)"
            return
        case .results:
            pathLabel.show(currentURL)
            freeLabel.stringValue = "Esito della ricerca (⌫ per uscire)"
            return
        case .normal: break
        }
        if let a = ArchivePath.split(currentURL) {
            locationButton.title = "▾ Archivio"
            pathLabel.show(currentURL)
            let size = (try? a.archive.resourceValues(forKeys: [.fileSizeKey]).fileSize).map { Format.short(Int64($0 ?? 0)) } ?? ""
            freeLabel.stringValue = "\(a.archive.lastPathComponent)  \(size)"
            return
        }
        if let s = FtpRegistry.session(for: currentURL) {
            locationButton.title = "▾ FTP"
            pathLabel.show(currentURL)
            freeLabel.stringValue = s.connection.host + (s.connection.tls || s.connection.implicitTLS ? " 🔒" : "")
            return
        }
        let keys: Set<URLResourceKey> = [.volumeLocalizedNameKey, .volumeAvailableCapacityForImportantUsageKey,
                                         .volumeAvailableCapacityKey, .volumeTotalCapacityKey]
        let v = try? currentURL.resourceValues(forKeys: keys)
        locationButton.title = "▾ " + (v?.volumeLocalizedName ?? "Disco")
        pathLabel.show(currentURL)
        // Sui dischi di rete la capacità "importante" vale 0: si usa quella semplice.
        let important = v?.volumeAvailableCapacityForImportantUsage ?? 0
        let free = important > 0 ? important : v?.volumeAvailableCapacity.map(Int64.init)
        if let free, let total = v?.volumeTotalCapacity {
            freeLabel.stringValue = "\(Format.short(free)) liberi di \(Format.short(Int64(total)))"
        } else {
            freeLabel.stringValue = ""
        }
        window?.title = "Mac Commander"
    }

    /// Nome della sottocartella di `ancestor` da cui si viene (per rimetterci il cursore).
    private func childName(of ancestor: URL) -> String? {
        let a = ancestor.path.hasSuffix("/") ? ancestor.path : ancestor.path + "/"
        guard currentURL.path.hasPrefix(a) else { return nil }
        return currentURL.path.dropFirst(a.count).split(separator: "/").first.map(String.init)
    }

    /// Invio nella barra del percorso: va alla cartella scritta (o alla cartella del file, col cursore sul file).
    private func goToTypedPath(_ raw: String) {
        defer { window?.makeFirstResponder(table) }
        let text = raw.trimmingCharacters(in: .whitespaces)
        guard !text.isEmpty else { return }
        if isRemote, let id = currentURL.host {
            var p = text
            if let s = FtpRegistry.session(for: currentURL), p.hasPrefix(s.connection.name + ":") { p.removeFirst(s.connection.name.count + 1) }
            if !p.hasPrefix("/") { p = currentURL.appendingPathComponent(p).path }
            navigate(to: FtpRegistry.url(id: id, path: p))
            return
        }
        var path = (text as NSString).expandingTildeInPath
        if !path.hasPrefix("/") { path = currentURL.appendingPathComponent(path).path }
        let url = URL(fileURLWithPath: path).standardizedFileURL
        var isDir: ObjCBool = false
        // Un archivio o una cartella al suo interno ("~/x.zip/cartella").
        if ArchivePath.split(url) != nil, !FileManager.default.fileExists(atPath: url.path, isDirectory: &isDir) || !isDir.boolValue {
            navigate(to: url)
            return
        }
        guard FileManager.default.fileExists(atPath: url.path, isDirectory: &isDir) else {
            Dialogs.message("Questo percorso non esiste", info: text, style: .warning)
            return
        }
        if isDir.boolValue { navigate(to: url) } else { navigate(to: url.deletingLastPathComponent(), select: url.lastPathComponent) }
    }

    func showMessage(_ text: String) {
        statusLabel.stringValue = text
    }

    func updateStatus() {
        // Come in TC: nella vista con le sottocartelle e nei risultati si vede dove sta il file sotto il cursore.
        if mode != .normal, marked.isEmpty, let c = cursorItem, !c.isParent {
            let rel: String
            let base = currentURL.path.hasSuffix("/") ? currentURL.path : currentURL.path + "/"
            if mode == .branch, c.url.path.hasPrefix(base) { rel = String(c.url.path.dropFirst(base.count)) } else { rel = Format.path(c.url) }
            statusLabel.stringValue = c.showsAsFolder ? rel : "\(rel)   \(Format.bytes(c.size))   \(Format.date(c.modified))"
            return
        }
        let files = allItems.filter { !$0.showsAsFolder }
        let folders = allItems.count - files.count
        let sel = items.filter { marked.contains($0.url) }
        let selBytes = sel.reduce(Int64(0)) { $0 + ($1.showsAsFolder ? dirSizes[$1.url] ?? 0 : $1.size) }
        let totBytes = files.reduce(Int64(0)) { $0 + $1.size }
        let selFolders = sel.filter(\.showsAsFolder).count
        let allBytes = totBytes + allItems.filter(\.showsAsFolder).reduce(Int64(0)) { $0 + (dirSizes[$1.url] ?? 0) }
        // Come in TC: "selezionati / totale".
        statusLabel.stringValue = "\(Format.short(selBytes)) / \(Format.short(allBytes)) in \(sel.count - selFolders) / \(files.count) file, \(selFolders) / \(folders) cartelle"
    }

    /// Con il cursore pieno il testo della riga cambia colore: si ridisegnano la riga lasciata e quella nuova.
    private var lastCursorRow = -1
    private func reloadCursorRows() {
        defer { lastCursorRow = cursorRow }
        guard Settings.shared.cursorFilled else { return }
        let rows = IndexSet([lastCursorRow, cursorRow].filter { $0 >= 0 && $0 < items.count })
        table.reloadData(forRowIndexes: rows, columnIndexes: IndexSet(integersIn: 0..<table.numberOfColumns))
    }

    private func refreshActiveLook() {
        table.enumerateAvailableRowViews { rowView, _ in rowView.needsDisplay = true }
        if Settings.shared.cursorFilled, cursorRow >= 0 {
            table.reloadData(forRowIndexes: IndexSet(integer: cursorRow), columnIndexes: IndexSet(integersIn: 0..<table.numberOfColumns))
        }
        pathLabel.textColor = isActive ? .white : .secondaryLabelColor
        freeLabel.textColor = isActive ? .white : .secondaryLabelColor
        pathBar?.layer?.backgroundColor = (isActive ? Theme.pathBarActive : Theme.pathBarInactive).cgColor
    }

    @objc private func locationClicked() {
        delegate?.panelDidBecomeActive(self)
        delegate?.panelShowLocations(self)
    }

    var locationAnchor: NSView { locationButton }
    var historyAnchor: NSView { pathLabel }

    // MARK: - Tabella

    func numberOfRows(in tableView: NSTableView) -> Int { items.count }

    func tableView(_ tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? {
        let rv = PanelRowView()
        rv.panel = self
        if items.indices.contains(row), Settings.shared.tagColors { rv.tint = Icons.labelColor(items[row].label) }
        rv.alternate = row % 2 == 1
        return rv
    }

    func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
        guard let id = tableColumn?.identifier, items.indices.contains(row) else { return nil }
        let item = items[row]
        var color = marked.contains(item.url) ? Theme.markedText : (item.isHidden ? Theme.hiddenText : Theme.text)
        if Settings.shared.cursorFilled && isActive && row == cursorRow && !marked.contains(item.url) { color = Theme.cursorText }
        let hideText = renamingItem?.url == item.url
        if id.rawValue == "name" {
            let cell = (tableView.makeView(withIdentifier: id, owner: self) as? NameCell) ?? NameCell(identifier: id, withIcon: true)
            cell.label.stringValue = hideText ? "" : item.isParent ? ".." : mode == .results ? Format.path(item.url)
                : (item.showsAsFolder ? item.name : item.baseName)
            cell.label.textColor = color
            cell.label.font = Theme.font
            cell.icon.image = Icons.icon(for: item)
            return cell
        }
        let cell = (tableView.makeView(withIdentifier: id, owner: self) as? NameCell) ?? {
            let c = NameCell(identifier: id, withIcon: false)
            c.label.font = id.rawValue == "ext" ? Theme.font : Theme.digits
            c.label.alignment = id.rawValue == "size" ? .right : .left
            c.label.lineBreakMode = .byTruncatingTail
            return c
        }()
        let tf = cell.label
        tf.textColor = color
        tf.font = id.rawValue == "ext" ? Theme.font : Theme.digits
        switch id.rawValue {
        case "ext": tf.stringValue = hideText || mode == .results ? "" : item.ext
        case "size":
            if item.showsAsFolder {
                tf.stringValue = dirSizes[item.url].map(Format.bytes) ?? (item.isParent ? "<SU>" : "<DIR>")
            } else {
                tf.stringValue = Format.bytes(item.size)
            }
        default: tf.stringValue = item.isParent ? "" : Format.date(item.modified)
        }
        return cell
    }

    func tableViewSelectionDidChange(_ notification: Notification) {
        if let c = cursorItem { tab.cursorName = c.name }
        reloadCursorRows()
        updateStatus()
        delegate?.panelCursorChanged(self)
    }

    func tableView(_ tableView: NSTableView, didClick tableColumn: NSTableColumn) {
        let key: SortKey
        switch tableColumn.identifier.rawValue {
        case "ext": key = .ext
        case "size": key = .size
        case "date": key = .date
        default: key = .name
        }
        if tab.sort.key == key { tab.sort.ascending.toggle() } else {
            tab.sort = FileSort(key: key, ascending: key == .name || key == .ext)
        }
        applyFilterAndSort(select: cursorItem?.name)
    }

    private func updateSortIndicator() {
        let idByKey: [SortKey: String] = [.name: "name", .ext: "ext", .size: "size", .date: "date"]
        for c in table.tableColumns {
            let on = c.identifier.rawValue == idByKey[tab.sort.key]
            table.setIndicatorImage(on ? NSImage(named: tab.sort.ascending ? "NSAscendingSortIndicator" : "NSDescendingSortIndicator") : nil, in: c)
        }
    }

    @objc private func doubleClicked() {
        guard table.clickedRow >= 0 else { return }
        open()
    }

    func didClick() { delegate?.panelDidBecomeActive(self) }

    /// Tasto destro come nel Finder: su un elemento non selezionato la selezione diventa quell'elemento;
    /// su uno selezionato il menu vale per tutta la selezione; sullo spazio vuoto, per la cartella.
    func contextMenu(row: Int) -> NSMenu? {
        delegate?.panelDidBecomeActive(self)
        endSearch()
        guard items.indices.contains(row), !items[row].isParent else {
            return delegate?.panelContextMenu(self, items: [])
        }
        if !marked.contains(items[row].url) {
            if !marked.isEmpty {
                marked.removeAll()
                table.reloadData()
            }
            setCursor(row)
        }
        return delegate?.panelContextMenu(self, items: selectedItems())
    }

    /// Per i Servizi e le Azioni rapide del menu: i file selezionati.
    var serviceURLs: [URL] { selectedItems().map(\.url).filter { $0.isFileURL && !ArchivePath.isInside($0) } }

    // MARK: - Rinomina sul posto (Shift+F6)

    var isRenaming: Bool { renameField != nil }

    /// Shift+F6 come in TC: il campo copre nome ed estensione (che spariscono) con tutto selezionato.
    /// Ripremendo Shift+F6 la selezione passa a: solo il nome, solo l'estensione, di nuovo tutto.
    func beginRename() {
        if renameField != nil { cycleRenameSelection(); return }
        guard let item = cursorItem, !item.isParent else { return }
        let row = cursorRow
        table.scrollRowToVisible(row)
        renamingItem = item
        renameRow = row
        renameStep = 0
        // Il nome sotto non deve vedersi: la riga si ridisegna vuota.
        table.reloadData(forRowIndexes: IndexSet(integer: row), columnIndexes: IndexSet(integersIn: 0..<table.numberOfColumns))
        var rect = table.frameOfCell(atColumn: 0, row: row).union(table.frameOfCell(atColumn: 1, row: row))
        let iconWidth: CGFloat = 21   // l'icona resta visibile, come in TC
        rect.origin.x += iconWidth
        rect.size.width -= iconWidth
        let f = NSTextField(frame: rect.insetBy(dx: 0, dy: 0))
        f.stringValue = item.name
        f.font = Theme.font
        f.textColor = Theme.text
        f.isBezeled = false
        f.isBordered = false
        f.drawsBackground = true
        f.backgroundColor = Theme.background
        f.wantsLayer = true
        f.layer?.borderWidth = 1
        f.layer?.borderColor = Theme.cursor.cgColor
        f.delegate = self
        f.focusRingType = .none
        f.cell?.isScrollable = true
        f.cell?.wraps = false
        table.addSubview(f)
        renameField = f
        window?.makeFirstResponder(f)
        f.currentEditor()?.selectAll(nil)
    }

    private var renameRow = -1
    private var renameStep = 0

    private func cycleRenameSelection() {
        guard let f = renameField, let ed = f.currentEditor() else { return }
        let text = f.stringValue as NSString
        let ext = text.pathExtension as NSString
        // Senza estensione (o nomi come ".bashrc") c'è solo "tutto".
        guard ext.length > 0, ext.length + 1 < text.length else { ed.selectAll(nil); return }
        renameStep = (renameStep + 1) % 3
        switch renameStep {
        case 1: ed.selectedRange = NSRange(location: 0, length: text.length - ext.length - 1)
        case 2: ed.selectedRange = NSRange(location: text.length - ext.length, length: ext.length)
        default: ed.selectAll(nil)
        }
    }

    func control(_ control: NSControl, textView: NSTextView, doCommandBy sel: Selector) -> Bool {
        guard control === renameField else { return false }
        if sel == #selector(NSResponder.insertNewline(_:)) { commitRename(); return true }
        if sel == #selector(NSResponder.cancelOperation(_:)) { cancelRename(); return true }
        return false
    }

    func controlTextDidEndEditing(_ obj: Notification) {
        if (obj.object as? NSTextField) === renameField { commitRename() }
    }

    private func commitRename() {
        guard let f = renameField, let item = renamingItem else { return }
        let newName = f.stringValue.trimmingCharacters(in: .whitespaces)
        cancelRename()
        guard !newName.isEmpty, newName != item.name else { return }
        if newName.contains("/") {
            Dialogs.message("Il nome non può contenere \"/\"", style: .warning)
            return
        }
        let dst = item.url.deletingLastPathComponent().appendingPathComponent(newName)
        if let s = FtpRegistry.session(for: item.url) {
            DispatchQueue.global(qos: .userInitiated).async {
                let r = Result { try s.rename(item.url.path, to: dst.path) }
                DispatchQueue.main.async { [weak self] in
                    if case .failure(let e) = r {
                        Dialogs.message("Non riesco a rinominare \"\(item.name)\"", info: e.localizedDescription, style: .warning)
                    }
                    self?.tab.cursorName = newName
                    self?.refresh()
                }
            }
            return
        }
        if FileManager.default.fileExists(atPath: dst.path) && newName.lowercased() != item.name.lowercased() {
            Dialogs.message("\"\(newName)\" esiste già", style: .warning)
            return
        }
        if rename(item.url.path, dst.path) != 0 {
            Dialogs.message("Non riesco a rinominare \"\(item.name)\"", info: String(cString: strerror(errno)), style: .warning)
            return
        }
        tab.cursorName = newName
        refresh()
    }

    func cancelRename() {
        guard let f = renameField else { return }
        renameField = nil
        renamingItem = nil
        f.removeFromSuperview()
        if renameRow >= 0 && renameRow < items.count {
            table.reloadData(forRowIndexes: IndexSet(integer: renameRow), columnIndexes: IndexSet(integersIn: 0..<table.numberOfColumns))
        }
        renameRow = -1
        window?.makeFirstResponder(table)
    }
}

/// Tabella del pannello: Cmd+clic seleziona, Shift+clic seleziona un intervallo.
final class PanelTableView: NSTableView {
    weak var panel: FilePanel?

    override func mouseDown(with event: NSEvent) {
        panel?.didClick()
        let row = self.row(at: convert(event.locationInWindow, from: nil))
        if row >= 0 && event.modifierFlags.contains(.command) { panel?.toggleMark(row: row); return }
        if row >= 0 && event.modifierFlags.contains(.shift) { panel?.markRange(to: row); return }
        super.mouseDown(with: event)
    }

    override func menu(for event: NSEvent) -> NSMenu? {
        panel?.contextMenu(row: row(at: convert(event.locationInWindow, from: nil)))
    }

    // Servizi e Azioni rapide del Mac nel menu del tasto destro (come nel Finder): ricevono i file selezionati.
    override func validRequestor(forSendType sendType: NSPasteboard.PasteboardType?, returnType: NSPasteboard.PasteboardType?) -> Any? {
        if returnType == nil, sendType == .fileURL || sendType == NSPasteboard.PasteboardType("NSFilenamesPboardType"),
           !(panel?.serviceURLs.isEmpty ?? true) {
            return self
        }
        return super.validRequestor(forSendType: sendType, returnType: returnType)
    }

    @objc func writeSelection(to pboard: NSPasteboard, types: [NSPasteboard.PasteboardType]) -> Bool {
        guard let urls = panel?.serviceURLs, !urls.isEmpty else { return false }
        pboard.clearContents()
        pboard.writeObjects(urls as [NSURL])
        pboard.setPropertyList(urls.map(\.path), forType: NSPasteboard.PasteboardType("NSFilenamesPboardType"))
        return true
    }

    // I tasti li gestisce MainWindowController; qui niente selezione col tastiera di AppKit.
    override func keyDown(with event: NSEvent) {}
}

/// Il cursore: barra rossa nel pannello attivo, cornice grigia nell'altro.
final class PanelRowView: NSTableRowView {
    weak var panel: FilePanel?
    /// Colore del tag del Finder, steso leggero su tutta la riga.
    var tint: NSColor?
    /// Riga dispari: "Sfondo righe alterne" delle Impostazioni.
    var alternate = false

    override func drawBackground(in dirtyRect: NSRect) {
        (alternate ? Theme.background2 : Theme.background).setFill()
        bounds.fill()
        guard let tint else { return }
        tint.withAlphaComponent(0.22).setFill()
        bounds.fill()
    }

    override func drawSelection(in dirtyRect: NSRect) {
        // Come in TC: cornice rossa (o barra piena) nel pannello attivo, niente nell'altro.
        guard panel?.isActive ?? false else { return }
        if Settings.shared.cursorFilled {
            Theme.cursor.setFill()
            bounds.fill()
            return
        }
        Theme.cursor.setStroke()
        let p = NSBezierPath(rect: bounds.insetBy(dx: 1, dy: 1))
        p.lineWidth = 1.5
        p.stroke()
    }

    override var isEmphasized: Bool { get { false } set {} }
}

final class NameCell: NSTableCellView {
    let icon = NSImageView()
    let label = NSTextField(labelWithString: "")

    init(identifier id: NSUserInterfaceItemIdentifier, withIcon: Bool) {
        super.init(frame: .zero)
        identifier = id
        label.translatesAutoresizingMaskIntoConstraints = false
        label.font = Theme.font
        label.lineBreakMode = .byTruncatingMiddle
        label.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
        addSubview(label)
        textField = label
        NSLayoutConstraint.activate([
            label.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -2),
            label.centerYAnchor.constraint(equalTo: centerYAnchor),
        ])
        guard withIcon else {
            label.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 2).isActive = true
            return
        }
        icon.translatesAutoresizingMaskIntoConstraints = false
        addSubview(icon)
        imageView = icon
        NSLayoutConstraint.activate([
            icon.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 2),
            icon.centerYAnchor.constraint(equalTo: centerYAnchor),
            icon.widthAnchor.constraint(equalToConstant: 16),
            icon.heightAnchor.constraint(equalToConstant: 16),
            label.leadingAnchor.constraint(equalTo: icon.trailingAnchor, constant: 5),
        ])
    }

    required init?(coder: NSCoder) { fatalError() }
}

/// Icone per tipo di file, tenute in memoria (leggerle file per file sul NAS è lento).
enum Icons {
    private static var cache: [String: NSImage] = [:]

    static func icon(for item: FileItem) -> NSImage {
        if item.isParent { return cached("..") { NSImage(systemSymbolName: "arrow.turn.left.up", accessibilityDescription: nil)! } }
        if item.isPackage { return cached("pkg:" + item.url.path) { NSWorkspace.shared.icon(forFile: item.url.path) } }
        if item.showsAsFolder {
            let color = labelColor(item.label)
            if color == nil && item.folderSymbol == nil { return cached("/") { NSWorkspace.shared.icon(for: .folder) } }
            return cached("/\(item.label)/\(String(describing: item.folderSymbol))") {
                folderIcon(color: color, symbol: item.folderSymbol)
            }
        }
        let ext = item.ext.lowercased()
        return cached("." + ext) {
            NSWorkspace.shared.icon(for: UTType(filenameExtension: ext) ?? .data)
        }
    }

    /// Colori dei tag del Finder, nell'ordine del numero di etichetta.
    static func labelColor(_ label: Int) -> NSColor? {
        let colors = NSWorkspace.shared.fileLabelColors
        guard label > 0, label < colors.count else { return nil }
        return colors[label]
    }

    /// Cartella del colore del tag, con il simbolo scelto nel Finder (come in macOS).
    private static func folderIcon(color: NSColor?, symbol: FolderSymbol?) -> NSImage {
        let base = NSWorkspace.shared.icon(for: .folder)
        let size = NSSize(width: 64, height: 64)
        return NSImage(size: size, flipped: false) { rect in
            base.draw(in: rect)
            if let color {
                color.setFill()
                rect.fill(using: .sourceAtop)
                base.draw(in: rect, from: .zero, operation: .luminosity, fraction: 0.4)
            }
            let glyph = NSRect(x: rect.width * 0.28, y: rect.height * 0.2, width: rect.width * 0.44, height: rect.height * 0.44)
            switch symbol {
            case .symbol(let name)?:
                let cfg = NSImage.SymbolConfiguration(pointSize: glyph.height, weight: .semibold)
                    .applying(.init(paletteColors: [NSColor.black.withAlphaComponent(0.45)]))
                if let img = NSImage(systemSymbolName: name, accessibilityDescription: nil)?.withSymbolConfiguration(cfg) {
                    let s = img.size
                    let k = min(glyph.width / s.width, glyph.height / s.height)
                    let r = NSRect(x: glyph.midX - s.width * k / 2, y: glyph.midY - s.height * k / 2, width: s.width * k, height: s.height * k)
                    img.draw(in: r)
                }
            case .emoji(let e)?:
                let str = NSAttributedString(string: e, attributes: [.font: NSFont.systemFont(ofSize: glyph.height * 0.8)])
                let s = str.size()
                str.draw(at: NSPoint(x: glyph.midX - s.width / 2, y: glyph.midY - s.height / 2))
            case nil: break
            }
            return true
        }
    }

    private static func cached(_ key: String, _ make: () -> NSImage) -> NSImage {
        if let i = cache[key] { return i }
        let i = make()
        i.size = NSSize(width: 16, height: 16)
        cache[key] = i
        return i
    }
}
