import AppKit
import CommanderCore
import Quartz

final class MainWindowController: NSWindowController, NSWindowDelegate, FilePanelDelegate {
    let left: FilePanel
    let right: FilePanel
    private(set) var active: FilePanel
    var other: FilePanel { active === left ? right : left }

    let queue = TransferQueue()
    private var queueWindow: QueueWindowController!
    private var hotlist: [HotlistEntry] = HotlistStore.load()
    private var menuOpen = false
    private let keyMenu = KeyMenu()
    private var cutChangeCount: Int?


    init() {
        let state = AppState.load()
        left = FilePanel(side: .left, tabs: state.left.makeTabs(), activeTab: state.left.active)
        right = FilePanel(side: .right, tabs: state.right.makeTabs(), activeTab: state.right.active)
        active = state.rightActive ? right : left

        let w = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1500, height: 900),
                         styleMask: [.titled, .closable, .miniaturizable, .resizable], backing: .buffered, defer: false)
        w.title = "Mac Commander"
        w.isReleasedWhenClosed = false
        w.minSize = NSSize(width: 800, height: 400)
        super.init(window: w)
        AppWindow.main = w
        w.delegate = self
        buildLayout()
        if !w.setFrameUsingName("Principale") { w.center() }
        w.setFrameAutosaveName("Principale")

        for p in [left, right] {
            p.delegate = self
            p.navigate(to: p.tab.url, select: p.tab.cursorName, record: false, quiet: true) { [weak p] ok in
                if !ok { p?.navigate(to: FileManager.default.homeDirectoryForCurrentUser) }
            }
        }
        setActive(active)

        queueWindow = QueueWindowController(queue: queue)
        queueWindow.onAdd = { [weak self] in
            self?.window?.makeKeyAndOrderFront(nil)
            self?.perform(.copy)
        }
        queue.onChange = { [weak self] in self?.queueWindow.update() }
        queue.onJobFinished = { [weak self] _ in
            self?.left.refresh()
            self?.right.refresh()
        }
    }

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

    private func buildLayout() {
        let split = NSStackView()
        split.orientation = .horizontal
        split.distribution = .fillEqually
        split.spacing = 1
        split.addArrangedSubview(left)
        split.addArrangedSubview(right)
        split.wantsLayer = true
        split.layer?.backgroundColor = Theme.panelDivider.cgColor
        NotificationCenter.default.addObserver(forName: Settings.changed, object: nil, queue: .main) { [weak split] _ in
            split?.layer?.backgroundColor = Theme.panelDivider.cgColor
        }

        let keys: [(String, Command)] = [("F2 Terminale", .terminal), ("F3 Visualizza", .view), ("F4 Modifica", .edit), ("F5 Copia", .copy),
                                         ("F6 Sposta", .move), ("F7 Crea cartella", .mkdir), ("F8 Elimina", .delete),
                                         ("⌥F4 Esci", .quit)]
        let keyBar = NSStackView(views: keys.map { title, cmd in
            let b = ActionButton(title) { [weak self] in self?.perform(cmd) }
            b.bezelStyle = .push
            b.controlSize = .small
            b.font = Theme.small
            return b
        })
        keyBar.orientation = .horizontal
        keyBar.distribution = .fillEqually
        keyBar.spacing = 4
        keyBar.edgeInsets = NSEdgeInsets(top: 3, left: 4, bottom: 4, right: 4)

        let root = NSView()
        for v in [split, keyBar] as [NSView] {
            v.translatesAutoresizingMaskIntoConstraints = false
            root.addSubview(v)
            NSLayoutConstraint.activate([
                v.leadingAnchor.constraint(equalTo: root.leadingAnchor),
                v.trailingAnchor.constraint(equalTo: root.trailingAnchor),
            ])
        }
        NSLayoutConstraint.activate([
            split.topAnchor.constraint(equalTo: root.topAnchor),
            keyBar.topAnchor.constraint(equalTo: split.bottomAnchor),
            keyBar.bottomAnchor.constraint(equalTo: root.bottomAnchor),
            keyBar.heightAnchor.constraint(equalToConstant: 30),
        ])
        window?.contentView = root
    }



    // MARK: - Pannello attivo

    func setActive(_ p: FilePanel) {
        if active !== p { active.cancelRename() }
        active = p
        left.isActive = p === left
        right.isActive = p === right
        refreshQuickLook()
        window?.makeFirstResponder(p.table)
    }

    func panelDidBecomeActive(_ panel: FilePanel) {
        if panel !== active { setActive(panel) }
    }

    func panelOpenFile(_ panel: FilePanel, item: FileItem) {
        if panel.isRemote { remoteOpen(item); return }
        if ArchivePath.isInside(item.url) {
            withExtracted(item.url) { NSWorkspace.shared.open($0) }
            return
        }
        NSWorkspace.shared.open(item.url)
    }

    /// Un file dentro un archivio si estrae in una cartella temporanea per aprirlo, vederlo o modificarlo.
    func withExtracted(_ url: URL, then: @escaping (URL) -> Void) {
        guard ArchivePath.isInside(url) else { then(url); return }
        active.showMessage("Estraggo \(url.lastPathComponent)…")
        DispatchQueue.global(qos: .userInitiated).async {
            let r = Result { try ArchiveReader.extractToTemp(url) }
            DispatchQueue.main.async { [weak self] in
                self?.active.updateStatus()
                switch r {
                case .success(let tmp): then(tmp)
                case .failure(let e): Dialogs.message("Non riesco a estrarre \"\(url.lastPathComponent)\"", info: e.localizedDescription, style: .warning)
                }
            }
        }
    }

    func panelCursorChanged(_ panel: FilePanel) {
        if panel === active { refreshQuickLook() }
    }

    func panelShowLocations(_ panel: FilePanel) {
        showLocations(for: panel)
    }

    // MARK: - Tastiera

    /// Tutti i tasti dell'app passano da qui, prima di AppKit.
    func handleKeyEvent(_ e: NSEvent) -> NSEvent? {
        let flags = e.modifierFlags.intersection([.control, .option, .shift, .command])
        if menuOpen { return e }
        if keyMenu.isOpen { return keyMenu.handleKey(e) ? nil : e }

        // Finestre di dialogo: F2 = Accoda.
        if NSApp.modalWindow != nil {
            if let h = Dialogs.modalKeyHandler, h(e) {
                return nil
            }
            if e.keyCode == KeyCode.f2 && flags.isEmpty, let b = Dialogs.queueButton {
                b.performClick(nil)
                return nil
            }
            return textShortcut(e, flags) ? nil : e
        }

        // Shift+F6 durante la rinomina: cambia la parte selezionata (tutto, nome, estensione).
        if e.keyCode == KeyCode.f6 && flags == .shift && active.isRenaming {
            active.beginRename()
            return nil
        }

        if let sw = NSApp.keyWindow?.windowController as? SearchWindowController, sw.handleKey(e) { return nil }

        // Campi di testo (rinomina, ricerche): Ctrl+C/X/V/A come su Windows.
        if let tv = NSApp.keyWindow?.firstResponder as? NSTextView, tv.isEditable {
            return textShortcut(e, flags) ? nil : e
        }

        if let viewer = NSApp.keyWindow?.windowController as? ViewerWindowController {
            return viewer.handleKey(e) ? nil : e
        }

        guard let window, (NSApp.keyWindow ?? window) === window, window.attachedSheet == nil else { return e }
        if flags.contains(.command) { return e }

        if let cmd = KeyMap.command(for: e, quickSearchActive: active.quickSearchActive) {
            perform(cmd)
            return nil
        }
        // Ricerca rapida: lettere e cifre senza Ctrl/Option.
        if Settings.shared.quickSearch, flags.isDisjoint(with: [.control, .option]), let chars = e.characters, !chars.isEmpty,
           chars.unicodeScalars.allSatisfy({ $0.value >= 0x20 && $0.value != 0x7F && !(0xF700...0xF8FF).contains($0.value) }) {
            active.appendSearch(chars)
            return nil
        }
        return e
    }

    private func textShortcut(_ e: NSEvent, _ flags: NSEvent.ModifierFlags) -> Bool {
        guard flags == .control, let tv = NSApp.keyWindow?.firstResponder as? NSTextView else { return false }
        switch e.charactersIgnoringModifiers?.lowercased() {
        case "c": tv.copy(nil)
        case "x": tv.cut(nil)
        case "v": tv.paste(nil)
        case "a": tv.selectAll(nil)
        case "z": tv.undoManager?.undo()
        default: return false
        }
        return true
    }

    // MARK: - Comandi

    func perform(_ cmd: Command) {
        let p = active
        // Qualsiasi altro comando chiude la ricerca rapida.
        switch cmd {
        case .up, .down, .space, .parentOrFilterBack: break
        default: p.endSearch()
        }
        // Sul server non ci sono: Cestino, appunti, rinomina multipla, dimensione, copia nella stessa cartella.
        if p.isRemote {
            switch cmd {
            case .newTextFile, .copySameDir, .calcSize, .clipCopy, .clipCut, .multiRename, .changeDates:
                p.showMessage("Questo comando non c'è sulle cartelle FTP")
                NSSound.beep()
                return
            case .view, .viewText:
                if let i = p.cursorItem, !i.showsAsFolder { remoteView(i) }
                return
            case .edit:
                if let i = p.cursorItem, !i.showsAsFolder { remoteEdit(i) }
                return
            case .delete, .deletePermanent:
                let items = p.selectedItems()
                if !items.isEmpty { remoteDelete(items) }
                return
            default: break
            }
        }
        // Dentro un archivio si guarda e si copia fuori (F5); per il resto serve Option+F5 / Option+F9.
        if p.isInArchive {
            switch cmd {
            case .move, .delete, .deletePermanent, .renameInPlace, .mkdir, .newTextFile, .multiRename, .changeDates,
                 .clipCopy, .clipCut, .clipPaste, .copySameDir, .branchView, .branchViewSelected, .calcSize, .calcAllSizes,
                 .terminal, .pack, .unpack:
                p.showMessage("Dentro un archivio si può solo copiare fuori (F5) o vedere i file")
                NSSound.beep()
                return
            default: break
            }
        }
        if (cmd == .copy || cmd == .move || cmd == .pack), other.isInArchive {
            p.showMessage("Nell'altro pannello c'è un archivio: per comprimere dei file usa Option+F5")
            NSSound.beep()
            return
        }
        switch cmd {
        case .up: if p.quickSearchActive { p.searchNext(-1) } else { p.moveCursor(by: -1) }
        case .down: if p.quickSearchActive { p.searchNext(1) } else { p.moveCursor(by: 1) }
        case .pageUp: p.moveCursor(by: -p.pageSize)
        case .pageDown: p.moveCursor(by: p.pageSize)
        case .home: p.moveCursor(by: -p.items.count)
        case .end: p.moveCursor(by: p.items.count)
        case .markUp: p.markAndMove(-1)
        case .markDown: p.markAndMove(1)
        case .open: p.open()
        case .parentOrFilterBack: p.backspace()
        case .goParent: p.goParent()
        case .enterPackage: p.enterAnyFolder()
        case .goRoot: p.goRoot()
        case .switchPanel: setActive(other)
        case .escape: if !closeQuickLook() { p.endSearch() }

        case .transferLeft: transfer(to: left)
        case .transferRight: transfer(to: right)
        case .openInNewTab:
            if let i = p.cursorItem, i.showsAsFolder { p.newTab(url: i.isParent ? p.currentURL.deletingLastPathComponent() : i.url) }
            else { p.newTab() }
        case .openInOtherNewTab:
            let url = p.cursorItem.flatMap { $0.showsAsFolder ? ($0.isParent ? p.currentURL.deletingLastPathComponent() : $0.url) : nil } ?? p.currentURL
            other.newTab(url: url)
        case .historyBack: p.historyMove(-1)
        case .historyForward: p.historyMove(1)
        case .historyList: showHistory()
        case .locationLeft: showLocations(for: left)
        case .locationRight: showLocations(for: right)
        case .hotlist: showHotlist()

        case .newTab: p.newTab()
        case .newTabBackground: p.newTab(activate: false)
        case .closeTab: p.closeTab()
        case .closeAllTabs: p.closeOtherTabs()
        case .nextTab: p.cycleTab(1)
        case .prevTab: p.cycleTab(-1)
        case .tabList: showTabList()
        case .swapPanels:
            let l = left.currentURL, r = right.currentURL
            left.navigate(to: r)
            right.navigate(to: l)
        case .reread: p.refresh()
        case .terminal:
            guard !p.isRemote else { p.showMessage("Il terminale si apre solo sulle cartelle del Mac"); NSSound.beep(); return }
            NSWorkspace.shared.open([p.currentURL], withApplicationAt: Settings.shared.terminalURL, configuration: NSWorkspace.OpenConfiguration())

        case .view: toggleQuickLook()
        case .viewText:
            if let i = p.cursorItem, !i.showsAsFolder { withExtracted(i.url) { ViewerWindowController.show($0) } }
        case .edit:
            if let i = p.cursorItem, !i.showsAsFolder { withExtracted(i.url) { [weak self] in self?.openInEditor($0) } }
        case .newTextFile: newTextFile()
        case .copy, .move:
            let kind: TransferKind = cmd == .copy ? .copy : .move
            if p.isRemote || other.isRemote {
                let items = p.selectedItems()
                if !items.isEmpty { remoteCopyOrMove(kind, items: items, from: p, to: other) }
            } else {
                copyOrMove(kind)
            }
        case .copySameDir: copySameDir()
        case .renameInPlace: p.beginRename()
        case .mkdir: makeDirectory()
        case .delete: delete(permanent: !Settings.shared.useTrash)
        case .deletePermanent: delete(permanent: true)
        case .calcSize: calcSize()
        case .calcAllSizes: p.computeAllFolderSizes()
        case .clipCopy: clipboard(cut: false)
        case .clipCut: clipboard(cut: true)
        case .clipPaste: paste()
        case .changeDates:
            let items = p.selectedItems()
            guard !items.isEmpty else { return }
            FileDatesWindow.run(items: items)
            left.refresh()
            right.refresh()
        case .ftpConnect: ftpConnect()
        case .ftpDisconnect: ftpDisconnect()
        case .ftpNewURL: ftpNewURL()
        case .multiRename:
            let items = p.selectedItems()
            guard !items.isEmpty else { return }
            MultiRenameWindow.run(items: items)
            p.clearMarksAfterOperation()
            left.refresh()
            right.refresh()

        case .space:
            if p.quickSearchActive { p.appendSearch(" ") } else { p.markAndMove(Settings.shared.spaceMovesDown ? 1 : 0) }
        case .insertMark: p.markAndMove(1)
        case .selectMask: selectByMask(on: true)
        case .deselectMask: selectByMask(on: false)
        case .invertSelection: p.invertMarks()
        case .restoreSelection: p.restoreSelection()
        case .selectAll: p.setMarks(where: { _ in true }, on: true)
        case .deselectAll: p.setMarks(where: { _ in true }, on: false)
        case .selectSameExt, .deselectSameExt:
            guard let c = p.cursorItem, !c.showsAsFolder else { return }
            let ext = c.ext.lowercased()
            p.setMarks(where: { !$0.showsAsFolder && $0.ext.lowercased() == ext }, on: cmd == .selectSameExt)
        case .branchView: p.toggleBranchView(selectedOnly: false)
        case .branchViewSelected: p.toggleBranchView(selectedOnly: true)
        case .search: SearchWindowController.show(for: self)
        case .pack: pack()
        case .unpack: unpack()
        case .testArchive: testArchives()
        case .quit: NSApp.terminate(nil)
        }
    }

    /// Ctrl+← / Ctrl+→: il pannello verso cui punta la freccia mostra la cartella sotto il cursore
    /// (se il cursore è nell'altro pannello e su una cartella), altrimenti la cartella dell'altro pannello.
    private func transfer(to target: FilePanel) {
        let source = target === left ? right : left
        var url = source.currentURL
        if active === source, let i = source.cursorItem, i.showsAsFolder {
            url = i.isParent ? source.currentURL.deletingLastPathComponent() : i.url
        }
        target.navigate(to: url)
    }

    /// "Vai a" della ricerca: la cartella del file nel pannello attivo, col cursore sul file.
    func showInPanel(_ url: URL) {
        window?.makeKeyAndOrderFront(nil)
        active.navigate(to: url.deletingLastPathComponent(), select: url.lastPathComponent)
        setActive(active)
    }

    /// "Apri pannello" della ricerca.
    func showSearchResults(_ items: [FileItem]) {
        window?.makeKeyAndOrderFront(nil)
        active.showResults(items)
        setActive(active)
    }

    // MARK: - Archivi (Option+F5, Option+F9, Option+Shift+F9)

    private func pack() {
        let items = active.selectedItems()
        guard !items.isEmpty, !active.isRemote, !other.isRemote else { NSSound.beep(); return }
        let targetDir = other.mode == .normal ? other.currentURL : active.currentURL
        guard let o = PackDialog.run(items: items, targetDir: targetDir, currentDir: active.currentURL) else { return }
        let ext = "." + o.format.rawValue
        if o.separate {
            for i in items {
                let name = (i.showsAsFolder ? i.name : i.baseName) + ext
                var job = TransferJob(kind: .pack, sources: [i.url], destination: o.archive.deletingLastPathComponent().appendingPathComponent(name))
                job.deleteSources = o.deleteSources
                queue.enqueue(job)
            }
        } else {
            var job = TransferJob(kind: .pack, sources: items.map(\.url), destination: o.archive)
            job.deleteSources = o.deleteSources
            queue.enqueue(job)
        }
        active.clearMarksAfterOperation()
    }

    /// Gli archivi selezionati, o quello sotto il cursore.
    private func selectedArchives() -> [URL] {
        active.selectedItems().filter { !$0.showsAsFolder && ArchivePath.isArchiveName($0.name) }.map(\.url)
    }

    private func unpack() {
        let archives = selectedArchives()
        guard !archives.isEmpty, !active.isRemote, !other.isRemote else {
            active.showMessage("Metti il cursore su un archivio (zip, rar, 7z…) o selezionane qualcuno")
            NSSound.beep()
            return
        }
        let targetDir = other.mode == .normal ? other.currentURL : active.currentURL
        guard let o = UnpackDialog.run(archives: archives, targetDir: targetDir) else { return }
        var job = TransferJob(kind: .extract, sources: archives, destination: o.destination, fileMask: o.mask,
                              policy: o.overwrite ? .overwriteAll : .ask)
        job.withPaths = o.withPaths
        job.extractToSubfolder = o.subfolders
        queue.enqueue(job)
        active.clearMarksAfterOperation()
    }

    private func testArchives() {
        let archives = selectedArchives()
        guard !archives.isEmpty else { NSSound.beep(); return }
        active.showMessage("Controllo \(archives.count == 1 ? archives[0].lastPathComponent : "\(archives.count) archivi")…")
        DispatchQueue.global(qos: .userInitiated).async {
            let errors = archives.compactMap { a in ArchiveReader.test(a).map { "\(a.lastPathComponent): \($0)" } }
            DispatchQueue.main.async { [weak self] in
                self?.active.updateStatus()
                if errors.isEmpty {
                    Dialogs.message(archives.count == 1 ? "L'archivio è integro" : "Gli archivi sono integri",
                                    info: archives.map(\.lastPathComponent).joined(separator: "\n"))
                } else {
                    Dialogs.message("Ci sono errori", info: errors.joined(separator: "\n"), style: .warning)
                }
            }
        }
    }

    private func openInEditor(_ url: URL) {
        NSWorkspace.shared.open([url], withApplicationAt: Settings.shared.editorURL, configuration: NSWorkspace.OpenConfiguration())
    }

    // MARK: - Copia, sposta, crea, elimina

    private func describe(_ items: [FileItem]) -> String {
        if items.count == 1 { return "\"\(items[0].name)\"" }
        let folders = items.filter(\.showsAsFolder).count
        let files = items.count - folders
        var parts: [String] = []
        if files > 0 { parts.append(files == 1 ? "1 file" : "\(files) file") }
        if folders > 0 { parts.append(folders == 1 ? "1 cartella" : "\(folders) cartelle") }
        return parts.joined(separator: " e ")
    }

    private func copyOrMove(_ kind: TransferKind) {
        let items = active.selectedItems()
        guard !items.isEmpty else { return }
        // Come TC: "cartella/*.*". Con F5 su un solo file si può scrivere il nuovo nome al posto di "*.*".
        let initial = Format.path(other.currentURL).replacingOccurrences(of: "//", with: "/") + (other.currentURL.path == "/" ? "*.*" : "/*.*")
        guard let opts = CopyDialog.run(kind: kind, items: items, target: initial),
              let dest = parseDestination(opts.target, count: items.count) else { return }
        queue.enqueue(TransferJob(kind: kind, sources: items.map(\.url), destination: dest.dir, newName: dest.name,
                                  renamePattern: dest.pattern, fileMask: opts.mask, verify: opts.verify, policy: opts.policy))
        active.clearMarksAfterOperation()
    }

    /// "~/x/*.*" o "~/x/" o una cartella esistente = destinazione; "~/x/*.bak" = maschera di rinomina;
    /// "~/x/nome.txt" con un solo elemento = nuovo nome.
    private func parseDestination(_ raw: String, count: Int) -> (dir: URL, name: String?, pattern: String?)? {
        var text = (raw.trimmingCharacters(in: .whitespaces) as NSString).expandingTildeInPath
        guard !text.isEmpty else { return nil }
        if !text.hasPrefix("/") { text = active.currentURL.path + "/" + text }
        var isDir: ObjCBool = false
        if text.hasSuffix("/") || (FileManager.default.fileExists(atPath: text, isDirectory: &isDir) && isDir.boolValue) {
            return (URL(fileURLWithPath: text, isDirectory: true), nil, nil)
        }
        let u = URL(fileURLWithPath: text)
        let last = u.lastPathComponent
        if last.contains("*") || last.contains("?") {
            return (u.deletingLastPathComponent(), nil, last == "*.*" || last == "*" ? nil : last)
        }
        if count > 1 { return (URL(fileURLWithPath: text, isDirectory: true), nil, nil) }
        return (u.deletingLastPathComponent(), last, nil)
    }

    private func copySameDir() {
        guard let item = active.cursorItem, !item.isParent else { return }
        let base = item.baseName as NSString
        var value = item.name
        while true {
            guard case .ok(let raw) = Dialogs.prompt("Copia \"\(item.name)\" con il nome:", value: value,
                                                     selection: NSRange(location: 0, length: base.length)) else { return }
            let name = raw.trimmingCharacters(in: .whitespaces)
            guard !name.isEmpty else { return }
            // Stesso nome (anche con maiuscole diverse: sul Mac è lo stesso file): come TC, avvisa e si riprova.
            if name.caseInsensitiveCompare(item.name) == .orderedSame {
                Dialogs.message("Non si può copiare un file su se stesso", info: "Scrivi un nome diverso.", style: .warning)
                value = name
                continue
            }
            queue.enqueue(TransferJob(kind: .copy, sources: [item.url], destination: active.currentURL, newName: name))
            return
        }
    }

    private func makeDirectory() {
        let suggestion = active.cursorItem.map { $0.isParent ? "" : ($0.showsAsFolder ? $0.name : $0.baseName) } ?? ""
        guard case .ok(let raw) = Dialogs.prompt("Nuova cartella:", value: suggestion) else { return }
        let name = raw.trimmingCharacters(in: .whitespaces)
        guard !name.isEmpty else { return }
        if active.isRemote { remoteMakeDirectory(name: name); return }
        let url = active.currentURL.appendingPathComponent(name)
        do {
            try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
            active.tab.cursorName = name.split(separator: "/").first.map(String.init)
            active.refresh()
        } catch {
            Dialogs.message("Non riesco a creare la cartella", info: error.localizedDescription, style: .warning)
        }
    }

    private func newTextFile() {
        guard case .ok(let raw) = Dialogs.prompt("Nuovo file di testo:", value: "testo.txt",
                                                 selection: NSRange(location: 0, length: 5)) else { return }
        let name = raw.trimmingCharacters(in: .whitespaces)
        guard !name.isEmpty else { return }
        let url = active.currentURL.appendingPathComponent(name)
        if !FileManager.default.fileExists(atPath: url.path) {
            guard FileManager.default.createFile(atPath: url.path, contents: Data()) else {
                Dialogs.message("Non riesco a creare \"\(name)\"", style: .warning)
                return
            }
        }
        active.tab.cursorName = name
        active.refresh()
        openInEditor(url)
    }

    private func delete(permanent: Bool) {
        let items = active.selectedItems()
        guard !items.isEmpty else { return }
        if Settings.shared.confirmDelete {
            let ok = permanent
                ? Dialogs.confirm("Eliminare definitivamente \(describe(items))?", info: "Non finiscono nel Cestino.", ok: "Elimina")
                : Dialogs.confirm("Spostare nel Cestino \(describe(items))?", ok: "Sposta nel Cestino")
            guard ok else { return }
        }
        // Il cursore va sul primo elemento che resta.
        let gone = Set(items.map(\.url))
        if let next = active.items[active.cursorRow...].first(where: { !gone.contains($0.url) })
            ?? active.items[..<active.cursorRow].last(where: { !gone.contains($0.url) }) {
            active.tab.cursorName = next.name
        }
        queue.enqueue(TransferJob(kind: permanent ? .delete : .trash, sources: items.map(\.url)))
        active.clearMarksAfterOperation()
    }

    private func calcSize() {
        let items = active.selectedItems()
        guard !items.isEmpty else { return }
        var bytes: Int64 = 0, files = 0, folders = 0, remaining = items.count
        for i in items {
            active.computeSize(i.url) { b, f, d in
                bytes += b
                files += f
                folders += d + (i.showsAsFolder ? 1 : 0)
                remaining -= 1
                if remaining == 0 {
                    Dialogs.message("Spazio occupato: \(Format.short(bytes))",
                                    info: "\(Format.bytes(bytes)) byte in \(files) file e \(folders) cartelle")
                }
            }
        }
    }

    // MARK: - Appunti (compatibili col Finder)

    private func clipboard(cut: Bool) {
        let items = active.selectedItems()
        guard !items.isEmpty else { return }
        let pb = NSPasteboard.general
        pb.clearContents()
        pb.writeObjects(items.map { $0.url as NSURL })
        cutChangeCount = cut ? pb.changeCount : nil
    }

    private func paste() {
        let pb = NSPasteboard.general
        guard let urls = pb.readObjects(forClasses: [NSURL.self], options: [.urlReadingFileURLsOnly: true]) as? [URL],
              !urls.isEmpty else { return }
        if active.isRemote { remotePaste(urls); return }
        let move = cutChangeCount == pb.changeCount
        queue.enqueue(TransferJob(kind: move ? .move : .copy, sources: urls, destination: active.currentURL))
        if move { cutChangeCount = nil }
    }

    // MARK: - Selezione con maschera

    private var lastMask = "*.*"

    private func selectByMask(on: Bool) {
        guard case .ok(let mask) = Dialogs.prompt(on ? "Seleziona i file:" : "Deseleziona i file:", value: lastMask),
              !mask.isEmpty else { return }
        lastMask = mask
        active.setMarks(where: { Matcher.matches($0.name, mask: mask) }, on: on)
    }

    // MARK: - Menu: preferiti, posizioni, cronologia, schede

    private func popUp(_ menu: NSMenu, in panel: FilePanel, at anchor: NSView? = nil) {
        menuOpen = true
        defer { menuOpen = false }
        if let anchor {
            menu.popUp(positioning: nil, at: NSPoint(x: 0, y: anchor.bounds.maxY + 4), in: anchor)
            return
        }
        let row = max(panel.cursorRow, 0)
        let r = panel.table.rect(ofRow: row)
        menu.popUp(positioning: nil, at: NSPoint(x: r.minX + 30, y: r.maxY), in: panel.table)
    }

    /// Ctrl+D: si apre sempre in alto a sinistra nell'elenco del pannello attivo, come in TC.
    private func showHotlist() {
        var items = hotlistItems(hotlist)
        items.append(.separator)
        let here = active.currentURL
        items.append(KeyMenu.Item("&Aggiungi «\(Mnemonic.escaped(here.lastPathComponent))» ai preferiti…") { [weak self] in self?.addToHotlist(here) })
        items.append(KeyMenu.Item("Modifica i preferi&ti…") { [weak self] in self?.editHotlist() })

        let table = active.table
        let visible = table.convert(table.visibleRect, to: nil)
        guard let win = table.window else { return }
        let r = win.convertToScreen(visible)
        keyMenu.show(items, topLeft: NSPoint(x: r.minX + 4, y: r.maxY - 2))
    }

    private func hotlistItems(_ entries: [HotlistEntry]) -> [KeyMenu.Item] {
        entries.compactMap { e in
            if e.isSeparator { return .separator }
            if let items = e.items { return KeyMenu.Item(e.name ?? "", submenu: hotlistItems(items)) }
            guard let url = e.url else { return nil }
            return KeyMenu.Item(e.name ?? "", toolTip: Format.path(url)) { [weak self] in
                self?.active.navigate(to: url)
            }
        }
    }

    private func addToHotlist(_ url: URL) {
        guard case .ok(let name) = Dialogs.prompt("Nome del preferito:", info: Format.path(url), value: Mnemonic.escaped(url.lastPathComponent)),
              !name.isEmpty else { return }
        hotlist.append(HotlistEntry(name: name, path: HotlistStore.storedPath(url)))
        do { try HotlistStore.save(hotlist) } catch {
            Dialogs.message("Non riesco a salvare i preferiti", info: error.localizedDescription, style: .warning)
        }
    }

    private func editHotlist() {
        let file = HotlistStore.defaultURL
        if !FileManager.default.fileExists(atPath: file.path) { try? HotlistStore.save(hotlist) }
        openInEditor(file)
    }

    func reloadHotlist() { hotlist = HotlistStore.load() }

    private func showLocations(for panel: FilePanel) {
        setActive(panel)
        let menu = NSMenu()
        let home = FileManager.default.homeDirectoryForCurrentUser
        let places: [(String, URL)] = [
            ("Home", home),
            ("Scrivania", home.appendingPathComponent("Desktop")),
            ("Download", home.appendingPathComponent("Downloads")),
            ("Documenti", home.appendingPathComponent("Documents")),
            ("iCloud Drive", home.appendingPathComponent("Library/Mobile Documents/com~apple~CloudDocs")),
            ("Applicazioni", URL(fileURLWithPath: "/Applications")),
        ]
        for (title, url) in places where FileManager.default.fileExists(atPath: url.path) {
            menu.addItem(ActionMenuItem(title) { panel.navigate(to: url) })
        }
        menu.addItem(.separator())
        let vols = FileManager.default.mountedVolumeURLs(includingResourceValuesForKeys: [.volumeLocalizedNameKey],
                                                         options: [.skipHiddenVolumes]) ?? []
        for v in vols {
            let name = (try? v.resourceValues(forKeys: [.volumeLocalizedNameKey]))?.volumeLocalizedName ?? v.lastPathComponent
            let item = ActionMenuItem(v.path == "/" ? "\(name)  /" : "\(name)  \(Format.path(v))") { panel.navigate(to: v) }
            item.image = NSWorkspace.shared.icon(forFile: v.path)
            item.image?.size = NSSize(width: 16, height: 16)
            menu.addItem(item)
        }
        popUp(menu, in: panel, at: panel.locationAnchor)
    }

    private func showHistory() {
        let p = active
        let menu = NSMenu()
        for (i, u) in p.tab.history.enumerated().reversed() {
            let item = ActionMenuItem(Format.path(u)) { p.historyJump(i) }
            item.state = i == p.tab.historyIndex ? .on : .off
            menu.addItem(item)
        }
        popUp(menu, in: p)
    }

    private func showTabList() {
        let p = active
        let menu = NSMenu()
        for (i, t) in p.tabs.enumerated() {
            let item = ActionMenuItem(Format.path(t.url)) { p.switchTab(i) }
            item.state = i == p.activeTabIndex ? .on : .off
            menu.addItem(item)
        }
        popUp(menu, in: p)
    }

    // MARK: - Stato

    func saveState() {
        AppState(left: PanelState(left), right: PanelState(right), rightActive: active === right).save()
    }

    func windowWillClose(_ notification: Notification) { saveState() }
}

