import Foundation

extension Notification.Name {
    /// Posted when `statusBarAppIDsData` changes so extra menu bar icons can refresh.
    static let statusBarShortcutIDsChanged = Notification.Name("google_apps.statusBarShortcutIDsChanged")
}

struct LauncherApp: Identifiable, Hashable {
    let id: UUID
    let name: String
    let assetIconName: String
    let fallbackSymbolName: String
    let description: String
    let isCreateNew: Bool
    let webURL: URL?

    init(
        id: UUID = UUID(),
        name: String,
        assetIconName: String,
        fallbackSymbolName: String,
        description: String,
        isCreateNew: Bool,
        webURL: URL?
    ) {
        self.id = id
        self.name = name
        self.assetIconName = assetIconName
        self.fallbackSymbolName = fallbackSymbolName
        self.description = description
        self.isCreateNew = isCreateNew
        self.webURL = webURL
    }
}

struct PersistedCustomApp: Codable {
    let id: UUID
    let name: String
    let urlString: String
}

extension LauncherApp {
    static let createNewTile = LauncherApp(
        id: UUID(uuidString: "AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA")!,
        name: "Create New App",
        assetIconName: "icon_create_new_app",
        fallbackSymbolName: "plus",
        description: "Create and add a custom app shortcut.",
        isCreateNew: true,
        webURL: nil
    )

