//
// StatusItemManager.swift
// IceGlass
//
// Copyright 2026 Rouslan Zenetl. All Rights Reserved.
//

import AppKit

final class StatusItemManager: @unchecked Sendable {
    private let logger = IceGlassLogger(
        subsystem: Bundle.main.bundleIdentifier ?? "dev.rzen.indie.IceGlass",
        category: "StatusItemManager"
    )

    static let shared = StatusItemManager()

    var statusItem: NSStatusItem?

    private init() {
        DispatchQueue.main.async { [weak self] in
            guard let self = self else {
                AppTerminator.terminate()
                return
            }
            self.setupStatusItem()
        }
    }

    private func setupStatusItem() {
        logger.debug("Initializing")
        statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
        updateIcon()
    }

    func updateIcon() {
        Task { @MainActor in
            guard let button = self.statusItem?.button else { return }

            guard let baseImage = NSImage(named: NSImage.Name("NHLShield")) else {
                button.title = "NHL"
                button.image = nil
                return
            }

            let height = button.frame.size.height > 0 ? button.frame.size.height : 22

            // Use full menu bar height; let width follow natural aspect ratio
            let srcW = baseImage.size.width
            let srcH = baseImage.size.height
            let scale = height / srcH
            let width = srcW * scale

            let resizedImage = NSImage(size: NSSize(width: width, height: height))
            resizedImage.lockFocus()
            baseImage.draw(
                in: NSRect(x: 0, y: 0, width: width, height: height),
                from: NSRect(x: 0, y: 0, width: srcW, height: srcH),
                operation: .copy,
                fraction: 1.0
            )
            resizedImage.unlockFocus()

            button.image = resizedImage
            button.imageScaling = .scaleProportionallyDown
        }
    }

    func updateStatusText(_ text: String) {
        Task { @MainActor in
            guard let button = self.statusItem?.button else { return }
            button.title = text.isEmpty ? "" : " \(text)"
        }
    }
}