// MARK: - Stato salvato tra un avvio e l'altro

struct PanelState: Codable {
    var tabs: [String]
    var sorts: [FileSort]
    var active: Int

    init(tabs: [String], active: Int) {
        self.tabs = tabs
        self.sorts = tabs.map { _ in FileSort() }
        self.active = active
    }

    init(_ p: FilePanel) {
        // Le schede su un server FTP non si riaprono al riavvio: si torna all'ultima cartella del Mac.
        let local = p.tabs.map { t in t.url.isFileURL ? t.url : (t.history.last(where: \.isFileURL) ?? FileManager.default.homeDirectoryForCurrentUser) }
        tabs = local.map(\.path)
        sorts = p.tabs.map(\.sort)
        active = p.activeTabIndex
    }

    func makeTabs() -> [PanelTab] {
        tabs.enumerated().map { i, path in
            PanelTab(url: URL(fileURLWithPath: path, isDirectory: true), sort: sorts.indices.contains(i) ? sorts[i] : FileSort())
        }
    }
}

struct AppState: Codable {
    var left: PanelState
    var right: PanelState
    var rightActive: Bool

    private static let key = "statoPannelli"

    static func load() -> AppState {
        if Settings.shared.restorePanels, let data = UserDefaults.standard.data(forKey: key),
           let s = try? JSONDecoder().decode(AppState.self, from: data) {
            return s
        }
        // Primo avvio: la cartella Inizio a sinistra, Download a destra.
        let home = FileManager.default.homeDirectoryForCurrentUser
        let downloads = home.appendingPathComponent("Downloads")
        return AppState(left: PanelState(tabs: [home.path], active: 0),
                        right: PanelState(tabs: [FileManager.default.fileExists(atPath: downloads.path) ? downloads.path : home.path], active: 0),
                        rightActive: false)
    }