    static let sampleApps: [LauncherApp] = [
        LauncherApp(id: UUID(uuidString: "F0000000-0000-0000-0000-000000000001")!, name: "Google Shopping", assetIconName: "icon_google_shopping", fallbackSymbolName: "bag.fill", description: "Explore products and offers.", isCreateNew: false, webURL: URL(string: "https://shopping.google.com")),
        LauncherApp(id: UUID(uuidString: "F0000000-0000-0000-0000-000000000002")!, name: "Gmail", assetIconName: "icon_gmail", fallbackSymbolName: "envelope.fill", description: "Read and send emails quickly.", isCreateNew: false, webURL: URL(string: "https://mail.google.com")),
        LauncherApp(id: UUID(uuidString: "F0000000-0000-0000-0000-000000000003")!, name: "Google Docs", assetIconName: "icon_google_docs", fallbackSymbolName: "doc.text.fill", description: "Create and edit documents.", isCreateNew: false, webURL: URL(string: "https://docs.google.com")),
        LauncherApp(id: UUID(uuidString: "F0000000-0000-0000-0000-000000000004")!, name: "Google Drive", assetIconName: "icon_google_drive", fallbackSymbolName: "externaldrive.fill", description: "Store and sync your files.", isCreateNew: false, webURL: URL(string: "https://drive.google.com")),
        LauncherApp(id: UUID(uuidString: "F0000000-0000-0000-0000-000000000005")!, name: "Google Earth", assetIconName: "icon_google_earth", fallbackSymbolName: "globe.americas.fill", description: "Explore places worldwide.", isCreateNew: false, webURL: URL(string: "https://earth.google.com")),
        LauncherApp(id: UUID(uuidString: "F0000000-0000-0000-0000-000000000006")!, name: "Google Photos", assetIconName: "icon_google_photos", fallbackSymbolName: "photo.stack.fill", description: "View and organize photos.", isCreateNew: false, webURL: URL(string: "https://photos.google.com")),
        LauncherApp(id: UUID(uuidString: "F0000000-0000-0000-0000-000000000007")!, name: "Google Maps", assetIconName: "icon_google_maps", fallbackSymbolName: "map.fill", description: "Find routes and places.", isCreateNew: false, webURL: URL(string: "https://maps.google.com")),
        LauncherApp(id: UUID(uuidString: "F0000000-0000-0000-0000-000000000008")!, name: "Google Translate", assetIconName: "icon_google_translate", fallbackSymbolName: "character.bubble.fill", description: "Translate text and speech.", isCreateNew: false, webURL: URL(string: "https://translate.google.com")),
        LauncherApp(id: UUID(uuidString: "F0000000-0000-0000-0000-000000000009")!, name: "Google Sheets", assetIconName: "icon_google_sheets", fallbackSymbolName: "tablecells.fill", description: "Work with spreadsheets.", isCreateNew: false, webURL: URL(string: "https://sheets.google.com")),
        LauncherApp(id: UUID(uuidString: "F0000000-0000-0000-0000-000000000010")!, name: "Google Search", assetIconName: "icon_google_search", fallbackSymbolName: "magnifyingglass.circle.fill", description: "Search the web quickly.", isCreateNew: false, webURL: URL(string: "https://www.google.com")),
        LauncherApp(id: UUID(uuidString: "F0000000-0000-0000-0000-000000000011")!, name: "YouTube", assetIconName: "icon_youtube", fallbackSymbolName: "play.rectangle.fill", description: "Watch videos and channels.", isCreateNew: false, webURL: URL(string: "https://www.youtube.com")),
        LauncherApp(id: UUID(uuidString: "F0000000-0000-0000-0000-000000000012")!, name: "Google Calendar", assetIconName: "icon_google_calendar", fallbackSymbolName: "calendar", description: "Manage events and schedules.", isCreateNew: false, webURL: URL(string: "https://calendar.google.com")),
        LauncherApp(id: UUID(uuidString: "F0000000-0000-0000-0000-000000000013")!, name: "Google Keep", assetIconName: "icon_google_keep", fallbackSymbolName: "lightbulb.fill", description: "Capture notes and reminders.", isCreateNew: false, webURL: URL(string: "https://keep.google.com")),
        LauncherApp(id: UUID(uuidString: "F0000000-0000-0000-0000-000000000014")!, name: "Google Slides", assetIconName: "icon_google_slides", fallbackSymbolName: "rectangle.on.rectangle.fill", description: "Build and present slides.", isCreateNew: false, webURL: URL(string: "https://slides.google.com")),
        LauncherApp(id: UUID(uuidString: "F0000000-0000-0000-0000-000000000015")!, name: "Google Forms", assetIconName: "icon_google_forms", fallbackSymbolName: "list.bullet.rectangle.fill", description: "Create forms and surveys.", isCreateNew: false, webURL: URL(string: "https://forms.google.com")),
        LauncherApp(id: UUID(uuidString: "F0000000-0000-0000-0000-000000000016")!, name: "Google Books", assetIconName: "icon_google_books", fallbackSymbolName: "book.fill", description: "Browse and read books.", isCreateNew: false, webURL: URL(string: "https://books.google.com")),
        LauncherApp(id: UUID(uuidString: "F0000000-0000-0000-0000-000000000017")!, name: "Google Travel", assetIconName: "icon_google_travel", fallbackSymbolName: "airplane", description: "Plan and organize trips.", isCreateNew: false, webURL: URL(string: "https://travel.google.com")),
        LauncherApp(id: UUID(uuidString: "F0000000-0000-0000-0000-000000000018")!, name: "Google Meet", assetIconName: "icon_google_meet", fallbackSymbolName: "video.fill", description: "Start and join video meetings.", isCreateNew: false, webURL: URL(string: "https://meet.google.com")),
        LauncherApp(id: UUID(uuidString: "F0000000-0000-0000-0000-000000000019")!, name: "Google Contacts", assetIconName: "icon_google_contacts", fallbackSymbolName: "person.crop.circle.fill", description: "Manage your contacts.", isCreateNew: false, webURL: URL(string: "https://contacts.google.com")),
        LauncherApp(id: UUID(uuidString: "F0000000-0000-0000-0000-00000000001A")!, name: "Google Blogger", assetIconName: "icon_google_blogger", fallbackSymbolName: "text.book.closed.fill", description: "Publish and read blogs.", isCreateNew: false, webURL: URL(string: "https://www.blogger.com")),
        LauncherApp(id: UUID(uuidString: "F0000000-0000-0000-0000-00000000001B")!, name: "Google Play", assetIconName: "icon_google_play", fallbackSymbolName: "play.circle.fill", description: "Apps, games, movies, and books.", isCreateNew: false, webURL: URL(string: "https://play.google.com")),
        LauncherApp(id: UUID(uuidString: "F0000000-0000-0000-0000-00000000001C")!, name: "Google News", assetIconName: "icon_google_news", fallbackSymbolName: "newspaper.fill", description: "Headlines tailored to you.", isCreateNew: false, webURL: URL(string: "https://news.google.com")),
        LauncherApp(id: UUID(uuidString: "F0000000-0000-0000-0000-00000000001D")!, name: "Google Chat", assetIconName: "icon_google_chat", fallbackSymbolName: "bubble.left.and.bubble.right.fill", description: "Team messaging and spaces.", isCreateNew: false, webURL: URL(string: "https://chat.google.com")),
        LauncherApp(id: UUID(uuidString: "F0000000-0000-0000-0000-00000000001E")!, name: "Google Finance", assetIconName: "icon_google_finance", fallbackSymbolName: "chart.line.uptrend.xyaxis", description: "Markets, news, and portfolios.", isCreateNew: false, webURL: URL(string: "https://www.google.com/finance")),
        LauncherApp(id: UUID(uuidString: "F0000000-0000-0000-0000-00000000001F")!, name: "Google Jamboard", assetIconName: "icon_google_jamboard", fallbackSymbolName: "paintbrush.fill", description: "Collaborative whiteboards.", isCreateNew: false, webURL: URL(string: "https://jamboard.google.com")),
        LauncherApp(id: UUID(uuidString: "F0000000-0000-0000-0000-000000000020")!, name: "Google Classroom", assetIconName: "icon_google_classroom", fallbackSymbolName: "graduationcap.fill", description: "Teaching and learning hub.", isCreateNew: false, webURL: URL(string: "https://classroom.google.com")),
        LauncherApp(id: UUID(uuidString: "F0000000-0000-0000-0000-000000000021")!, name: "Google Arts & Culture", assetIconName: "icon_google_arts_culture", fallbackSymbolName: "building.columns.fill", description: "Museums, art, and history.", isCreateNew: false, webURL: URL(string: "https://artsandculture.google.com")),
        LauncherApp(id: UUID(uuidString: "F0000000-0000-0000-0000-000000000022")!, name: "Google Voice", assetIconName: "icon_google_voice", fallbackSymbolName: "phone.fill", description: "Calls, voicemail, and SMS.", isCreateNew: false, webURL: URL(string: "https://voice.google.com")),
        LauncherApp(id: UUID(uuidString: "F0000000-0000-0000-0000-000000000023")!, name: "Chrome Web Store", assetIconName: "icon_chrome_web_store", fallbackSymbolName: "bag.fill", description: "Extensions and themes for Chrome.", isCreateNew: false, webURL: URL(string: "https://chrome.google.com/webstore")),
        LauncherApp(id: UUID(uuidString: "F0000000-0000-0000-0000-000000000024")!, name: "Google Fi Wireless", assetIconName: "icon_google_fi", fallbackSymbolName: "antenna.radiowaves.left.and.right", description: "Phone plan and account.", isCreateNew: false, webURL: URL(string: "https://fi.google.com")),
        LauncherApp(id: UUID(uuidString: "F0000000-0000-0000-0000-000000000025")!, name: "Google Ads", assetIconName: "icon_google_ads", fallbackSymbolName: "megaphone.fill", description: "Advertising campaigns.", isCreateNew: false, webURL: URL(string: "https://ads.google.com")),
        LauncherApp(id: UUID(uuidString: "F0000000-0000-0000-0000-000000000026")!, name: "Chrome Remote Desktop", assetIconName: "icon_chrome_remote_desktop", fallbackSymbolName: "desktopcomputer", description: "Access computers remotely.", isCreateNew: false, webURL: URL(string: "https://remotedesktop.google.com")),
        LauncherApp(id: UUID(uuidString: "F0000000-0000-0000-0000-000000000027")!, name: "Gemini", assetIconName: "icon_gemini", fallbackSymbolName: "sparkles", description: "Google AI assistant.", isCreateNew: false, webURL: URL(string: "https://gemini.google.com")),
    ]

