import AppKit

extension AppDelegate {

    func setupStatusBar() {
        statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
        if let button = statusItem.button {
            let minutes = workTimerDuration / 60
            let seconds = workTimerDuration % 60
            button.title = String(format: "🍅 %02d:%02d", minutes, seconds)
            button.font = NSFont.monospacedSystemFont(ofSize: 12, weight: .medium)
        }

        let menu = NSMenu()
        statusMenuItem = NSMenuItem(title: "Pommedoro: Running", action: nil, keyEquivalent: "")
        statusMenuItem.isEnabled = false
        menu.addItem(statusMenuItem)
        menu.addItem(NSMenuItem.separator())
        pauseMenuItem = NSMenuItem(title: "Pause", action: #selector(togglePause), keyEquivalent: "p")
        menu.addItem(pauseMenuItem)
        menu.addItem(NSMenuItem(title: "Restart Timer", action: #selector(restartTimer), keyEquivalent: "r"))
        menu.addItem(NSMenuItem.separator())

        // Settings submenu with inline sliders and color picker
        settingsMenuBuilder = SettingsMenuBuilder()
        menu.addItem(settingsMenuBuilder.buildSettingsSubmenu())

        menu.addItem(NSMenuItem.separator())
        menu.addItem(NSMenuItem(title: "View Work Log", action: #selector(showWorkLog), keyEquivalent: "w"))
        menu.addItem(NSMenuItem.separator())
        debugMenuItem = NSMenuItem(title: "Debug Mode", action: #selector(toggleDebugMode), keyEquivalent: "d")
        debugMenuItem.state = isDebugMode ? .on : .off
        menu.addItem(debugMenuItem)
        menu.addItem(NSMenuItem.separator())
        launchAtLoginMenuItem = NSMenuItem(title: "Launch at Login", action: #selector(toggleLaunchAtLogin), keyEquivalent: "l")
        launchAtLoginMenuItem.state = LaunchAgent.isInstalled() ? .on : .off
        menu.addItem(launchAtLoginMenuItem)
        menu.addItem(NSMenuItem.separator())
        menu.addItem(NSMenuItem(title: "Check for Updates…", action: #selector(checkForUpdates), keyEquivalent: "u"))
        menu.addItem(NSMenuItem(title: "Quit Pommedoro", action: #selector(closePommedoro), keyEquivalent: "q"))

        for item in menu.items {
            if item.target == nil && item.action != nil {
                item.target = self
            }
        }

        statusItem.menu = menu
    }

    func updateStatusBar() {
        let minutes = remainingSeconds / 60
        let seconds = remainingSeconds % 60
        let time = String(format: "%02d:%02d", minutes, seconds)
        let prefix = isPaused ? "⏸" : "🍅"
        statusItem.button?.title = "\(prefix) \(time)"
        statusMenuItem.title = isPaused ? "Pommedoro: Paused" : "Pommedoro: Running"
        pauseMenuItem.title = isPaused ? "Resume" : "Pause"
    }
}