    func save() {
        if let data = try? JSONEncoder().encode(self) { UserDefaults.standard.set(data, forKey: Self.key) }
    }
}

// MARK: - F3: anteprima come la barra spaziatrice del Finder

extension MainWindowController: QLPreviewPanelDataSource, QLPreviewPanelDelegate {
    private var quickLookOpen: Bool { QLPreviewPanel.sharedPreviewPanelExists() && QLPreviewPanel.shared().isVisible }

    func toggleQuickLook() {
        if quickLookOpen {
            QLPreviewPanel.shared().orderOut(nil)
            return
        }
        guard active.cursorItem != nil else { return }
        // Il pannello non prende la tastiera: le frecce restano all'elenco e l'anteprima segue il cursore.
        let ql = QLPreviewPanel.shared()!
        ql.updateController()
        ql.orderFront(nil)
        ql.reloadData()
    }

    func refreshQuickLook() {
        guard quickLookOpen else { return }
        QLPreviewPanel.shared().reloadData()
    }

    /// Esc chiude l'anteprima.
    func closeQuickLook() -> Bool {
        guard quickLookOpen else { return false }
        QLPreviewPanel.shared().orderOut(nil)
        return true
    }

    override func acceptsPreviewPanelControl(_ panel: QLPreviewPanel!) -> Bool { true }

