//
//  AppDelegate.swift
//  google_apps
//
//  Created by Dev Mac 1 on 27/03/2026.
//

import Cocoa

@main
class AppDelegate: NSObject, NSApplicationDelegate {
    private var statusItem: NSStatusItem?

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        applyBundledAppIcon()
        configureMainWindowIfNeeded()
        setupStatusBarItem()
        StatusBarAppIconsController.shared.start()
    }

    private func applyBundledAppIcon() {
        if let assetAppIcon = NSImage(named: "AppIcon") {
            NSApp.applicationIconImage = assetAppIcon
            return
        }
        if let icnsURL = Bundle.main.url(forResource: "AppIcon", withExtension: "icns"),
           let icnsIcon = NSImage(contentsOf: icnsURL) {
            NSApp.applicationIconImage = icnsIcon
        }
    }

    private func setupStatusBarItem() {
        let item = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength)
        statusItem = item

        guard let button = item.button else { return }
        if let menuBarIcon = NSImage(named: "menu_bar_icon") {
            button.image = menuBarIcon
            button.image?.isTemplate = false
        } else {
            button.image = NSImage(systemSymbolName: "square.grid.2x2.fill", accessibilityDescription: "My Apps")
            button.image?.isTemplate = true
        }
        button.imageScaling = .scaleProportionallyDown
        button.imagePosition = .imageOnly
        button.action = #selector(statusBarButtonClicked(_:))
        button.target = self
        button.sendAction(on: [.leftMouseUp, .rightMouseUp])
    }

    @objc
    private func statusBarButtonClicked(_ sender: Any?) {
        guard let event = NSApp.currentEvent else {
            openMainWindowFromStatusBar()
            return
        }
        if event.type == .rightMouseUp {
            presentStatusBarShortcutsMenu()
        } else {
            openMainWindowFromStatusBar()
        }
    }

    private func presentStatusBarShortcutsMenu() {
        guard let button = statusItem?.button else { return }

        let menu = NSMenu()
        let openItem = NSMenuItem(
            title: "Open My Apps",
            action: #selector(openMainWindowFromStatusBar),
            keyEquivalent: ""
        )
        openItem.target = self
        menu.addItem(openItem)

        menu.addItem(.separator())
        let quitItem = NSMenuItem(
            title: "Quit",
            action: #selector(terminateApp),
            keyEquivalent: "q"
        )
        quitItem.target = self
        menu.addItem(quitItem)

        let location = NSPoint(x: 0, y: button.bounds.height)
        menu.popUp(positioning: nil, at: location, in: button)
    }

    @objc
    private func terminateApp() {
        NSApp.terminate(nil)
    }

    @objc
    private func openMainWindowFromStatusBar() {
        configureMainWindowIfNeeded()
        NSApp.setActivationPolicy(.regular)
        NSApp.activate(ignoringOtherApps: true)
        if let window = NSApp.windows.first {
            window.makeKeyAndOrderFront(nil)
        }
    }

    private func configureMainWindowIfNeeded() {
        guard let window = NSApp.windows.first else { return }
        window.title = "My Apps"
        window.styleMask.remove(.titled)
        window.isOpaque = false
        window.backgroundColor = .clear
        applyRoundedCorners(to: window)
        window.titlebarAppearsTransparent = true
        window.titleVisibility = .hidden
        window.styleMask.insert(.fullSizeContentView)
        // Avoid treating SwiftUI search fields as the draggable window background (clicks/typing fail otherwise).
        window.isMovableByWindowBackground = false
        window.minSize = NSSize(width: 760, height: 520)

        let targetContentSize = NSSize(width: 980, height: 700)
        if window.contentRect(forFrameRect: window.frame).size.width < targetContentSize.width ||
            window.contentRect(forFrameRect: window.frame).size.height < targetContentSize.height {
            let currentCenter = NSPoint(x: window.frame.midX, y: window.frame.midY)
            var targetFrame = window.frameRect(forContentRect: NSRect(origin: .zero, size: targetContentSize))
            targetFrame.origin = NSPoint(
                x: currentCenter.x - (targetFrame.width / 2),
                y: currentCenter.y - (targetFrame.height / 2)
            )
            window.setFrame(targetFrame, display: true)
        }
    }

    private func applyRoundedCorners(to window: NSWindow) {
        let cornerRadius: CGFloat = 16
        window.hasShadow = true
        window.contentView?.wantsLayer = true
        window.contentView?.layer?.cornerRadius = cornerRadius
        window.contentView?.layer?.masksToBounds = true
    }

    func applicationWillTerminate(_ aNotification: Notification) {
        // Insert code here to tear down your application
    }

    func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool {
        return true
    }


}