    static func customAppsFromStorageJSON(_ json: String) -> [LauncherApp] {
        guard !json.isEmpty, let data = json.data(using: .utf8) else { return [] }
        do {
            let persisted = try JSONDecoder().decode([PersistedCustomApp].self, from: data)
            return persisted.compactMap { item in
                guard let parsedURL = URL(string: item.urlString) else { return nil }
                return LauncherApp(
                    id: item.id,
                    name: item.name,
                    assetIconName: "",
                    fallbackSymbolName: "globe",
                    description: "Custom app shortcut.",
                    isCreateNew: false,
                    webURL: parsedURL
                )
            }
        } catch {
            return []
        }
    }

    static func allLaunchableAppsFromUserDefaults() -> [LauncherApp] {
        let customJSON = UserDefaults.standard.string(forKey: "customLauncherAppsData") ?? ""
        return sampleApps + customAppsFromStorageJSON(customJSON)
    }

    static func statusBarShortcutIDSet() -> Set<UUID> {
        let raw = UserDefaults.standard.string(forKey: "statusBarAppIDsData") ?? ""
        guard !raw.isEmpty, let data = raw.data(using: .utf8) else { return [] }
        do {
            let strings = try JSONDecoder().decode([String].self, from: data)
            return Set(strings.compactMap(UUID.init(uuidString:)))
        } catch {
            return []
        }
    }

    static func statusBarShortcutsOrdered() -> [LauncherApp] {
        let ids = statusBarShortcutIDSet()
        return allLaunchableAppsFromUserDefaults()
            .filter { ids.contains($0.id) }
            .sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending }
    }

    /// Writes `statusBarAppIDsData` in the same JSON format as SwiftUI `@AppStorage`.
    static func persistStatusBarShortcutIDs(_ ids: Set<UUID>) {
        do {
            let strings = ids.map(\.uuidString).sorted()
            let data = try JSONEncoder().encode(strings)
            UserDefaults.standard.set(String(decoding: data, as: UTF8.self), forKey: "statusBarAppIDsData")
            LauncherApp.notifyStatusBarShortcutIdentifiersChanged()
        } catch {
            // Ignore persistence failures; menu bar state may be slightly stale until next change.
        }
    }

    static func notifyStatusBarShortcutIdentifiersChanged() {
        DispatchQueue.main.async {
            NotificationCenter.default.post(name: .statusBarShortcutIDsChanged, object: nil)
        }
    }
}