    override func beginPreviewPanelControl(_ panel: QLPreviewPanel!) {
        panel.dataSource = self
        panel.delegate = self
    }

    override func endPreviewPanelControl(_ panel: QLPreviewPanel!) {
        panel.dataSource = nil
        panel.delegate = nil
    }

    func numberOfPreviewItems(in panel: QLPreviewPanel!) -> Int {
        guard let i = active.cursorItem, i.url.isFileURL else { return 0 }
        return 1
    }

    func previewPanel(_ panel: QLPreviewPanel!, previewItemAt index: Int) -> QLPreviewItem! {
        guard let i = active.cursorItem else { return nil }
        if ArchivePath.isInside(i.url) {
            // Dentro un archivio: si estrae il file (le cartelle non hanno anteprima).
            guard !i.showsAsFolder, let tmp = try? ArchiveReader.extractToTemp(i.url) else { return nil }
            return tmp as NSURL
        }
        return (i.isParent ? active.currentURL : i.url) as NSURL
    }

    /// Se il pannello d'anteprima ha la tastiera (clic sopra), i tasti tornano all'elenco.
    func previewPanel(_ panel: QLPreviewPanel!, handle event: NSEvent!) -> Bool {
        guard event.type == .keyDown else { return false }
        window?.makeKeyAndOrderFront(nil)
        return handleKeyEvent(event) == nil
    }
}

