//
//  ViewController.swift
//  AI Companion for Meet
//
//  Created by Dev Mac 1 on 06/04/2026.
//

import Cocoa
import QuartzCore
import AVFoundation
import AVKit
import Speech
import WebKit
import AuthenticationServices
import StoreKit
import ScreenCaptureKit

private enum SidebarPage: Int {
    case joinMeetings = 0
    case photo = 1
    case video = 2
    case widgets = 3
    case settings = 4
    case aiCompanion = 5
}

private enum ZoomJoinMode: Int {
    case id = 0
    case url = 1
}

private enum SettingsAction: Int {
    case restore = 0
    case rateUs = 1
    case support = 2
    case moreApps = 3
    case shareApp = 4
    case upgrade = 5
    case privacyPolicy = 6
    case termsOfServices = 7
}

private struct SpeechLocaleOption {
    let identifier: String
    let displayName: String
}

private enum PremiumPlan: Int {
    case weekly = 0
    case monthly = 1
    case yearly = 2
    case lifetime = 3
}

private enum PremiumStoreProduct {
    static let weekly = "com.mqldev.meetingsapp.premium.weekly"
    static let monthly = "com.mqldev.meetingsapp.premium.monthly"
    static let yearly = "com.mqldev.meetingsapp.premium.yearly"
    static let lifetime = "com.mqldev.meetingsapp.premium.lifetime"

    static let allIDs = [weekly, monthly, yearly, lifetime]

    static func productID(for plan: PremiumPlan) -> String {
        switch plan {
        case .weekly: return weekly
        case .monthly: return monthly
        case .yearly: return yearly
        case .lifetime: return lifetime
        }
    }

    static func plan(for productID: String) -> PremiumPlan? {
        switch productID {
        case weekly: return .weekly
        case monthly: return .monthly
        case yearly: return .yearly
        case lifetime: return .lifetime
        default: return nil
        }
    }
}

@MainActor
private final class StoreKitCoordinator {
    enum PurchaseOutcome {
        case success
        case cancelled
        case pending
        case unavailable
        case alreadyOwned
        case failed(String)
    }

    private(set) var productsByID: [String: Product] = [:]
    private(set) var activeEntitlementProductIDs: Set<String> = []
    private(set) var lastProductLoadError: String?
    var onEntitlementsChanged: ((Bool) -> Void)?

    var hasPremiumAccess: Bool { !activeEntitlementProductIDs.isEmpty }
    var hasLifetimeAccess: Bool { activeEntitlementProductIDs.contains(PremiumStoreProduct.lifetime) }
    var activeNonLifetimePlan: PremiumPlan? {
        activeEntitlementProductIDs
            .compactMap { PremiumStoreProduct.plan(for: $0) }
            .filter { $0 != .lifetime }
            .max(by: { $0.rawValue < $1.rawValue })
    }

    private var transactionUpdatesTask: Task<Void, Never>?

    deinit {
        transactionUpdatesTask?.cancel()
    }

    func start() async {
        if transactionUpdatesTask == nil {
            transactionUpdatesTask = Task { [weak self] in
                await self?.observeTransactionUpdates()
            }
        }
        await refreshProducts()
        await refreshEntitlements()
    }

    func refreshProducts() async {
        do {
            let products = try await Product.products(for: PremiumStoreProduct.allIDs)
            productsByID = Dictionary(uniqueKeysWithValues: products.map { ($0.id, $0) })
            lastProductLoadError = nil
        } catch {
            productsByID = [:]
            lastProductLoadError = error.localizedDescription
        }
    }

    func refreshEntitlements() async {
        let previousHasPremiumAccess = hasPremiumAccess
        var active = Set<String>()
        for await entitlement in Transaction.currentEntitlements {
            guard case .verified(let transaction) = entitlement else { continue }
            guard PremiumStoreProduct.allIDs.contains(transaction.productID) else { continue }
            if Self.isTransactionActive(transaction) {
                active.insert(transaction.productID)
            }
        }
        // Some StoreKit test timelines can briefly report empty current entitlements
        // even though a latest verified transaction exists for a non-consumable.
        // Merge in latest transactions to keep launch access state accurate.
        for productID in PremiumStoreProduct.allIDs {
            guard let latest = await Transaction.latest(for: productID),
                  case .verified(let transaction) = latest,
                  Self.isTransactionActive(transaction) else { continue }
            active.insert(productID)
        }
        activeEntitlementProductIDs = active
        let newHasPremiumAccess = hasPremiumAccess
        if newHasPremiumAccess != previousHasPremiumAccess {
            onEntitlementsChanged?(newHasPremiumAccess)
        }
    }

    func purchase(plan: PremiumPlan) async -> PurchaseOutcome {
        let productID = PremiumStoreProduct.productID(for: plan)

        if activeEntitlementProductIDs.contains(productID) {
            return .alreadyOwned
        }

        guard let product = productsByID[productID] else {
            await refreshProducts()
            guard let refreshed = productsByID[productID] else {
                if let lastProductLoadError, !lastProductLoadError.isEmpty {
                    return .failed("Unable to load products: \(lastProductLoadError)")
                }
                let loadedIDs = productsByID.keys.sorted().joined(separator: ", ")
                let debugIDs = loadedIDs.isEmpty ? "none" : loadedIDs
                return .failed("Product ID not found in StoreKit response. Requested: \(productID). Loaded IDs: \(debugIDs)")
            }
            return await purchase(product: refreshed)
        }

        return await purchase(product: product)
    }

    func restorePurchases() async -> String {
        do {
            try await AppStore.sync()
            await refreshEntitlements()
            if hasPremiumAccess {
                return "Purchases restored successfully."
            }
            return "No previous premium purchase was found for this Apple ID."
        } catch {
            return "Restore failed: \(error.localizedDescription)"
        }
    }

    private func purchase(product: Product) async -> PurchaseOutcome {
        do {
            let result = try await product.purchase()
            switch result {
            case .success(let verificationResult):
                guard case .verified(let transaction) = verificationResult else {
                    return .failed("Purchase verification failed.")
                }
                await transaction.finish()
                await refreshEntitlements()
                return .success
            case .pending:
                return .pending
            case .userCancelled:
                return .cancelled
            @unknown default:
                return .failed("Unknown purchase state.")
            }
        } catch {
            return .failed(error.localizedDescription)
        }
    }

    private func observeTransactionUpdates() async {
        for await update in Transaction.updates {
            guard case .verified(let transaction) = update else { continue }
            if PremiumStoreProduct.allIDs.contains(transaction.productID) {
                await refreshEntitlements()
            }
            await transaction.finish()
        }
    }

    private static func isTransactionActive(_ transaction: Transaction) -> Bool {
        if transaction.revocationDate != nil { return false }
        if let expirationDate = transaction.expirationDate {
            return expirationDate > Date()
        }
        return true
    }
}

final class ViewController: NSViewController {
    private enum MeetingTranscriptStatus: String, Codable {
        case notRequested
        case processing
        case ready
        case failed
    }

    private enum MeetingNotesStatus: String, Codable {
        case notRequested
        case processing
        case ready
        case failed
    }

    private enum MeetingTranscriptSource: String, Codable {
        case meetApi
        case localAudioAppleSpeech
        case localMultiChannelAppleSpeech
    }

    private enum PaywallFooterAction {
        case manageSubscription
        case restorePurchase
        case continueWithFreePlan
        case privacyPolicy
        case support
        case termsOfServices
    }

    private struct GoogleProfileDisplay {
        let name: String
        let email: String
        let pictureURL: URL?
    }

    private struct MeetingRecordingSummary: Codable {
        let id: String
        let title: String
        let meetURLString: String
        let startedAt: Date
        let endedAt: Date
        let audioFilePath: String
        /// Google account email that was signed in when this recording was saved.
        /// Used to scope AI Companion history per-account.
        var accountEmail: String?
        var microphoneAudioFilePath: String?
        var systemAudioFilePath: String?
        var transcriptStatusRaw: String?
        var transcriptSourceRaw: String?
        var transcriptText: String?
        var transcriptSegmentsJSON: String?
        var transcriptErrorMessage: String?
        var notesStatusRaw: String?
        var notesText: String?
        var notesErrorMessage: String?
    }

    private struct ActiveMeetingRecordingSession {
        let id: String
        let title: String
        let meetURL: URL
        let startedAt: Date
        let systemAudioFileURL: URL
        let microphoneAudioFileURL: URL
    }

    private var palette = Palette(isDarkMode: true)
    private let typography = Typography()
    private let launchContentSize = NSSize(width: 920, height: 690)
    private let launchMinContentSize = NSSize(width: 760, height: 600)
    private let launchSplashMinimumVisibleDuration: TimeInterval = 2
    private let launchSplashTimeout: TimeInterval = 12
    private var launchSplashView: LaunchSplashView?
    private var launchSplashTimeoutWorkItem: DispatchWorkItem?
    private var launchSplashMinimumDelayWorkItem: DispatchWorkItem?
    private var launchSplashShownAt: Date?
    private var hasDismissedLaunchSplash = false

    private var mainContentHost: NSView?
    /// Pin constraints for the current page inside `mainContentHost`; deactivated before each swap so relayout never stacks duplicates.
    private var mainContentHostPinConstraints: [NSLayoutConstraint] = []
    private var sidebarRowViews: [SidebarPage: NSView] = [:]
    private var selectedSidebarPage: SidebarPage = .joinMeetings
    private var selectedZoomJoinMode: ZoomJoinMode = .id
    private var pageCache: [SidebarPage: NSView] = [:]
    private var sidebarPageByView = [ObjectIdentifier: SidebarPage]()
    private var zoomJoinModeByView = [ObjectIdentifier: ZoomJoinMode]()
    private var zoomJoinModeViews: [ZoomJoinMode: NSView] = [:]
    private var settingsActionByView = [ObjectIdentifier: SettingsAction]()
    private var aiCompanionAudioURLByView = [ObjectIdentifier: URL]()
    private var aiCompanionAudioStatusLabelByView = [ObjectIdentifier: NSTextField]()
    private var aiCompanionTranscriptMeetingIdByView = [ObjectIdentifier: String]()
    private var aiCompanionTranscriptStatusLabelByView = [ObjectIdentifier: NSTextField]()
    private var aiCompanionTranscriptCurrentRequestId: UUID?
    private var aiCompanionTranscriptWindow: NSWindow?
    private weak var aiCompanionTranscriptTextView: NSTextView?
    private var aiCompanionTranscriptTaskByMeetingId = [String: Task<Void, Never>]()
    private var aiCompanionNotesMeetingIdByView = [ObjectIdentifier: String]()
    private var aiCompanionNotesStatusLabelByView = [ObjectIdentifier: NSTextField]()
    private var aiCompanionNotesCurrentRequestId: UUID?
    private var aiCompanionNotesPanel: NSPanel?
    private weak var aiCompanionNotesRootView: NSView?
    private weak var aiCompanionNotesHeaderView: NSView?
    private weak var aiCompanionNotesTitleLabel: NSTextField?
    private weak var aiCompanionNotesSubtitleLabel: NSTextField?
    private weak var aiCompanionNotesTextView: NSTextView?
    private weak var aiCompanionNotesCopyButton: NSButton?
    private weak var aiCompanionNotesCloseButton: NSButton?
    private var aiCompanionNotesOutsideClickMonitor: Any?
    private var aiCompanionNotesTaskByMeetingId = [String: Task<Void, Never>]()
    private var aiCompanionAudioPlayer: AVPlayer?
    private var aiCompanionLocalAudioPlayer: AVAudioPlayer?
    private var aiCompanionCurrentlyPlayingURL: URL?
    private weak var aiCompanionCurrentlyPlayingButton: NSButton?
    private var aiCompanionPlaybackEndObserver: NSObjectProtocol?
    private var aiCompanionPlaybackFailedObserver: NSObjectProtocol?
    private var aiCompanionTimeControlObserver: NSKeyValueObservation?
    private var aiCompanionAudioRequestID = UUID()
    private var aiCompanionNoProgressWorkItem: DispatchWorkItem?

    private let aiCompanionSpeechSynthesizer = AVSpeechSynthesizer()
    private var aiCompanionIsUsingSpeech = false
    private var aiCompanionSpeechTextByView = [ObjectIdentifier: String]()
    private var aiCompanionCurrentlySpeakingButtonId: ObjectIdentifier?
    private var paywallWindow: NSWindow?
    private weak var paywallOverlayView: NSView?
    private let paywallContentWidth: CGFloat = 520
    private let launchWindowLeftOffset: CGFloat = 80
    private var selectedPremiumPlan: PremiumPlan = .monthly
    private var paywallPlanViews: [PremiumPlan: NSView] = [:]
    private var premiumPlanByView = [ObjectIdentifier: PremiumPlan]()
    private var paywallFooterActionByView = [ObjectIdentifier: PaywallFooterAction]()
    private weak var paywallOfferLabel: NSTextField?
    private weak var paywallContinueLabel: NSTextField?
    private weak var paywallContinueButton: NSView?
    private weak var sidebarPremiumTitleLabel: NSTextField?
    private weak var sidebarPremiumIconView: NSImageView?
    private weak var sidebarPremiumButtonView: HoverTrackingView?
    private weak var instantMeetCardView: HoverSurfaceView?
    private weak var instantMeetTitleLabel: NSTextField?
    private weak var instantMeetSubtitleLabel: NSTextField?
    private weak var joinWithLinkCardView: HoverSurfaceView?
    private weak var joinWithLinkTitleLabel: NSTextField?
    private weak var joinMeetPrimaryButton: NSButton?
    private weak var meetLinkField: NSTextField?
    private weak var browseAddressField: NSTextField?
    private var inAppBrowserWindowController: InAppBrowserWindowController?
    private var embeddedBrowserViewController: InAppBrowserContainerViewController?
    private var embeddedBrowserURL: URL?
    private var embeddedBrowserPolicy: InAppBrowserURLPolicy = .allowAll
    private weak var mainPanelAuthBar: NSView?
    private var mainContentHostTopToAuthConstraint: NSLayoutConstraint?
    private var mainContentHostTopToPanelConstraint: NSLayoutConstraint?
    private let googleOAuth = GoogleOAuthService.shared
    private let calendarClient = GoogleCalendarClient()
    private let googleMeetClient = GoogleMeetClient()
    private let storeKitCoordinator = StoreKitCoordinator()
    private var storeKitStartupTask: Task<Void, Never>?
    private var paywallPurchaseTask: Task<Void, Never>?
    private var paywallPriceLabels: [PremiumPlan: NSTextField] = [:]
    private var paywallSubtitleLabels: [PremiumPlan: NSTextField] = [:]
    private var paywallBadgeLabels: [PremiumPlan: NSTextField] = [:]
    private var paywallStrikePriceLabels: [PremiumPlan: NSTextField] = [:]
    private var paywallContinueEnabled = true
    private var paywallUpgradeFlowEnabled = false
    private let launchPaywallDelay: TimeInterval = 3
    private var hasCompletedInitialStoreKitSync = false
    private var hasPresentedLaunchPaywall = false
    private var launchPaywallWorkItem: DispatchWorkItem?
    private var hasViewAppearedOnce = false
    private var lastKnownPremiumAccess = false
    private var displayedScheduleMeetings: [ScheduledMeeting] = []
    private var appUsageSessionStartDate: Date?
    private var hasObservedAppLifecycleForUsage = false
    private var premiumUpgradeRatingPromptWorkItem: DispatchWorkItem?

    private enum ScheduleFilter: Int {
        case all = 0
        case today = 1
        case week = 2
    }

    private enum SchedulePageFilter: Int {
        case all = 0
        case today = 1
        case week = 2
        case month = 3
        case customRange = 4
    }

    /// Saved meeting list filters on AI Companion (uses each recording’s `endedAt` day in the current calendar).
    private enum AiCompanionRecordingsFilter: Int {
        case all = 0
        case today = 1
        case week = 2
        case previousWeek = 3
        case previousMonth = 4
        case customRange = 5
    }

    private var scheduleFilter: ScheduleFilter = .all
    private weak var scheduleDateHeadingLabel: NSTextField?
    private weak var scheduleCardsStack: NSStackView?
    private weak var scheduleCardsScrollView: NSScrollView?
    private weak var scheduleScrollLeftButton: NSView?
    private weak var scheduleScrollRightButton: NSView?
    private weak var scheduleFilterDropdown: NSPopUpButton?
    private weak var scheduleGoogleAuthButton: NSButton?
    private weak var scheduleGoogleAuthHostView: GoogleProfileAuthHostView?
    private var scheduleGoogleAuthHostPadWidthConstraint: NSLayoutConstraint?
    private var scheduleGoogleAuthHostPadHeightConstraint: NSLayoutConstraint?
    private var scheduleGoogleAuthButtonWidthConstraint: NSLayoutConstraint?
    private var scheduleGoogleAuthButtonHeightConstraint: NSLayoutConstraint?
    private weak var settingsReminderMasterSwitch: NSSwitch?
    private weak var settingsReminder1DaySwitch: NSSwitch?
    private weak var settingsReminder12HoursSwitch: NSSwitch?
    private weak var settingsReminder1HourSwitch: NSSwitch?
    /// Circular avatar size when signed in (top-right, Google-style).
    private let scheduleGoogleSignedInAvatarSize: CGFloat = 36
    private var scheduleGoogleAuthHovering = false
    private var scheduleCurrentProfile: GoogleProfileDisplay?
    /// Larger copy of the header avatar for the account popover (optional).
    private var scheduleProfileMenuAvatar: NSImage?
    private var scheduleProfileImageTask: Task<Void, Never>?
    private var googleAccountPopover: NSPopover?
    private var scheduleCachedMeetings: [ScheduledMeeting] = []
    private var aiCompanionLocalRecordings: [MeetingRecordingSummary] = []
    private var aiCompanionRecordingsFilter: AiCompanionRecordingsFilter = .today
    private var aiCompanionFilterFromDate: Date = Calendar.current.startOfDay(for: Date())
    private var aiCompanionFilterToDate: Date = Calendar.current.startOfDay(for: Date())
    private var aiCompanionRecordingsRangeErrorMessage: String?
    private weak var aiCompanionRecordingsFilterDropdown: NSPopUpButton?
    private weak var aiCompanionFilterFromDatePicker: NSDatePicker?
    private weak var aiCompanionFilterToDatePicker: NSDatePicker?
    private weak var aiCompanionRecordingsRangeErrorLabel: NSTextField?
    private var activeMeetingRecordingSession: ActiveMeetingRecordingSession?
    private var activeMeetingAudioRecorder: AVAudioRecorder?
    private var activeMeetingSystemAudioStopper: (() async -> Void)?
    private var meetingRecordingMonitorTask: Task<Void, Never>?
    private weak var aiCompanionStopRecordingButton: NSButton?
    private let widgetSnapshotLimit: Int = 3

    private var schedulePageFilter: SchedulePageFilter = .all
    private var schedulePageFromDate: Date = Calendar.current.startOfDay(for: Date())
    private var schedulePageToDate: Date = Calendar.current.startOfDay(for: Date())
    private var schedulePageFilteredMeetings: [ScheduledMeeting] = []
    private var schedulePageVisibleCount: Int = 0
    private let schedulePageBatchSize: Int = 6
    private let schedulePageCardsPerRow: Int = 3
    private let schedulePageCardSpacing: CGFloat = 20
    private let schedulePageCardHeight: CGFloat = 182
    /// Match `makeJoinMeetingsContent` vertical rhythm between sections.
    private let schedulePageStackSpacing: CGFloat = 14
    /// Tighter gap from header block (title + filters) to the date line below.
    private let schedulePageHeaderToDateSpacing: CGFloat = 10
    /// Join Meetings: gap from “Schedule” row to date heading, and date heading to card strip (keeps cards aligned with the rest of the column).
    private let joinPageScheduleHeaderToDateSpacing: CGFloat = 8
    private let joinPageDateToMeetingCardsSpacing: CGFloat = 8
    /// Match Join Meetings main content insets so the top auth/profile bar lines up with page edges.
    private let schedulePageLeadingInset: CGFloat = 28
    private let schedulePageTrailingInset: CGFloat = 28
    private var schedulePageScrollObservation: NSObjectProtocol?
    private weak var schedulePageDateHeadingLabel: NSTextField?
    private weak var schedulePageFilterDropdown: NSPopUpButton?
    private weak var schedulePageFromDatePicker: NSDatePicker?
    private weak var schedulePageToDatePicker: NSDatePicker?
    private weak var schedulePageRangeErrorLabel: NSTextField?
    private weak var schedulePageCardsStack: NSStackView?
    private weak var schedulePageCardsScrollView: NSScrollView?
    private weak var settingsPagePrimaryLanguagePopup: NSPopUpButton?
    private weak var settingsPageSecondaryLanguagePopup: NSPopUpButton?

    // MARK: - Calendar page (custom month UI)
    private var calendarPageMonthAnchor: Date = Calendar.current.startOfDay(for: Date())
    private var calendarPageSelectedDate: Date = Calendar.current.startOfDay(for: Date())
    private weak var calendarPageMonthLabel: NSTextField?
    private weak var calendarPageGridStack: NSStackView?
    private var calendarPageGridHeightConstraint: NSLayoutConstraint?
    private weak var calendarPageDaySummaryLabel: NSTextField?
    private var calendarPageActionPopover: NSPopover?
    private var calendarPageCreatePopover: NSPopover?
    private weak var topToastView: NSVisualEffectView?
    private var topToastHideWorkItem: DispatchWorkItem?

    /// In-app browser navigation: `.allowAll` or `.whitelist(hostSuffixes:)` (e.g. `["google.com"]` matches `meet.google.com`).
    private let inAppBrowserDefaultPolicy: InAppBrowserURLPolicy = .allowAll

    private let darkModeDefaultsKey = "settings.darkModeEnabled"
    private let appUsageAccumulatedSecondsDefaultsKey = "rating.appUsageAccumulatedSeconds"
    private let userHasRatedDefaultsKey = "rating.userHasRated"
    private let ratingStateMigrationV2DoneDefaultsKey = "rating.stateMigrationV2Done"
    private let nonPremiumJoinTrialConsumedDefaultsKey = "join.nonPremiumTrialConsumed"
    private let aiCompanionLocalRecordingsDefaultsKey = "aiCompanion.localRecordings"
    private let aiCompanionPreferredLanguage1DefaultsKey = "aiCompanion.preferredLanguage1"
    private let aiCompanionPreferredLanguage2DefaultsKey = "aiCompanion.preferredLanguage2"
    private weak var activeMeetingConsentWindow: NSWindow?
    private weak var meetingConsentPrimaryLanguagePopup: NSPopUpButton?
    private weak var meetingConsentSecondaryLanguagePopup: NSPopUpButton?
    private var didTapInlineMeetingConsentClose = false
    private let ratingEligibleUsageSeconds: TimeInterval = 30 * 60
    private let meetingTranscriptionService = MeetingTranscriptionService()
    private let meetingNotesService = MeetingNotesService()
    private var aiCompanionTranscriptProgressByMeetingId: [String: String] = [:]
    private var aiCompanionNotesProgressByMeetingId: [String: String] = [:]
    private var darkModeEnabled: Bool {
        get {
            let hasValue = UserDefaults.standard.object(forKey: darkModeDefaultsKey) != nil
            return hasValue ? UserDefaults.standard.bool(forKey: darkModeDefaultsKey) : systemPrefersDarkMode()
        }
        set { UserDefaults.standard.set(newValue, forKey: darkModeDefaultsKey) }
    }

    private var nonPremiumJoinTrialConsumed: Bool {
        get { UserDefaults.standard.bool(forKey: nonPremiumJoinTrialConsumedDefaultsKey) }
        set { UserDefaults.standard.set(newValue, forKey: nonPremiumJoinTrialConsumedDefaultsKey) }
    }

    private var shouldGateJoinActionsForNonPremium: Bool {
        !storeKitCoordinator.hasPremiumAccess && nonPremiumJoinTrialConsumed
    }

    private func makeSettingsPopover() -> NSPopover {
        let popover = NSPopover()
        popover.behavior = .transient
        popover.animates = true
        let showUpgradeInSettings = storeKitCoordinator.hasPremiumAccess && !storeKitCoordinator.hasLifetimeAccess
        let showRateUsInSettings = shouldShowRateUsInSettings
        let speechOptions = aiCompanionSupportedSpeechLocaleOptions()
        popover.contentViewController = SettingsMenuViewController(
            palette: palette,
            typography: typography,
            darkModeEnabled: darkModeEnabled,
            showRateUsInSettings: showRateUsInSettings,
            showUpgradeInSettings: showUpgradeInSettings,
            speechLocaleOptions: speechOptions,
            selectedPrimaryLanguageIdentifier: UserDefaults.standard.string(forKey: aiCompanionPreferredLanguage1DefaultsKey),
            selectedSecondaryLanguageIdentifier: UserDefaults.standard.string(forKey: aiCompanionPreferredLanguage2DefaultsKey),
            onToggleDarkMode: { [weak self] enabled in
                self?.setDarkMode(enabled)
            },
            onUpdatePreferredSpeechLanguages: { [weak self] primary, secondary in
                self?.updateAiCompanionPreferredSpeechLanguages(primary: primary, secondary: secondary)
            },
            onAction: { [weak self] action, sourceView, clickPoint in
                self?.handleSettingsAction(action, sourceView: sourceView, clickLocationInSourceView: clickPoint)
            }
        )
        return popover
    }

    private var settingsPopover: NSPopover?

    override func viewDidLoad() {
        super.viewDidLoad()
        aiCompanionSpeechSynthesizer.delegate = self
        loadAiCompanionLocalRecordings()
        // Sync toggle + palette with current macOS appearance on launch.
        darkModeEnabled = systemPrefersDarkMode()
        palette = Palette(isDarkMode: darkModeEnabled)
        storeKitCoordinator.onEntitlementsChanged = { [weak self] hasPremiumAccess in
            guard let self else { return }
            self.handlePremiumAccessChanged(hasPremiumAccess)
        }
        NotificationCenter.default.post(
            name: .statusBarPremiumAccessChanged,
            object: nil,
            userInfo: ["hasPremiumAccess": storeKitCoordinator.hasPremiumAccess]
        )
        migrateLegacyRatingStateIfNeeded()
        beginUsageTrackingSessionIfNeeded()
        observeAppLifecycleForUsageTrackingIfNeeded()
        registerWidgetNotificationObservers()
        setupRootView()
        buildMainLayout()
        showLaunchSplashIfNeeded()
        startStoreKit()
    }

    override func viewDidAppear() {
        super.viewDidAppear()
        DesktopWidgetWindowManager.shared.restore()
        hasViewAppearedOnce = true
        presentLaunchPaywallIfNeeded()
        dismissLaunchSplashIfReady()
        applyWindowTitle(for: selectedSidebarPage)
        guard let window = view.window else { return }
        configureMainWindowChrome(window)

        // Ensure launch size is applied even when macOS tries to restore prior window state.
        window.isRestorable = false
        window.setFrameAutosaveName("")

        DispatchQueue.main.async { [weak self, weak window] in
            guard let self, let window else { return }

            let frameSize = window.frameRect(forContentRect: NSRect(origin: .zero, size: self.launchContentSize)).size
            var newFrame = window.frame
            newFrame.size = frameSize
            window.setFrame(newFrame, display: true)
            window.center()
            if let screen = window.screen ?? NSScreen.main {
                var adjustedFrame = window.frame
                adjustedFrame.origin.x -= self.launchWindowLeftOffset
                let minX = screen.visibleFrame.minX
                adjustedFrame.origin.x = max(minX, adjustedFrame.origin.x)
                window.setFrame(adjustedFrame, display: true)
            }

            window.minSize = window.frameRect(forContentRect: NSRect(origin: .zero, size: self.launchMinContentSize)).size
        }
    }

    override var representedObject: Any? {
        didSet {}
    }

    deinit {
        premiumUpgradeRatingPromptWorkItem?.cancel()
        endUsageTrackingSession()
        launchSplashTimeoutWorkItem?.cancel()
        launchSplashMinimumDelayWorkItem?.cancel()
        NotificationCenter.default.removeObserver(self)
        if let observer = schedulePageScrollObservation {
            NotificationCenter.default.removeObserver(observer)
        }
        storeKitStartupTask?.cancel()
        paywallPurchaseTask?.cancel()
        launchPaywallWorkItem?.cancel()
        meetingRecordingMonitorTask?.cancel()
    }
}

private extension ViewController {
    func setupRootView() {
        view.appearance = NSAppearance(named: darkModeEnabled ? .darkAqua : .aqua)
        view.wantsLayer = true
        view.layer?.backgroundColor = palette.pageBackground.cgColor
    }

    private func makeLaunchSplashTheme() -> LaunchSplashView.Theme {
        let borderAlpha: CGFloat = darkModeEnabled ? 0.9 : 0.45
        let cardBackground = darkModeEnabled ? palette.sectionCard : palette.tabBarBackground
        let cardBorder = darkModeEnabled ? palette.inputBorder : palette.separator
        return LaunchSplashView.Theme(
            background: palette.pageBackground,
            cardBackground: cardBackground,
            cardBorder: cardBorder.withAlphaComponent(borderAlpha),
            titleText: palette.textPrimary,
            subtitleText: palette.textSecondary,
            accent: palette.primaryBlue
        )
    }

    private func showLaunchSplashIfNeeded() {
        guard launchSplashView == nil else { return }
        let splash = LaunchSplashView(frame: .zero)
        splash.alphaValue = 1
        let displayName = (Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String)?
            .trimmingCharacters(in: .whitespacesAndNewlines)
        let fallbackName = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String
        let resolvedName = (displayName?.isEmpty == false ? displayName : fallbackName) ?? "AI Companion for Meet"
        let splashIcon = NSImage(named: "LaunchLogo") ?? NSApp.applicationIconImage
        splash.configure(appName: resolvedName, appIcon: splashIcon, theme: makeLaunchSplashTheme())

        view.addSubview(splash)
        NSLayoutConstraint.activate([
            splash.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            splash.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            splash.topAnchor.constraint(equalTo: view.topAnchor),
            splash.bottomAnchor.constraint(equalTo: view.bottomAnchor)
        ])
        view.layoutSubtreeIfNeeded()
        launchSplashView = splash
        launchSplashShownAt = Date()

        launchSplashTimeoutWorkItem?.cancel()
        let timeoutWorkItem = DispatchWorkItem { [weak self] in
            self?.dismissLaunchSplash(force: true)
        }
        launchSplashTimeoutWorkItem = timeoutWorkItem
        DispatchQueue.main.asyncAfter(deadline: .now() + launchSplashTimeout, execute: timeoutWorkItem)
    }

    private func dismissLaunchSplashIfReady() {
        guard hasCompletedInitialStoreKitSync else { return }
        guard !hasDismissedLaunchSplash else { return }
        if let shownAt = launchSplashShownAt {
            let elapsed = Date().timeIntervalSince(shownAt)
            let remaining = launchSplashMinimumVisibleDuration - elapsed
            if remaining > 0 {
                launchSplashMinimumDelayWorkItem?.cancel()
                let minDelayWorkItem = DispatchWorkItem { [weak self] in
                    self?.dismissLaunchSplash(force: false)
                }
                launchSplashMinimumDelayWorkItem = minDelayWorkItem
                DispatchQueue.main.asyncAfter(deadline: .now() + remaining, execute: minDelayWorkItem)
                return
            }
        }
        dismissLaunchSplash(force: false)
    }

    private func dismissLaunchSplash(force: Bool) {
        guard !hasDismissedLaunchSplash else { return }
        guard let splash = launchSplashView else { return }
        if !force && !hasCompletedInitialStoreKitSync { return }

        hasDismissedLaunchSplash = true
        launchSplashTimeoutWorkItem?.cancel()
        launchSplashTimeoutWorkItem = nil
        launchSplashMinimumDelayWorkItem?.cancel()
        launchSplashMinimumDelayWorkItem = nil

        let removeSplash: () -> Void = { [weak self] in
            splash.removeFromSuperview()
            self?.launchSplashView = nil
            self?.launchSplashShownAt = nil
        }

        let fadeOutAndRemove: () -> Void = {
            NSAnimationContext.runAnimationGroup({ context in
                context.duration = 0.24
                context.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
                splash.animator().alphaValue = 0
            }, completionHandler: removeSplash)
        }

        if NSWorkspace.shared.accessibilityDisplayShouldReduceMotion {
            splash.completeLoading(duration: 0) {
                removeSplash()
            }
            return
        }

        splash.completeLoading {
            fadeOutAndRemove()
        }
    }

    func systemPrefersDarkMode() -> Bool {
        // Use the system-wide appearance setting (not app/window effective appearance).
        // When the key is missing, macOS is in Light mode.
        let global = UserDefaults.standard.persistentDomain(forName: UserDefaults.globalDomain)
        let style = global?["AppleInterfaceStyle"] as? String
        return style?.lowercased() == "dark"
    }

    func buildMainLayout() {
        let splitContainer = NSStackView()
        splitContainer.translatesAutoresizingMaskIntoConstraints = false
        splitContainer.orientation = .horizontal
        splitContainer.spacing = 14
        splitContainer.distribution = .fill
        splitContainer.alignment = .top
        view.addSubview(splitContainer)

        NSLayoutConstraint.activate([
            splitContainer.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            splitContainer.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            splitContainer.topAnchor.constraint(equalTo: view.topAnchor),
            splitContainer.bottomAnchor.constraint(equalTo: view.bottomAnchor)
        ])

        let sidebar = makeSidebar()
        let mainPanel = makeMainPanel()
        sidebar.setContentHuggingPriority(.required, for: .horizontal)
        sidebar.setContentCompressionResistancePriority(.required, for: .horizontal)
        mainPanel.setContentHuggingPriority(.defaultLow, for: .horizontal)
        mainPanel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
        splitContainer.addArrangedSubview(sidebar)
        splitContainer.addArrangedSubview(mainPanel)
    }

    @objc private func sidebarItemClicked(_ sender: NSClickGestureRecognizer) {
        guard let view = sender.view else { return }
        activateSidebarItem(view)
    }

    private func activateSidebarItem(_ view: NSView) {
        guard let page = sidebarPageByView[ObjectIdentifier(view)],
              page != selectedSidebarPage || page == .settings else { return }
        showSidebarPage(page)
    }

    @objc private func zoomJoinModeClicked(_ sender: NSClickGestureRecognizer) {
        guard let view = sender.view,
              let mode = zoomJoinModeByView[ObjectIdentifier(view)],
              mode != selectedZoomJoinMode else { return }
        selectedZoomJoinMode = mode
        updateZoomJoinModeAppearance()
        if selectedSidebarPage == .joinMeetings {
            pageCache[.joinMeetings] = nil
            showSidebarPage(.joinMeetings)
        }
    }

    @objc private func premiumButtonClicked(_ sender: NSClickGestureRecognizer) {
        if storeKitCoordinator.hasLifetimeAccess {
            openManageSubscriptions()
        } else if storeKitCoordinator.hasPremiumAccess {
            showPaywall(upgradeFlow: true, preferredPlan: .lifetime)
        } else {
            showPaywall()
        }
    }

    @objc private func sidebarButtonClicked(_ sender: NSButton) {
        guard let page = SidebarPage(rawValue: sender.tag),
              page != selectedSidebarPage || page == .settings else { return }
        showSidebarPage(page)
    }

    private func registerWidgetNotificationObservers() {
        NotificationCenter.default.addObserver(self, selector: #selector(widgetOpenJoinMeetingsPageRequested), name: .widgetOpenJoinMeetingsPage, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(widgetOpenSchedulePageRequested), name: .widgetOpenSchedulePage, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(widgetOpenCalendarPageRequested), name: .widgetOpenCalendarPage, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(widgetOpenSettingsPageRequested), name: .widgetOpenSettingsPage, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(widgetSignInRequested), name: .widgetSignInRequested, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(widgetRefreshRequested), name: .widgetRefreshRequested, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(widgetOpenMeetWebRequested), name: .widgetOpenMeetWebRequested, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(widgetOpenMeetingLinkRequested(_:)), name: .widgetOpenMeetingLinkRequested, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(statusBarOpenSidebarPageRequested(_:)), name: .statusBarOpenSidebarPage, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(statusBarSignOutRequested), name: .statusBarSignOutRequested, object: nil)
    }

    @objc private func widgetOpenJoinMeetingsPageRequested() { showSidebarPage(.joinMeetings) }
    @objc private func widgetOpenSchedulePageRequested() { showSidebarPage(.photo) }
    @objc private func widgetOpenCalendarPageRequested() { showSidebarPage(.video) }
    @objc private func widgetOpenSettingsPageRequested() { showSidebarPage(.settings) }
    @objc private func widgetSignInRequested() { scheduleConnectClicked() }
    @objc private func widgetRefreshRequested() { scheduleReloadClicked() }

    @objc private func widgetOpenMeetWebRequested() {
        guard let url = URL(string: "https://meet.google.com/") else { return }
        openInDefaultBrowser(url: url)
    }

    @objc private func widgetOpenMeetingLinkRequested(_ notification: Notification) {
        guard let link = notification.userInfo?["link"] as? String,
              let url = URL(string: link.trimmingCharacters(in: .whitespacesAndNewlines)) else { return }
        openInDefaultBrowser(url: url)
    }

    @objc private func statusBarOpenSidebarPageRequested(_ notification: Notification) {
        guard let pageRaw = notification.userInfo?["page"] as? Int,
              let page = SidebarPage(rawValue: pageRaw) else { return }
        showSidebarPage(page)
    }

    @objc private func statusBarSignOutRequested() { performGoogleSignOut() }

    @objc private func joinMeetClicked(_ sender: Any?) {
        guard shouldGateJoinActionsForNonPremium == false else {
            showPaywall()
            return
        }

        let rawInput = meetLinkField?.stringValue.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""

        guard let url = normalizedMeetJoinURL(from: rawInput) else {
            showSimpleAlert(
                title: "Invalid Meet link",
                message: "Enter a valid Google Meet link or meeting code (for example nkd-grps-duv, meet.google.com/nkd-grps-duv, or https://meet.google.com/nkd-grps-duv)."
            )
            return
        }

        let shouldOpenMeeting = beginMeetingRecordingIfConsented(meetingTitle: "Quick Join Meeting", meetingURL: url)
        guard shouldOpenMeeting else { return }
        openInDefaultBrowser(url: url)
        consumeNonPremiumJoinTrialIfNeeded()
    }

    @objc private func joinWithLinkCardClicked(_ sender: NSClickGestureRecognizer) {
        meetLinkField?.window?.makeFirstResponder(meetLinkField)
    }

    @objc private func cancelMeetJoinClicked(_ sender: Any?) {
        meetLinkField?.stringValue = ""
    }

    @objc private func browseOpenAddressClicked(_ sender: Any?) {
        let raw = browseAddressField?.stringValue.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
        guard raw.isEmpty == false else {
            showSimpleAlert(title: "Browse", message: "Enter a web address (for example meet.google.com).")
            return
        }
        let normalized = normalizedURLString(from: raw)
        guard let url = URL(string: normalized), url.scheme == "http" || url.scheme == "https" else {
            showSimpleAlert(title: "Invalid address", message: "Enter a valid http or https URL.")
            return
        }
        openURLWithRouting(url, policy: inAppBrowserDefaultPolicy)
    }

    @objc private func browseQuickLinkMeetClicked(_ sender: Any?) {
        guard let url = URL(string: "https://meet.google.com/") else { return }
        openInDefaultBrowser(url: url)
    }

    @objc private func browseQuickLinkMeetHelpClicked(_ sender: Any?) {
        guard let url = URL(string: "https://support.google.com/meet") else { return }
        openURLWithRouting(url, policy: inAppBrowserDefaultPolicy)
    }

    @objc private func browseQuickLinkZoomHelpClicked(_ sender: Any?) {
        guard let url = URL(string: "https://support.zoom.us") else { return }
        openURLWithRouting(url, policy: inAppBrowserDefaultPolicy)
    }

    @objc private func instantMeetClicked(_ sender: NSClickGestureRecognizer) {
        guard shouldGateJoinActionsForNonPremium == false else {
            showPaywall()
            return
        }

        // Meet blocks WKWebView. To support instant-stop recording we must create a real Meet space (with meeting code)
        // before launching the user's browser.
        guard hasGoogleSessionAvailable() else {
            showSimpleAlert(
                title: "Connect Google to start Instant Meeting",
                message: "To auto-stop recording when the meeting ends, connect your Google account first."
            )
            guard let fallbackURL = URL(string: "https://meet.google.com/new") else { return }
            openInDefaultBrowser(url: fallbackURL)
            consumeNonPremiumJoinTrialIfNeeded()
            return
        }

        let title = "Instant Meeting"
        let consentChoice = requestMeetingRecordingConsent(title: title)
        if consentChoice == .dismissed { return }

        meetingRecordingMonitorTask?.cancel()
        meetingRecordingMonitorTask = nil
        if activeMeetingRecordingSession != nil { finishActiveMeetingRecording(cancelMonitoring: false) }

        Task { [weak self] in
            guard let self else { return }
            do {
                let now = Date()
                let end = now.addingTimeInterval(60 * 60) // 1h placeholder; Meet lifecycle monitor will stop recording when call ends.
                let token = try await self.googleOAuth.validAccessToken(presentingWindow: self.view.window)
                let meeting = try await self.calendarClient.createEvent(
                    accessToken: token,
                    title: title,
                    description: nil,
                    start: now,
                    end: end
                )

                DispatchQueue.main.async {
                    if consentChoice == .allowAndContinue {
                        // Start Meet API-based recording lifecycle monitoring using the real meeting URL (has code).
                        self.startAutomaticRecordingFlow(meetingTitle: title, meetingURL: meeting.meetURL)
                    }
                    self.openInDefaultBrowser(url: meeting.meetURL)
                    self.consumeNonPremiumJoinTrialIfNeeded()
                }
            } catch {
                DispatchQueue.main.async {
                    self.showSimpleAlert(title: "Could not create Instant Meeting", message: error.localizedDescription)
                }
            }
        }
    }

    private func consumeNonPremiumJoinTrialIfNeeded() {
        guard !storeKitCoordinator.hasPremiumAccess,
              !nonPremiumJoinTrialConsumed else { return }
        nonPremiumJoinTrialConsumed = true
        refreshInstantMeetPremiumState()
    }

    private func normalizedURLString(from value: String) -> String {
        if value.lowercased().hasPrefix("http://") || value.lowercased().hasPrefix("https://") {
            return value
        }
        return "https://\(value)"
    }

    /// Typical Meet meeting code shape: three hyphen-separated groups (e.g. `nkd-grps-duv`).
    private func isValidMeetMeetingCode(_ code: String) -> Bool {
        let trimmed = code.trimmingCharacters(in: .whitespacesAndNewlines)
        guard trimmed.isEmpty == false else { return false }
        let pattern = "^[a-z0-9]{3}-[a-z0-9]{4}-[a-z0-9]{3}$"
        return trimmed.range(of: pattern, options: [.regularExpression, .caseInsensitive]) != nil
    }

    /// Accepts `https://meet.google.com/...`, `meet.google.com/...`, or a bare code; returns canonical Meet URL or `nil`.
    private func normalizedMeetJoinURL(from rawInput: String) -> URL? {
        let trimmed = rawInput.trimmingCharacters(in: .whitespacesAndNewlines)
        guard trimmed.isEmpty == false else { return nil }

        let lower = trimmed.lowercased()

        if lower.hasPrefix("http://") || lower.hasPrefix("https://") {
            guard let url = URL(string: trimmed),
                  let host = url.host?.lowercased(),
                  host == "meet.google.com" || host.hasSuffix(".meet.google.com") else {
                return nil
            }
            let path = url.path.trimmingCharacters(in: CharacterSet(charactersIn: "/"))
            guard path.isEmpty == false else { return nil }
            let firstSegment = path.split(separator: "/").first.map(String.init) ?? path
            guard isValidMeetMeetingCode(firstSegment) else { return nil }
            return URL(string: "https://meet.google.com/\(firstSegment.lowercased())")
        }

        if lower.hasPrefix("meet.google.com/") {
            let afterHost = trimmed.dropFirst("meet.google.com/".count)
            let beforeQuery = String(afterHost).split(separator: "?").first.map(String.init) ?? String(afterHost)
            let firstSegment = beforeQuery.split(separator: "/").first.map(String.init) ?? beforeQuery
            guard isValidMeetMeetingCode(firstSegment) else { return nil }
            return URL(string: "https://meet.google.com/\(firstSegment.lowercased())")
        }

        if isValidMeetMeetingCode(trimmed) {
            return URL(string: "https://meet.google.com/\(trimmed.lowercased())")
        }

        return nil
    }

    private func openInAppBrowser(with url: URL, policy: InAppBrowserURLPolicy = .allowAll) {
        let browserController: InAppBrowserWindowController
        if let existing = inAppBrowserWindowController {
            browserController = existing
        } else {
            browserController = InAppBrowserWindowController()
            inAppBrowserWindowController = browserController
        }

        browserController.load(url: url, policy: policy)
        browserController.applyDefaultFrameCenteredOnVisibleScreen()
        browserController.showWindow(nil)
        browserController.window?.makeKeyAndOrderFront(nil)
        browserController.window?.orderFrontRegardless()
        NSApp.activate(ignoringOtherApps: true)
    }

    private func openInDefaultBrowser(url: URL) {
        let routed = googleOAuth.urlForPreferredGoogleAccountIfPossible(url)
        NSWorkspace.shared.open(routed, configuration: NSWorkspace.OpenConfiguration()) { [weak self] _, error in
            if let error {
                DispatchQueue.main.async {
                    self?.showSimpleAlert(title: "Unable to open browser", message: error.localizedDescription)
                }
            }
        }
    }

    private func openURLWithRouting(_ url: URL, policy: InAppBrowserURLPolicy = .allowAll) {
        let scheme = (url.scheme ?? "").lowercased()
        if scheme == "http" || scheme == "https" {
            showEmbeddedWebPage(url, policy: policy)
            return
        }
        openInDefaultBrowser(url: url)
    }

    private func embeddedBrowserController() -> InAppBrowserContainerViewController {
        if let existing = embeddedBrowserViewController {
            return existing
        }
        let controller = InAppBrowserContainerViewController()
        embeddedBrowserViewController = controller
        return controller
    }

    private func detachEmbeddedBrowserIfNeeded() {
        guard let controller = embeddedBrowserViewController, controller.parent === self else { return }
        controller.view.removeFromSuperview()
        controller.removeFromParent()
    }

    private func mountMainContentView(_ child: NSView) {
        guard let host = mainContentHost else { return }
        NSLayoutConstraint.deactivate(mainContentHostPinConstraints)
        mainContentHostPinConstraints.removeAll()
        host.subviews.forEach { $0.removeFromSuperview() }
        child.translatesAutoresizingMaskIntoConstraints = false
        host.addSubview(child)
        mainContentHostPinConstraints = [
            child.leadingAnchor.constraint(equalTo: host.leadingAnchor),
            child.trailingAnchor.constraint(equalTo: host.trailingAnchor),
            child.topAnchor.constraint(equalTo: host.topAnchor),
            child.bottomAnchor.constraint(equalTo: host.bottomAnchor)
        ]
        NSLayoutConstraint.activate(mainContentHostPinConstraints)
    }

    private func showEmbeddedWebPage(_ url: URL, policy: InAppBrowserURLPolicy = .allowAll) {
        embeddedBrowserURL = url
        embeddedBrowserPolicy = policy

        let controller = embeddedBrowserController()
        _ = controller.view
        if controller.parent !== self {
            addChild(controller)
        }
        controller.setNavigationPolicy(policy)
        controller.load(url: url)

        setEmbeddedBrowserLayoutMode(isEmbedded: true)
        applyEmbeddedBrowserWindowTitle(url: url)
        mountMainContentView(controller.view)
    }

    private func setEmbeddedBrowserLayoutMode(isEmbedded: Bool) {
        mainPanelAuthBar?.isHidden = isEmbedded
        mainContentHostTopToAuthConstraint?.isActive = !isEmbedded
        mainContentHostTopToPanelConstraint?.isActive = isEmbedded
    }

    private func applyEmbeddedBrowserWindowTitle(url: URL) {
        if let host = url.host, host.isEmpty == false {
            view.window?.title = host
        } else {
            view.window?.title = "Browser"
        }
    }

    private func openRateUsDestination() {
        let configured = (Bundle.main.object(forInfoDictionaryKey: "RateUsURL") as? String)?
            .trimmingCharacters(in: .whitespacesAndNewlines)
        let placeholder = (Bundle.main.object(forInfoDictionaryKey: "AppLaunchPlaceholderURL") as? String)?
            .trimmingCharacters(in: .whitespacesAndNewlines)
        let hardcodedRateUsURL = "https://apps.apple.com/pk/app/meeting-app-for-google-meet/id6654920763?mt=12"

        var candidateStrings = [String]()
        if let configured, !configured.isEmpty {
            candidateStrings.append(configured)
            if let appID = extractAppleAppID(from: configured) {
                candidateStrings.append("macappstore://apps.apple.com/app/id\(appID)")
                candidateStrings.append("macappstore://itunes.apple.com/app/id\(appID)")
            }
        }
        candidateStrings.append(hardcodedRateUsURL)
        candidateStrings.append("macappstore://apps.apple.com/app/id6654920763")
        candidateStrings.append("macappstore://itunes.apple.com/app/id6654920763")
        if let placeholder, !placeholder.isEmpty {
            candidateStrings.append(placeholder)
        }

        for candidate in candidateStrings {
            guard let url = URL(string: candidate) else { continue }
            if NSWorkspace.shared.open(url) {
                return
            }
        }

        showSimpleAlert(
            title: "Unable to Open Rate Page",
            message: "Could not open the App Store rating page. Please try again."
        )

        requestAppRatingIfEligible(markAsRated: true)
    }

    private func extractAppleAppID(from urlString: String) -> String? {
        guard let match = urlString.range(of: "id[0-9]+", options: .regularExpression) else {
            return nil
        }
        let token = String(urlString[match])
        return String(token.dropFirst())
    }

    private func openInSafari(url: URL) {
        guard let safariAppURL = NSWorkspace.shared.urlForApplication(withBundleIdentifier: "com.apple.Safari") else {
            NSWorkspace.shared.open(url)
            return
        }

        let configuration = NSWorkspace.OpenConfiguration()
        NSWorkspace.shared.open([url], withApplicationAt: safariAppURL, configuration: configuration) { _, error in
            if let error {
                self.showSimpleAlert(title: "Unable to Open Safari", message: error.localizedDescription)
            }
        }
    }

    private func openManageSubscriptions() {
        if let appStoreURL = URL(string: "macappstore://apps.apple.com/account/subscriptions"),
           NSWorkspace.shared.open(appStoreURL) {
            return
        }
        guard let url = URL(string: "https://apps.apple.com/account/subscriptions") else {
            showSimpleAlert(title: "Unable to Open Subscriptions", message: "The subscriptions URL is invalid.")
            return
        }
        openInDefaultBrowser(url: url)
    }

    private func openRestoreSubscriptionPage() {
        let fallbackURL = "https://support.apple.com/en-us/108096"
        let restoreURL = (Bundle.main.object(forInfoDictionaryKey: "RestoreSubscriptionURL") as? String) ?? fallbackURL
        guard let url = URL(string: restoreURL) else {
            if let fallback = URL(string: fallbackURL) {
                NSWorkspace.shared.open(fallback)
            }
            return
        }
        NSWorkspace.shared.open(url)
    }

    private func performRestorePurchases() {
        Task { [weak self] in
            guard let self else { return }
            let message = await self.storeKitCoordinator.restorePurchases()
            self.refreshPaywallStoreUI()
            self.showSimpleAlert(title: "Restore Purchases", message: message)
        }
    }

    private func shareAppURL() -> URL? {
        if let configured = Bundle.main.object(forInfoDictionaryKey: "AppShareURL") as? String {
            let trimmed = configured.trimmingCharacters(in: .whitespacesAndNewlines)
            if trimmed.isEmpty == false, let url = URL(string: trimmed) {
                return url
            }
        }
        return nil
    }

    private func shareAppFromSettingsMenu(sourceView: NSView? = nil, clickLocationInSourceView: NSPoint? = nil) {
        let appName = Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String
            ?? Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String
            ?? "Meetings App"
        let message = "Check out \(appName) for managing and joining meetings."
        let appURL = shareAppURL()
        let shareItems: [Any] = appURL.map { [message, $0] } ?? [message]

        let picker = NSSharingServicePicker(items: shareItems)
        let anchorView = sourceView ?? sidebarRowViews[.settings] ?? view
        let anchorPoint = clickLocationInSourceView
            ?? NSPoint(x: anchorView.bounds.midX, y: anchorView.bounds.midY)
        let anchorRect = NSRect(x: anchorPoint.x, y: anchorPoint.y, width: 1, height: 1)
        picker.show(relativeTo: anchorRect, of: anchorView, preferredEdge: .minY)

        let clipboardText = ([message, appURL?.absoluteString].compactMap { $0 }).joined(separator: "\n")
        NSPasteboard.general.clearContents()
        NSPasteboard.general.setString(clipboardText, forType: .string)
    }

    private func showSidebarPage(_ page: SidebarPage) {
        selectedSidebarPage = page
        updateSidebarAppearance()
        applyWindowTitle(for: page)
        setEmbeddedBrowserLayoutMode(isEmbedded: false)
        detachEmbeddedBrowserIfNeeded()
        let child = viewForPage(page)
        mountMainContentView(child)
    }

    private func showSettingsPopover() {
        guard let anchor = sidebarRowViews[.settings] else { return }
        if settingsPopover?.isShown == true {
            settingsPopover?.performClose(nil)
            return
        }

        settingsPopover = makeSettingsPopover()
        if let menu = settingsPopover?.contentViewController as? SettingsMenuViewController {
            menu.setDarkModeEnabled(darkModeEnabled)
        }

        settingsPopover?.show(relativeTo: anchor.bounds, of: anchor, preferredEdge: .maxX)
    }

    private func setDarkMode(_ enabled: Bool) {
        darkModeEnabled = enabled
        NSApp.appearance = NSAppearance(named: enabled ? .darkAqua : .aqua)
        view.appearance = NSAppearance(named: enabled ? .darkAqua : .aqua)
        palette = Palette(isDarkMode: enabled)
        launchSplashView?.apply(theme: makeLaunchSplashTheme())
        reloadTheme()
    }

    private func reloadTheme() {
        pageCache.removeAll()
        if let observer = schedulePageScrollObservation {
            NotificationCenter.default.removeObserver(observer)
        }
        schedulePageScrollObservation = nil
        sidebarRowViews.removeAll()
        sidebarPageByView.removeAll()
        zoomJoinModeByView.removeAll()
        zoomJoinModeViews.removeAll()
        settingsActionByView.removeAll()
        paywallPlanViews.removeAll()
        premiumPlanByView.removeAll()
        paywallFooterActionByView.removeAll()
        paywallPriceLabels.removeAll()
        paywallSubtitleLabels.removeAll()
        paywallBadgeLabels.removeAll()
        paywallStrikePriceLabels.removeAll()
        paywallContinueLabel = nil
        paywallContinueButton = nil
        paywallContinueEnabled = true

        detachEmbeddedBrowserIfNeeded()
        embeddedBrowserViewController = nil
        embeddedBrowserURL = nil
        embeddedBrowserPolicy = .allowAll
        mainPanelAuthBar = nil
        mainContentHostTopToAuthConstraint = nil
        mainContentHostTopToPanelConstraint = nil

        googleAccountPopover?.performClose(nil)
        googleAccountPopover = nil

        NSLayoutConstraint.deactivate(mainContentHostPinConstraints)
        mainContentHostPinConstraints.removeAll()
        mainContentHost = nil
        view.subviews.forEach { $0.removeFromSuperview() }
        setupRootView()
        buildMainLayout()
        showSidebarPage(selectedSidebarPage)
    }

    private func handleSettingsAction(_ action: SettingsAction, sourceView: NSView? = nil, clickLocationInSourceView: NSPoint? = nil) {
        switch action {
        case .restore:
            performRestorePurchases()
        case .rateUs:
            openRateUsDestination()
        case .support:
            openSettingsLinkInDefaultBrowser(infoKey: "SupportURL")
        case .privacyPolicy:
            openSettingsLinkInDefaultBrowser(infoKey: "PrivacyPolicyURL")
        case .termsOfServices:
            openSettingsLinkInDefaultBrowser(infoKey: "TermsOfServiceURL")
        case .moreApps:
            if let moreAppsURL = Bundle.main.object(forInfoDictionaryKey: "MoreAppsURL") as? String,
               let url = URL(string: moreAppsURL) {
                openURLWithRouting(url, policy: inAppBrowserDefaultPolicy)
            }
        case .shareApp:
            shareAppFromSettingsMenu(sourceView: sourceView, clickLocationInSourceView: clickLocationInSourceView)
        case .upgrade:
            showPaywall(upgradeFlow: true, preferredPlan: .lifetime)
        }
    }

    private func openSettingsLink(infoKey: String) {
        let defaultURL = (Bundle.main.object(forInfoDictionaryKey: "AppLaunchPlaceholderURL") as? String) ?? "https://example.com/app-link-coming-soon"
        let urlString = (Bundle.main.object(forInfoDictionaryKey: infoKey) as? String) ?? defaultURL
        guard let url = URL(string: urlString) else { return }
        openURLWithRouting(url, policy: inAppBrowserDefaultPolicy)
    }

    private func openSettingsLinkInDefaultBrowser(infoKey: String) {
        let defaultURL = (Bundle.main.object(forInfoDictionaryKey: "AppLaunchPlaceholderURL") as? String) ?? "https://example.com/app-link-coming-soon"
        let urlString = (Bundle.main.object(forInfoDictionaryKey: infoKey) as? String) ?? defaultURL
        guard let url = URL(string: urlString) else { return }
        openInDefaultBrowser(url: url)
    }

    private func showSimpleAlert(title: String, message: String) {
        let alert = NSAlert()
        alert.messageText = title
        alert.informativeText = message
        alert.addButton(withTitle: "OK")
        alert.runModal()
    }

    private enum MeetingRecordingConsentChoice {
        case allowAndContinue
        case continueWithoutRecording
        case dismissed
    }

    private func requestMeetingRecordingConsent(title: String) -> MeetingRecordingConsentChoice {
        let alert = NSAlert()
        alert.messageText = "Record this meeting locally?"
        alert.informativeText = "With your consent, the app will record meeting audio on this Mac and show it in AI Companion after the meeting."
        alert.addButton(withTitle: "Allow and Continue")
        alert.addButton(withTitle: "Continue Without Recording")
        alert.window.title = title

        let speechOptions = aiCompanionSupportedSpeechLocaleOptions()
        let languageContainer = NSView(frame: NSRect(x: 0, y: 0, width: 320, height: 96))
        languageContainer.translatesAutoresizingMaskIntoConstraints = false
        languageContainer.widthAnchor.constraint(equalToConstant: 320).isActive = true
        languageContainer.heightAnchor.constraint(equalToConstant: 96).isActive = true

        let languageTitle = NSTextField(labelWithString: "Transcription Languages")
        languageTitle.translatesAutoresizingMaskIntoConstraints = false
        languageTitle.font = NSFont.systemFont(ofSize: 11, weight: .semibold)
        languageTitle.textColor = NSColor.secondaryLabelColor

        let language1Popup = NSPopUpButton(frame: .zero, pullsDown: false)
        language1Popup.translatesAutoresizingMaskIntoConstraints = false
        language1Popup.controlSize = .small
        language1Popup.target = self
        language1Popup.action = #selector(meetingConsentSpeechLanguageChanged(_:))
        for option in speechOptions {
            language1Popup.addItem(withTitle: option.displayName)
            language1Popup.lastItem?.representedObject = option.identifier
        }

        let selectedPrimary = UserDefaults.standard.string(forKey: aiCompanionPreferredLanguage1DefaultsKey)
            ?? speechOptions.first?.identifier
            ?? Locale.current.identifier
        selectSettingsPageLanguage(identifier: selectedPrimary, in: language1Popup)

        let language2Popup = NSPopUpButton(frame: .zero, pullsDown: false)
        language2Popup.translatesAutoresizingMaskIntoConstraints = false
        language2Popup.controlSize = .small
        language2Popup.target = self
        language2Popup.action = #selector(meetingConsentSpeechLanguageChanged(_:))
        language2Popup.addItem(withTitle: "None")
        language2Popup.lastItem?.representedObject = ""
        for option in speechOptions {
            language2Popup.addItem(withTitle: option.displayName)
            language2Popup.lastItem?.representedObject = option.identifier
        }
        if let selectedSecondary = UserDefaults.standard.string(forKey: aiCompanionPreferredLanguage2DefaultsKey),
           selectedSecondary.isEmpty == false {
            selectSettingsPageLanguage(identifier: selectedSecondary, in: language2Popup)
        } else {
            language2Popup.selectItem(at: 0)
        }

        let language1Label = NSTextField(labelWithString: "Preferred Language 1")
        language1Label.translatesAutoresizingMaskIntoConstraints = false
        language1Label.font = NSFont.systemFont(ofSize: 11, weight: .semibold)
        language1Label.textColor = NSColor.secondaryLabelColor
        language1Label.alignment = .center

        let language2Label = NSTextField(labelWithString: "Preferred Language 2")
        language2Label.translatesAutoresizingMaskIntoConstraints = false
        language2Label.font = NSFont.systemFont(ofSize: 11, weight: .semibold)
        language2Label.textColor = NSColor.secondaryLabelColor
        language2Label.alignment = .center

        languageContainer.addSubview(languageTitle)
        languageContainer.addSubview(language1Label)
        languageContainer.addSubview(language1Popup)
        languageContainer.addSubview(language2Label)
        languageContainer.addSubview(language2Popup)

        NSLayoutConstraint.activate([
            languageTitle.topAnchor.constraint(equalTo: languageContainer.topAnchor, constant: 0),
            languageTitle.centerXAnchor.constraint(equalTo: languageContainer.centerXAnchor),

            language1Label.topAnchor.constraint(equalTo: languageTitle.bottomAnchor, constant: 2),
            language1Label.centerXAnchor.constraint(equalTo: languageContainer.centerXAnchor),
            language1Popup.topAnchor.constraint(equalTo: language1Label.bottomAnchor, constant: 2),
            language1Popup.centerXAnchor.constraint(equalTo: languageContainer.centerXAnchor),
            language1Popup.widthAnchor.constraint(equalToConstant: 240),

            language2Label.topAnchor.constraint(equalTo: language1Popup.bottomAnchor, constant: 3),
            language2Label.centerXAnchor.constraint(equalTo: languageContainer.centerXAnchor),
            language2Popup.topAnchor.constraint(equalTo: language2Label.bottomAnchor, constant: 2),
            language2Popup.centerXAnchor.constraint(equalTo: languageContainer.centerXAnchor),
            language2Popup.widthAnchor.constraint(equalToConstant: 240),
            language2Popup.bottomAnchor.constraint(equalTo: languageContainer.bottomAnchor, constant: -1)
        ])

        alert.accessoryView = languageContainer
        didTapInlineMeetingConsentClose = false
        activeMeetingConsentWindow = alert.window
        meetingConsentPrimaryLanguagePopup = language1Popup
        meetingConsentSecondaryLanguagePopup = language2Popup
        if let contentView = alert.window.contentView {
            let topCloseButton = NSButton(title: "✕", target: self, action: #selector(meetingConsentInlineCloseTapped(_:)))
            topCloseButton.translatesAutoresizingMaskIntoConstraints = false
            topCloseButton.isBordered = false
            topCloseButton.font = NSFont.systemFont(ofSize: 15, weight: .semibold)
            topCloseButton.contentTintColor = NSColor.tertiaryLabelColor
            topCloseButton.wantsLayer = true
            topCloseButton.layer?.cornerRadius = 20
            topCloseButton.layer?.backgroundColor = NSColor.windowBackgroundColor.withAlphaComponent(0.35).cgColor
            contentView.addSubview(topCloseButton)
            NSLayoutConstraint.activate([
                topCloseButton.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10),
                topCloseButton.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -10),
                topCloseButton.widthAnchor.constraint(equalToConstant: 40),
                topCloseButton.heightAnchor.constraint(equalToConstant: 40)
            ])
        }
        let response = alert.runModal()
        activeMeetingConsentWindow = nil
        meetingConsentPrimaryLanguagePopup = nil
        meetingConsentSecondaryLanguagePopup = nil

        if didTapInlineMeetingConsentClose {
            return .dismissed
        }

        if let primary = language1Popup.selectedItem?.representedObject as? String,
           primary.isEmpty == false {
            var secondary = language2Popup.selectedItem?.representedObject as? String
            if secondary?.isEmpty == true {
                secondary = nil
            }
            updateAiCompanionPreferredSpeechLanguages(primary: primary, secondary: secondary)
        }

        switch response {
        case .alertFirstButtonReturn:
            return .allowAndContinue
        case .alertSecondButtonReturn:
            return .continueWithoutRecording
        default:
            return .dismissed
        }
    }

    @objc private func meetingConsentInlineCloseTapped(_ sender: NSButton) {
        didTapInlineMeetingConsentClose = true
        guard let consentWindow = activeMeetingConsentWindow else { return }
        NSApp.stopModal(withCode: .abort)
        consentWindow.orderOut(nil)
    }

    @objc private func meetingConsentSpeechLanguageChanged(_ sender: NSPopUpButton) {
        guard let primary = meetingConsentPrimaryLanguagePopup?.selectedItem?.representedObject as? String,
              primary.isEmpty == false else { return }

        var secondary: String? = meetingConsentSecondaryLanguagePopup?.selectedItem?.representedObject as? String
        if secondary?.isEmpty == true {
            secondary = nil
        }
        if let secondaryValue = secondary,
           secondaryValue.replacingOccurrences(of: "_", with: "-").lowercased() == primary.replacingOccurrences(of: "_", with: "-").lowercased() {
            secondary = nil
            meetingConsentSecondaryLanguagePopup?.selectItem(at: 0)
        }
        updateAiCompanionPreferredSpeechLanguages(primary: primary, secondary: secondary)
    }

    private func loadAiCompanionLocalRecordings() {
        guard let raw = UserDefaults.standard.data(forKey: aiCompanionLocalRecordingsDefaultsKey) else {
            aiCompanionLocalRecordings = []
            return
        }
        let decoder = JSONDecoder()
        if let decoded = try? decoder.decode([MeetingRecordingSummary].self, from: raw) {
            var migrated = decoded
            let testEmail = "mqlmac1@gmail.com"
            var didMigrate = false
            for idx in migrated.indices {
                let existing = migrated[idx].accountEmail?.trimmingCharacters(in: .whitespacesAndNewlines)
                if existing?.isEmpty != false {
                    migrated[idx].accountEmail = testEmail
                    didMigrate = true
                }
            }
            aiCompanionLocalRecordings = migrated.sorted(by: { $0.endedAt > $1.endedAt })
            if didMigrate {
                persistAiCompanionLocalRecordings()
            }
        } else {
            aiCompanionLocalRecordings = []
        }
    }

    private func persistAiCompanionLocalRecordings() {
        let encoder = JSONEncoder()
        guard let encoded = try? encoder.encode(aiCompanionLocalRecordings) else { return }
        UserDefaults.standard.set(encoded, forKey: aiCompanionLocalRecordingsDefaultsKey)
    }

    private func aiCompanionActiveAccountEmail() -> String? {
        guard hasGoogleSessionAvailable() else { return nil }
        let raw = scheduleCurrentProfile?.email.trimmingCharacters(in: .whitespacesAndNewlines)
        guard let raw, raw.isEmpty == false, raw.contains("@") else { return nil }
        return raw.lowercased()
    }

    private func aiCompanionRecordingsForActiveAccount() -> [MeetingRecordingSummary] {
        guard let email = aiCompanionActiveAccountEmail() else { return [] }
        return aiCompanionLocalRecordings.filter { ($0.accountEmail ?? "").lowercased() == email }
    }

    private func requestSpeechRecognitionAuthorizationIfNeeded() async throws {
        switch SFSpeechRecognizer.authorizationStatus() {
        case .authorized:
            return
        case .notDetermined:
            let status = await withCheckedContinuation { continuation in
                SFSpeechRecognizer.requestAuthorization { status in
                    continuation.resume(returning: status)
                }
            }
            guard status == .authorized else {
                throw NSError(
                    domain: "AiCompanionTranscript",
                    code: 15,
                    userInfo: [NSLocalizedDescriptionKey: "Speech recognition permission denied. Enable it in System Settings and try again."]
                )
            }
        case .denied:
            throw NSError(
                domain: "AiCompanionTranscript",
                code: 15,
                userInfo: [NSLocalizedDescriptionKey: "Speech recognition permission denied. Enable it in System Settings and try again."]
            )
        case .restricted:
            throw NSError(
                domain: "AiCompanionTranscript",
                code: 16,
                userInfo: [NSLocalizedDescriptionKey: "Speech recognition is restricted on this Mac."]
            )
        @unknown default:
            throw NSError(
                domain: "AiCompanionTranscript",
                code: 17,
                userInfo: [NSLocalizedDescriptionKey: "Speech recognition authorization is unavailable."]
            )
        }
    }

    private func transcribeLocalAudioWithAppleSpeech(audioURL: URL) async throws -> String {
        try await requestSpeechRecognitionAuthorizationIfNeeded()

        guard let recognizer = SFSpeechRecognizer(locale: Locale.current) ?? SFSpeechRecognizer(locale: Locale(identifier: "en-US")) else {
            throw NSError(
                domain: "AiCompanionTranscript",
                code: 18,
                userInfo: [NSLocalizedDescriptionKey: "Speech recognizer is unavailable for the current locale."]
            )
        }

        let request = SFSpeechURLRecognitionRequest(url: audioURL)
        request.shouldReportPartialResults = false
        if #available(macOS 13.0, *) {
            request.addsPunctuation = true
        }

        return try await withCheckedThrowingContinuation { continuation in
            var hasResumed = false
            var task: SFSpeechRecognitionTask?
            task = recognizer.recognitionTask(with: request) { result, error in
                if hasResumed { return }

                if let error {
                    hasResumed = true
                    task?.cancel()
                    continuation.resume(throwing: error)
                    return
                }

                guard let result else { return }
                if result.isFinal {
                    hasResumed = true
                    task?.finish()
                    continuation.resume(returning: result.bestTranscription.formattedString)
                }
            }
        }
    }

    private func aiCompanionTranscriptStatus(for recording: MeetingRecordingSummary) -> MeetingTranscriptStatus {
        guard let raw = recording.transcriptStatusRaw, let status = MeetingTranscriptStatus(rawValue: raw) else {
            return .notRequested
        }
        return status
    }

    private func aiCompanionTranscriptStatusText(for recording: MeetingRecordingSummary) -> String {
        switch aiCompanionTranscriptStatus(for: recording) {
        case .notRequested:
            return "Transcript not requested"
        case .processing:
            if let progress = aiCompanionTranscriptProgressByMeetingId[recording.id], progress.isEmpty == false {
                return progress
            }
            return "Transcript processing..."
        case .ready:
            return "Transcript ready"
        case .failed:
            let error = recording.transcriptErrorMessage?.trimmingCharacters(in: .whitespacesAndNewlines)
            if let error, error.isEmpty == false {
                return "Transcript unavailable (tap to retry)"
            }
            return "Transcript unavailable (tap to retry)"
        }
    }

    private func aiCompanionNotesStatus(for recording: MeetingRecordingSummary) -> MeetingNotesStatus {
        guard let raw = recording.notesStatusRaw, let status = MeetingNotesStatus(rawValue: raw) else {
            return .notRequested
        }
        return status
    }

    private func aiCompanionNotesStatusText(for recording: MeetingRecordingSummary) -> String {
        switch aiCompanionNotesStatus(for: recording) {
        case .notRequested:
            return "Notes not requested"
        case .processing:
            if let progress = aiCompanionNotesProgressByMeetingId[recording.id], progress.isEmpty == false {
                return progress
            }
            return "Preparing notes, please wait..."
        case .ready:
            return "Notes ready"
        case .failed:
            return "Notes unavailable (tap to retry)"
        }
    }

    private func aiCompanionMeetingFromRecording(_ recording: MeetingRecordingSummary) -> ScheduledMeeting? {
        guard let meetURL = URL(string: recording.meetURLString) else { return nil }
        return ScheduledMeeting(
            id: recording.id,
            title: recording.title,
            subtitle: nil,
            startDate: recording.startedAt,
            endDate: recording.endedAt,
            meetURL: meetURL,
            isAllDay: false
        )
    }

    @discardableResult
    private func aiCompanionUpdateRecording(meetingId: String, mutate: (inout MeetingRecordingSummary) -> Void) -> MeetingRecordingSummary? {
        guard let idx = aiCompanionLocalRecordings.firstIndex(where: { $0.id == meetingId }) else { return nil }
        mutate(&aiCompanionLocalRecordings[idx])
        persistAiCompanionLocalRecordings()
        return aiCompanionLocalRecordings[idx]
    }

    private func aiCompanionRefreshTranscriptStatusLabels(forMeetingID meetingId: String) {
        guard let recording = aiCompanionLocalRecordings.first(where: { $0.id == meetingId }) else { return }
        let statusText = aiCompanionTranscriptStatusText(for: recording)
        for (buttonId, linkedMeetingId) in aiCompanionTranscriptMeetingIdByView where linkedMeetingId == meetingId {
            aiCompanionTranscriptStatusLabelByView[buttonId]?.stringValue = statusText
        }
    }

    private func aiCompanionRefreshNotesStatusLabels(forMeetingID meetingId: String) {
        guard let recording = aiCompanionLocalRecordings.first(where: { $0.id == meetingId }) else { return }
        let statusText = aiCompanionNotesStatusText(for: recording)
        for (buttonId, linkedMeetingId) in aiCompanionNotesMeetingIdByView where linkedMeetingId == meetingId {
            aiCompanionNotesStatusLabelByView[buttonId]?.stringValue = statusText
        }
    }

    private func localRecordingDirectoryURL() -> URL {
        let base = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first
            ?? URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
        let bundleID = Bundle.main.bundleIdentifier ?? "meetings_app"
        let directory = base.appendingPathComponent(bundleID, isDirectory: true).appendingPathComponent("MeetingRecordings", isDirectory: true)
        try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true, attributes: nil)
        return directory
    }

    private func beginMeetingRecordingIfConsented(meetingTitle: String, meetingURL: URL) -> Bool {
        let consentChoice = requestMeetingRecordingConsent(title: meetingTitle)
        if consentChoice == .dismissed {
            return false
        }

        meetingRecordingMonitorTask?.cancel()
        meetingRecordingMonitorTask = nil
        if activeMeetingRecordingSession != nil { finishActiveMeetingRecording(cancelMonitoring: false) }
        guard consentChoice == .allowAndContinue else { return true }
        let permission = AVCaptureDevice.authorizationStatus(for: .audio)
        switch permission {
        case .authorized:
            startAutomaticRecordingFlow(meetingTitle: meetingTitle, meetingURL: meetingURL)
        case .notDetermined:
            AVCaptureDevice.requestAccess(for: .audio) { [weak self] granted in
                DispatchQueue.main.async {
                    guard let self else { return }
                    if granted {
                        self.startAutomaticRecordingFlow(meetingTitle: meetingTitle, meetingURL: meetingURL)
                    } else {
                        self.showSimpleAlert(title: "Microphone permission denied", message: "Enable microphone access in System Settings to record meetings locally.")
                    }
                }
            }
        case .denied, .restricted:
            showSimpleAlert(title: "Microphone permission required", message: "Enable microphone access in System Settings to record meetings locally.")
        @unknown default:
            break
        }
        return true
    }

    private func startAutomaticRecordingFlow(meetingTitle: String, meetingURL: URL) {
        guard let meetingCode = aiCompanionMeetMeetingCode(from: meetingURL), hasGoogleSessionAvailable() else {
            startMeetingRecording(meetingTitle: meetingTitle, meetingURL: meetingURL)
            return
        }

        showTopToast(message: "Recording will start when the meeting starts", isError: false)
        meetingRecordingMonitorTask = Task { [weak self] in
            guard let self else { return }
            defer { self.meetingRecordingMonitorTask = nil }

            do {
                let space = try await self.googleMeetClient.getSpace(
                    accessToken: try await self.googleOAuth.validAccessToken(presentingWindow: self.view.window),
                    spaceNameOrMeetingCode: "spaces/\(meetingCode)"
                )
                let spaceName = space.name ?? "spaces/\(meetingCode)"
                var hasStarted = false
                var inactivePollCount = 0
                let noStartDeadline = Date().addingTimeInterval(20 * 60)

                while !Task.isCancelled {
                    let token = try await self.googleOAuth.validAccessToken(presentingWindow: self.view.window)
                    let isActive = try await self.aiCompanionIsMeetingActive(spaceResourceName: spaceName, accessToken: token)

                    if isActive {
                        inactivePollCount = 0
                        if !hasStarted {
                            self.startMeetingRecording(meetingTitle: meetingTitle, meetingURL: meetingURL)
                            hasStarted = true
                        }
                    } else if hasStarted {
                        inactivePollCount += 1
                        if inactivePollCount >= 1 {
                            self.finishActiveMeetingRecording(cancelMonitoring: false)
                            break
                        }
                    } else if Date() > noStartDeadline {
                        break
                    }

                    try await Task.sleep(nanoseconds: 2_000_000_000)
                }
            } catch {
                if self.activeMeetingRecordingSession == nil {
                    self.startMeetingRecording(meetingTitle: meetingTitle, meetingURL: meetingURL)
                }
            }
        }
    }

    private func aiCompanionIsMeetingActive(spaceResourceName: String, accessToken: String) async throws -> Bool {
        let records = try await googleMeetClient.listConferenceRecords(accessToken: accessToken, spaceResourceName: spaceResourceName)
        return records.contains { $0.startTime != nil && $0.endTime == nil }
    }

    private func startMeetingRecording(meetingTitle: String, meetingURL: URL) {
        let recordingID = UUID().uuidString
        let outputURL = localRecordingDirectoryURL().appendingPathComponent("\(recordingID)-system.m4a")
        let microphoneURL = localRecordingDirectoryURL().appendingPathComponent("\(recordingID)-mic.m4a")

        activeMeetingRecordingSession = ActiveMeetingRecordingSession(
            id: recordingID,
            title: meetingTitle,
            meetURL: meetingURL,
            startedAt: Date(),
            systemAudioFileURL: outputURL,
            microphoneAudioFileURL: microphoneURL
        )
        pageCache[.aiCompanion] = nil
        if selectedSidebarPage == .aiCompanion { showSidebarPage(.aiCompanion) }

        startMicrophoneRecording(at: microphoneURL, showToast: false)

        if #available(macOS 13.0, *) {
            let systemRecorder = MeetingSystemAudioRecorder(outputURL: outputURL)
            activeMeetingSystemAudioStopper = { [systemRecorder] in
                try? await systemRecorder.stop()
            }
            Task { [weak self] in
                guard let self else { return }
                do {
                    try await systemRecorder.start()
                    await MainActor.run {
                        self.showTopToast(message: "Meeting recording started (meeting + microphone)", isError: false)
                    }
                } catch {
                    await MainActor.run {
                        self.activeMeetingSystemAudioStopper = nil
                        self.showTopToast(message: "System audio unavailable. Recording microphone only.", isError: true)
                    }
                }
            }
            return
        }

        showTopToast(message: "Meeting recording started (microphone only)", isError: false)
    }

    private func startMicrophoneRecording(at outputURL: URL, showToast: Bool) {
        let settings: [String: Any] = [
            AVFormatIDKey: kAudioFormatMPEG4AAC,
            AVSampleRateKey: 48_000,
            AVNumberOfChannelsKey: 1,
            AVEncoderBitRateKey: 128_000,
            AVEncoderAudioQualityKey: AVAudioQuality.max.rawValue
        ]
        do {
            let recorder = try AVAudioRecorder(url: outputURL, settings: settings)
            recorder.prepareToRecord()
            recorder.record()
            activeMeetingAudioRecorder = recorder
            if showToast {
                showTopToast(message: "Meeting recording started (microphone only)", isError: false)
            }
        } catch {
            activeMeetingRecordingSession = nil
            showSimpleAlert(title: "Could not start recording", message: error.localizedDescription)
        }
    }

    private func finishActiveMeetingRecording(cancelMonitoring: Bool = true) {
        if cancelMonitoring {
            meetingRecordingMonitorTask?.cancel()
            meetingRecordingMonitorTask = nil
        }
        guard let session = activeMeetingRecordingSession else { return }
        let stopSystemAudio = activeMeetingSystemAudioStopper
        activeMeetingSystemAudioStopper = nil
        activeMeetingAudioRecorder?.stop()
        activeMeetingAudioRecorder = nil
        activeMeetingRecordingSession = nil
        Task { [weak self] in
            guard let self else { return }
            if let stopSystemAudio { await stopSystemAudio() }
            let finalized = await self.finalizeMeetingAudioFile(
                systemURL: session.systemAudioFileURL,
                microphoneURL: session.microphoneAudioFileURL,
                recordingID: session.id
            )
            var accountEmail = await MainActor.run { self.aiCompanionActiveAccountEmail() }
            if accountEmail == nil, self.hasGoogleSessionAvailable() {
                do {
                    let token = try await self.googleOAuth.validAccessToken(presentingWindow: self.view.window)
                    if let profile = try? await self.googleOAuth.fetchUserProfile(accessToken: token) {
                        let display = await MainActor.run { self.makeGoogleProfileDisplay(from: profile) }
                        await MainActor.run { [weak self] in
                            self?.applyGoogleProfile(display)
                        }
                        let cleaned = profile.email?.trimmingCharacters(in: .whitespacesAndNewlines)
                        if let cleaned, cleaned.isEmpty == false {
                            accountEmail = cleaned.lowercased()
                        }
                    }
                } catch {
                    // If profile lookup fails, persist recording without account scoping (it will be hidden in AI Companion).
                }
            }
            await MainActor.run {
                let summary = MeetingRecordingSummary(
                    id: session.id,
                    title: session.title,
                    meetURLString: session.meetURL.absoluteString,
                    startedAt: session.startedAt,
                    endedAt: Date(),
                    audioFilePath: finalized.mixedURL.path,
                    accountEmail: accountEmail,
                    microphoneAudioFilePath: finalized.microphoneURL?.path,
                    systemAudioFilePath: finalized.systemURL?.path,
                    transcriptStatusRaw: MeetingTranscriptStatus.notRequested.rawValue,
                    transcriptSourceRaw: nil,
                    transcriptText: nil,
                    transcriptSegmentsJSON: nil,
                    transcriptErrorMessage: nil,
                    notesStatusRaw: MeetingNotesStatus.notRequested.rawValue,
                    notesText: nil,
                    notesErrorMessage: nil
                )
                self.aiCompanionLocalRecordings.insert(summary, at: 0)
                self.aiCompanionLocalRecordings.sort(by: { $0.endedAt > $1.endedAt })
                self.persistAiCompanionLocalRecordings()
                self.aiCompanionStartTranscriptProcessing(forMeetingID: summary.id, requestId: nil, interactiveAuth: false, forceRegenerate: false)
                self.pageCache[.aiCompanion] = nil
                self.showTopToast(message: "Meeting recording saved", isError: false)
                if self.selectedSidebarPage == .aiCompanion {
                    self.showSidebarPage(.aiCompanion)
                }
            }
        }
    }

    private func fileSize(at url: URL) -> Int64 {
        let attrs = try? FileManager.default.attributesOfItem(atPath: url.path)
        return attrs?[.size] as? Int64 ?? 0
    }

    private func hasAudioPayload(at url: URL, minBytes: Int64 = 10_000) -> Bool {
        guard FileManager.default.fileExists(atPath: url.path) else { return false }
        return fileSize(at: url) >= minBytes
    }

    private struct FinalizedMeetingAudio {
        let mixedURL: URL
        let microphoneURL: URL?
        let systemURL: URL?
    }

    private func finalizeMeetingAudioFile(systemURL: URL, microphoneURL: URL, recordingID: String) async -> FinalizedMeetingAudio {
        let destinationURL = localRecordingDirectoryURL().appendingPathComponent("\(recordingID).m4a")
        let hasSystem = hasAudioPayload(at: systemURL)
        let hasMic = hasAudioPayload(at: microphoneURL)

        if !hasSystem { try? FileManager.default.removeItem(at: systemURL) }
        if !hasMic { try? FileManager.default.removeItem(at: microphoneURL) }

        let savedMicURL: URL? = hasMic ? microphoneURL : nil
        let savedSystemURL: URL? = hasSystem ? systemURL : nil

        if hasSystem && hasMic {
            do {
                try await mixAudioFiles(systemURL: systemURL, microphoneURL: microphoneURL, destinationURL: destinationURL)
                return FinalizedMeetingAudio(mixedURL: destinationURL, microphoneURL: savedMicURL, systemURL: savedSystemURL)
            } catch {
                // Fall back to best available single track for playback; per-channel files stay intact.
            }
        }

        let chosenURL: URL?
        if hasSystem {
            chosenURL = systemURL
        } else if hasMic {
            chosenURL = microphoneURL
        } else {
            chosenURL = nil
        }

        if let chosenURL {
            if chosenURL.path != destinationURL.path {
                try? FileManager.default.removeItem(at: destinationURL)
                do {
                    try FileManager.default.copyItem(at: chosenURL, to: destinationURL)
                } catch {
                    return FinalizedMeetingAudio(mixedURL: chosenURL, microphoneURL: savedMicURL, systemURL: savedSystemURL)
                }
            }
            return FinalizedMeetingAudio(mixedURL: destinationURL, microphoneURL: savedMicURL, systemURL: savedSystemURL)
        }

        return FinalizedMeetingAudio(mixedURL: destinationURL, microphoneURL: nil, systemURL: nil)
    }

    private func mixAudioFiles(systemURL: URL, microphoneURL: URL, destinationURL: URL) async throws {
        try? FileManager.default.removeItem(at: destinationURL)

        let composition = AVMutableComposition()
        guard let systemTrack = composition.addMutableTrack(withMediaType: .audio, preferredTrackID: kCMPersistentTrackID_Invalid),
              let micTrack = composition.addMutableTrack(withMediaType: .audio, preferredTrackID: kCMPersistentTrackID_Invalid) else {
            throw NSError(domain: "MeetingAudioMix", code: 1, userInfo: [NSLocalizedDescriptionKey: "Unable to create audio composition tracks."])
        }

        let systemAsset = AVURLAsset(url: systemURL)
        let micAsset = AVURLAsset(url: microphoneURL)

        if let src = try await systemAsset.loadTracks(withMediaType: .audio).first {
            let duration = try await systemAsset.load(.duration)
            try systemTrack.insertTimeRange(CMTimeRange(start: .zero, duration: duration), of: src, at: .zero)
        }
        if let src = try await micAsset.loadTracks(withMediaType: .audio).first {
            let duration = try await micAsset.load(.duration)
            try micTrack.insertTimeRange(CMTimeRange(start: .zero, duration: duration), of: src, at: .zero)
        }

        guard let export = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetAppleM4A) else {
            throw NSError(domain: "MeetingAudioMix", code: 2, userInfo: [NSLocalizedDescriptionKey: "Unable to create audio export session."])
        }

        // Give the local microphone a small speech-focused boost while preserving meeting audio.
        let systemMix = AVMutableAudioMixInputParameters(track: systemTrack)
        systemMix.setVolume(1.0, at: .zero)
        let micMix = AVMutableAudioMixInputParameters(track: micTrack)
        micMix.setVolume(1.35, at: .zero)
        let audioMix = AVMutableAudioMix()
        audioMix.inputParameters = [systemMix, micMix]

        export.outputURL = destinationURL
        export.outputFileType = .m4a
        export.audioMix = audioMix
        await withCheckedContinuation { continuation in
            export.exportAsynchronously {
                continuation.resume()
            }
        }
        if export.status != .completed {
            throw export.error ?? NSError(domain: "MeetingAudioMix", code: 3, userInfo: [NSLocalizedDescriptionKey: "Audio mix export failed."])
        }
    }

    private func showTopToast(message: String, isError: Bool) {
        topToastHideWorkItem?.cancel()
        topToastHideWorkItem = nil
        topToastView?.removeFromSuperview()
        topToastView = nil

        let toast = NSVisualEffectView()
        toast.translatesAutoresizingMaskIntoConstraints = false
        toast.material = darkModeEnabled ? .hudWindow : .popover
        toast.blendingMode = .withinWindow
        toast.state = .active
        toast.wantsLayer = true
        toast.layer?.cornerRadius = 10
        toast.layer?.masksToBounds = true
        toast.layer?.borderWidth = 1
        toast.layer?.borderColor = NSColor.white.withAlphaComponent(darkModeEnabled ? 0.10 : 0.18).cgColor
        toast.layer?.backgroundColor = NSColor.black.withAlphaComponent(darkModeEnabled ? 0.68 : 0.78).cgColor
        toast.alphaValue = 0

        let row = NSStackView()
        row.translatesAutoresizingMaskIntoConstraints = false
        row.orientation = .horizontal
        row.alignment = .centerY
        row.spacing = 8
        row.distribution = .fill

        let icon = NSImageView()
        icon.translatesAutoresizingMaskIntoConstraints = false
        icon.imageScaling = .scaleProportionallyDown
        icon.image = NSImage(
            systemSymbolName: isError ? "xmark.circle.fill" : "checkmark.circle.fill",
            accessibilityDescription: isError ? "Error" : "Success"
        )
        icon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 16, weight: .semibold)
        icon.contentTintColor = isError ? NSColor.systemRed : NSColor.systemGreen

        let label = textLabel(
            message,
            font: NSFont.systemFont(ofSize: 13, weight: .semibold),
            color: NSColor.white
        )
        label.alignment = .left
        label.maximumNumberOfLines = 2
        label.lineBreakMode = .byWordWrapping
        row.addArrangedSubview(icon)
        row.addArrangedSubview(label)
        toast.addSubview(row)

        view.addSubview(toast)
        NSLayoutConstraint.activate([
            toast.topAnchor.constraint(equalTo: view.topAnchor, constant: 14),
            toast.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            toast.widthAnchor.constraint(lessThanOrEqualTo: view.widthAnchor, constant: -40),
            toast.heightAnchor.constraint(greaterThanOrEqualToConstant: 40),

            icon.widthAnchor.constraint(equalToConstant: 16),
            icon.heightAnchor.constraint(equalToConstant: 16),

            row.leadingAnchor.constraint(equalTo: toast.leadingAnchor, constant: 14),
            row.trailingAnchor.constraint(equalTo: toast.trailingAnchor, constant: -14),
            row.topAnchor.constraint(equalTo: toast.topAnchor, constant: 10),
            row.bottomAnchor.constraint(equalTo: toast.bottomAnchor, constant: -10)
        ])

        topToastView = toast

        NSAnimationContext.runAnimationGroup { context in
            context.duration = 0.18
            context.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
            toast.animator().alphaValue = 1
        }

        let hideWorkItem = DispatchWorkItem { [weak self, weak toast] in
            guard let self, let toast else { return }
            NSAnimationContext.runAnimationGroup({ context in
                context.duration = 0.2
                context.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
                toast.animator().alphaValue = 0
            }, completionHandler: {
                toast.removeFromSuperview()
                if self.topToastView === toast {
                    self.topToastView = nil
                }
            })
        }
        topToastHideWorkItem = hideWorkItem
        DispatchQueue.main.asyncAfter(deadline: .now() + 2.0, execute: hideWorkItem)
    }

    private func confirmPremiumUpgrade(for targetPlan: PremiumPlan) -> Bool {
        let alert = NSAlert()
        alert.messageText = "Already Premium"
        alert.informativeText = "You are already premium. Do you want to continue with this purchase?"
        alert.addButton(withTitle: "Continue")
        alert.addButton(withTitle: "Cancel")
        return alert.runModal() == .alertFirstButtonReturn
    }

    private func showPaywall(upgradeFlow: Bool = false, preferredPlan: PremiumPlan? = nil) {
        if !Thread.isMainThread {
            DispatchQueue.main.async { [weak self] in
                self?.showPaywall(upgradeFlow: upgradeFlow, preferredPlan: preferredPlan)
            }
            return
        }
        paywallUpgradeFlowEnabled = upgradeFlow
        if let preferredPlan {
            selectedPremiumPlan = preferredPlan
        } else if !storeKitCoordinator.hasPremiumAccess {
            selectedPremiumPlan = .yearly
        }
        if let existingOverlay = paywallOverlayView {
            refreshPaywallStoreUI()
            existingOverlay.alphaValue = 1
            view.addSubview(existingOverlay, positioned: .above, relativeTo: nil)
            return
        }
        if let existing = paywallWindow {
            refreshPaywallStoreUI()
            animatePaywallPresentation(existing)
            existing.makeKeyAndOrderFront(nil)
            NSApp.activate(ignoringOtherApps: true)
            return
        }

        let content = makePaywallContent()
        let overlay = NSView()
        overlay.translatesAutoresizingMaskIntoConstraints = false
        overlay.wantsLayer = true
        overlay.layer?.backgroundColor = palette.pageBackground.withAlphaComponent(0.98).cgColor
        overlay.alphaValue = 0
        overlay.addSubview(content)
        view.addSubview(overlay, positioned: .above, relativeTo: nil)
        NSLayoutConstraint.activate([
            overlay.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            overlay.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            overlay.topAnchor.constraint(equalTo: view.topAnchor),
            overlay.bottomAnchor.constraint(equalTo: view.bottomAnchor),

            content.leadingAnchor.constraint(equalTo: overlay.leadingAnchor),
            content.trailingAnchor.constraint(equalTo: overlay.trailingAnchor),
            content.topAnchor.constraint(equalTo: overlay.topAnchor),
            content.bottomAnchor.constraint(equalTo: overlay.bottomAnchor)
        ])
        paywallOverlayView = overlay
        NSAnimationContext.runAnimationGroup { context in
            context.duration = 0.20
            context.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
            overlay.animator().alphaValue = 1
        }

        Task { [weak self] in
            guard let self else { return }
            await self.storeKitCoordinator.refreshProducts()
            self.refreshPaywallStoreUI()
        }
    }

    private func animatePaywallPresentation(_ window: NSWindow) {
        let finalFrame = window.frame
        let targetScreen = window.screen ?? NSScreen.main
        let startY: CGFloat
        if let screen = targetScreen {
            startY = screen.visibleFrame.maxY + 12
        } else {
            startY = finalFrame.origin.y + 120
        }
        let startFrame = NSRect(x: finalFrame.origin.x, y: startY, width: finalFrame.width, height: finalFrame.height)

        window.setFrame(startFrame, display: false)
        window.alphaValue = 0

        NSAnimationContext.runAnimationGroup { context in
            context.duration = 0.28
            context.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
            window.animator().alphaValue = 1
            window.animator().setFrame(finalFrame, display: true)
        }
    }

    @objc private func closePaywallClicked(_ sender: Any?) {
        if let overlay = paywallOverlayView {
            paywallOverlayView = nil
            paywallUpgradeFlowEnabled = false
            overlay.removeFromSuperview()
            return
        }
        if let win = paywallWindow {
            win.performClose(nil)
            return
        }
        if let gesture = sender as? NSGestureRecognizer, let win = gesture.view?.window {
            win.performClose(nil)
            return
        }
        if let view = sender as? NSView, let win = view.window {
            win.performClose(nil)
            return
        }
    }

    private func dismissPaywallIfPresented() {
        if !Thread.isMainThread {
            DispatchQueue.main.async { [weak self] in
                self?.dismissPaywallIfPresented()
            }
            return
        }
        closePaywallClicked(nil)
    }

    @objc private func paywallFooterLinkClicked(_ sender: NSClickGestureRecognizer) {
        guard let view = sender.view else { return }
        let action = paywallFooterActionByView[ObjectIdentifier(view)]
        let text = (view.subviews.first { $0 is NSTextField } as? NSTextField)?.stringValue ?? "Link"
        guard let action else {
            showSimpleAlert(title: text, message: "\(text) tapped.")
            return
        }
        handlePaywallFooterAction(action)
    }

    private func handlePaywallFooterAction(_ action: PaywallFooterAction) {
        switch action {
        case .manageSubscription:
            openManageSubscriptions()
        case .restorePurchase:
            performRestorePurchases()
        case .continueWithFreePlan:
            closePaywallClicked(nil)
        case .privacyPolicy:
            openSettingsLinkInDefaultBrowser(infoKey: "PrivacyPolicyURL")
        case .support:
            openSettingsLinkInDefaultBrowser(infoKey: "SupportURL")
        case .termsOfServices:
            openSettingsLinkInDefaultBrowser(infoKey: "TermsOfServiceURL")
        }
    }

    @objc private func paywallFooterButtonPressed(_ sender: NSButton) {
        guard let action = paywallFooterActionByView[ObjectIdentifier(sender)] else { return }
        handlePaywallFooterAction(action)
    }

    @objc private func paywallPlanClicked(_ sender: NSClickGestureRecognizer) {
        guard let view = sender.view,
              let plan = premiumPlanByView[ObjectIdentifier(view)] else { return }
        selectedPremiumPlan = plan
        updatePaywallPlanSelection()
    }

    @objc private func paywallPlanButtonClicked(_ sender: NSButton) {
        guard let plan = PremiumPlan(rawValue: sender.tag) else { return }
        selectedPremiumPlan = plan
        updatePaywallPlanSelection()
    }

    private func updatePaywallPlanSelection() {
        for (plan, view) in paywallPlanViews {
            applyPaywallPlanStyle(view, isSelected: plan == selectedPremiumPlan)
        }
        paywallOfferLabel?.stringValue = paywallOfferText(for: selectedPremiumPlan)
        updatePaywallContinueState(isLoading: false)
    }

    private func paywallOfferText(for plan: PremiumPlan) -> String {
        if storeKitCoordinator.hasPremiumAccess {
            if storeKitCoordinator.hasLifetimeAccess {
                return "Lifetime premium is active on this Apple ID."
            }
            if paywallUpgradeFlowEnabled {
                let currentPlanName = storeKitCoordinator.activeNonLifetimePlan?.displayName ?? "Premium"
                if plan == .lifetime {
                    return "Current plan: \(currentPlanName). Tap Continue to upgrade to Lifetime."
                }
                return "Current plan: \(currentPlanName). Select Lifetime to upgrade."
            }
            return "Premium is active on this Apple ID."
        }
        let productID = PremiumStoreProduct.productID(for: plan)
        if let product = storeKitCoordinator.productsByID[productID] {
            let localizedPrice = localizedDisplayPrice(product.displayPrice)
            if product.type == .nonConsumable {
                return "\(localizedPrice) one-time purchase"
            }
            if let subscription = product.subscription {
                let billingText = "\(localizedPrice)/\(subscriptionUnitText(subscription.subscriptionPeriod.unit))"
                if let introOffer = subscription.introductoryOffer,
                   introOffer.paymentMode == .freeTrial {
                    return "Free for \(subscriptionPeriodText(introOffer.period)), then \(billingText)"
                }
                return billingText
            }
            return localizedPrice
        }
        let fallbackPrice = fallbackPriceText(for: plan)
        switch plan {
        case .weekly:
            return "\(fallbackPrice)/week"
        case .monthly:
            return "\(fallbackPrice)/month"
        case .yearly:
            return "\(fallbackPrice)/year (3 days free trial)"
        case .lifetime:
            return "\(fallbackPrice) one-time purchase"
        }
    }

    private func localizedDisplayPrice(_ value: String) -> String {
        value.trimmingCharacters(in: .whitespacesAndNewlines)
    }

    private func fallbackPriceText(for plan: PremiumPlan) -> String {
        let fallbackAmount: Decimal
        switch plan {
        case .weekly:
            fallbackAmount = 1100
        case .monthly:
            fallbackAmount = 2500
        case .yearly:
            fallbackAmount = 9900
        case .lifetime:
            fallbackAmount = 14900
        }
        return localeCurrencyText(for: fallbackAmount)
    }

    private func fallbackLifetimeStrikePriceText() -> String {
        localeCurrencyText(for: 29_800)
    }

    private func fallbackAmount(for plan: PremiumPlan) -> Decimal {
        switch plan {
        case .weekly:
            return 1100
        case .monthly:
            return 2500
        case .yearly:
            return 9900
        case .lifetime:
            return 14900
        }
    }

    private func yearlySavingsBadgeText() -> String {
        let yearlyProduct = storeKitCoordinator.productsByID[PremiumStoreProduct.yearly]
        let monthlyProduct = storeKitCoordinator.productsByID[PremiumStoreProduct.monthly]

        let yearlyAmount = yearlyProduct?.price ?? fallbackAmount(for: .yearly)
        let monthlyAmount = monthlyProduct?.price ?? fallbackAmount(for: .monthly)
        let yearlyCostIfMonthly = monthlyAmount * Decimal(12)
        guard yearlyCostIfMonthly > 0 else { return "Save 0%" }

        let savingsRatio = (yearlyCostIfMonthly - yearlyAmount) / yearlyCostIfMonthly
        guard savingsRatio > 0 else { return "Save 0%" }
        let savingsPercentDecimal = savingsRatio * Decimal(100)
        let roundedPercent = Int(NSDecimalNumber(decimal: savingsPercentDecimal).doubleValue.rounded())
        let savingsPercent = max(1, roundedPercent)
        return "Save \(savingsPercent)%"
    }

    private func localeCurrencyText(for amount: Decimal) -> String {
        let formatter = NumberFormatter()
        formatter.numberStyle = .currency
        formatter.locale = Locale.current

        if formatter.currencyCode == nil {
            formatter.currencyCode = "USD"
        }
        return formatter.string(from: amount as NSDecimalNumber) ?? "\(amount)"
    }

    private func strikePriceText(for product: Product) -> String {
        let strikeAmount = product.price * Decimal(2)
        return strikeAmount.formatted(product.priceFormatStyle)
    }

    private func subscriptionUnitText(_ unit: Product.SubscriptionPeriod.Unit) -> String {
        switch unit {
        case .day: return "day"
        case .week: return "week"
        case .month: return "month"
        case .year: return "year"
        @unknown default: return "period"
        }
    }

    private func subscriptionPeriodText(_ period: Product.SubscriptionPeriod) -> String {
        let unit = subscriptionUnitText(period.unit)
        if period.value == 1 {
            return "1 \(unit)"
        }
        return "\(period.value) \(unit)s"
    }

    private func freeTrialPackageText(for product: Product) -> String? {
        guard let introOffer = product.subscription?.introductoryOffer,
              introOffer.paymentMode == .freeTrial else {
            return nil
        }
        return "\(subscriptionPeriodText(introOffer.period)) free trial"
    }

    private func startStoreKit() {
        storeKitStartupTask?.cancel()
        storeKitStartupTask = Task { [weak self] in
            guard let self else { return }
            await self.storeKitCoordinator.start()
            self.hasCompletedInitialStoreKitSync = true
            self.refreshPaywallStoreUI()
            self.presentLaunchPaywallIfNeeded()
            self.dismissLaunchSplashIfReady()
        }
    }

    private func refreshPaywallStoreUI() {
        for (plan, label) in paywallPriceLabels {
            let productID = PremiumStoreProduct.productID(for: plan)
            if let product = storeKitCoordinator.productsByID[productID] {
                label.stringValue = localizedDisplayPrice(product.displayPrice)
            } else {
                label.stringValue = fallbackPriceText(for: plan)
            }
        }
        for (plan, label) in paywallSubtitleLabels {
            let productID = PremiumStoreProduct.productID(for: plan)
            guard let product = storeKitCoordinator.productsByID[productID],
                  let period = product.subscription?.subscriptionPeriod else {
                // Show neutral fallback text when subscription metadata isn't available.
                label.stringValue = "Billed via App Store"
                continue
            }
            let recurringText = "\(localizedDisplayPrice(product.displayPrice))/\(subscriptionUnitText(period.unit))"
            if let trialText = freeTrialPackageText(for: product) {
                label.stringValue = "\(recurringText)  •  \(trialText)"
            } else {
                label.stringValue = recurringText
            }
        }
        for (plan, label) in paywallStrikePriceLabels {
            guard plan == .lifetime else { continue }
            let productID = PremiumStoreProduct.productID(for: plan)
            if let product = storeKitCoordinator.productsByID[productID] {
                label.stringValue = strikePriceText(for: product)
            } else {
                label.stringValue = fallbackLifetimeStrikePriceText()
            }
        }
        paywallBadgeLabels[.yearly]?.stringValue = yearlySavingsBadgeText()
        paywallBadgeLabels[.lifetime]?.stringValue = "Best Value"
        refreshSidebarPremiumButton()
        refreshInstantMeetPremiumState()
        updatePaywallPlanSelection()
        updatePaywallContinueState(isLoading: false)
    }

    private func refreshInstantMeetPremiumState() {
        let isLocked = shouldGateJoinActionsForNonPremium
        let lockedAlpha: CGFloat = 0.6

        instantMeetCardView?.alphaValue = isLocked ? lockedAlpha : 1.0
        instantMeetTitleLabel?.alphaValue = isLocked ? lockedAlpha : 1.0
        instantMeetSubtitleLabel?.alphaValue = isLocked ? lockedAlpha : 1.0
        instantMeetCardView?.toolTip = isLocked ? "Free trial used. Upgrade to continue." : nil
        instantMeetCardView?.onHoverChanged?(false)

        joinWithLinkCardView?.alphaValue = isLocked ? lockedAlpha : 1.0
        joinWithLinkTitleLabel?.alphaValue = isLocked ? lockedAlpha : 1.0
        meetLinkField?.isEditable = !isLocked
        meetLinkField?.isSelectable = !isLocked
        meetLinkField?.alphaValue = isLocked ? lockedAlpha : 1.0
        joinMeetPrimaryButton?.isEnabled = true
        joinMeetPrimaryButton?.alphaValue = isLocked ? lockedAlpha : 1.0
        joinMeetPrimaryButton?.toolTip = isLocked ? "Free trial used. Upgrade to continue." : nil
        joinWithLinkCardView?.toolTip = isLocked ? "Free trial used. Upgrade to continue." : nil
    }

    private func handlePremiumAccessChanged(_ hasPremiumAccess: Bool) {
        let hadPremiumAccess = lastKnownPremiumAccess
        lastKnownPremiumAccess = hasPremiumAccess
        NotificationCenter.default.post(
            name: .statusBarPremiumAccessChanged,
            object: nil,
            userInfo: ["hasPremiumAccess": hasPremiumAccess]
        )
        premiumUpgradeRatingPromptWorkItem?.cancel()
        refreshPaywallStoreUI()
        refreshScheduleCardsForPremiumStateChange()
        refreshPagesAfterPremiumStateUpdate()
        Task { [weak self] in
            await self?.loadSchedule()
        }

        if !hadPremiumAccess && hasPremiumAccess {
            dismissPaywallIfPresented()
            if selectedSidebarPage != .joinMeetings {
                Task { [weak self] in
                    await self?.loadSchedule()
                }
            }
            // Skip delayed review prompt during initial launch entitlement sync.
            // We only want this after a real in-session upgrade.
            if hasCompletedInitialStoreKitSync {
                scheduleRatingPromptAfterPremiumUpgrade()
            }
            MeetingReminderManager.shared.requestPermissionIfNeeded { [weak self] _ in
                guard let self else { return }
                MeetingReminderManager.shared.scheduleReminders(for: self.scheduleCachedMeetings)
            }
        }
        if hadPremiumAccess && !hasPremiumAccess {
            MeetingReminderManager.shared.cancelAllReminders()
            DesktopWidgetWindowManager.shared.removeAllInstances()
            showPaywall()
        }
    }

    private func refreshPagesAfterPremiumStateUpdate() {
        pageCache[.joinMeetings] = nil
        pageCache[.photo] = nil
        pageCache[.video] = nil
        pageCache[.widgets] = nil
        pageCache[.settings] = nil
        pageCache[.aiCompanion] = nil
        showSidebarPage(selectedSidebarPage)
    }

    private var userHasRated: Bool {
        UserDefaults.standard.bool(forKey: userHasRatedDefaultsKey)
    }

    private var accumulatedAppUsageSeconds: TimeInterval {
        get {
            UserDefaults.standard.double(forKey: appUsageAccumulatedSecondsDefaultsKey)
        }
        set {
            UserDefaults.standard.set(newValue, forKey: appUsageAccumulatedSecondsDefaultsKey)
        }
    }

    private var totalTrackedUsageSeconds: TimeInterval {
        let liveSessionSeconds: TimeInterval
        if let start = appUsageSessionStartDate {
            liveSessionSeconds = max(0, Date().timeIntervalSince(start))
        } else {
            liveSessionSeconds = 0
        }
        return accumulatedAppUsageSeconds + liveSessionSeconds
    }

    private var hasReachedRatingUsageThreshold: Bool {
        totalTrackedUsageSeconds >= ratingEligibleUsageSeconds
    }

    private var shouldShowRateUsInSettings: Bool {
        true
    }

    private func migrateLegacyRatingStateIfNeeded() {
        let defaults = UserDefaults.standard
        guard !defaults.bool(forKey: ratingStateMigrationV2DoneDefaultsKey) else { return }
        // Legacy behavior marked "rated" immediately after requesting review.
        // Clear once so testing and new logic can run correctly.
        defaults.set(false, forKey: userHasRatedDefaultsKey)
        defaults.set(true, forKey: ratingStateMigrationV2DoneDefaultsKey)
    }

    private func beginUsageTrackingSessionIfNeeded() {
        guard appUsageSessionStartDate == nil else { return }
        appUsageSessionStartDate = Date()
    }

    private func endUsageTrackingSession() {
        guard let start = appUsageSessionStartDate else { return }
        let sessionElapsedSeconds = max(0, Date().timeIntervalSince(start))
        accumulatedAppUsageSeconds += sessionElapsedSeconds
        appUsageSessionStartDate = nil
    }

    private func observeAppLifecycleForUsageTrackingIfNeeded() {
        guard !hasObservedAppLifecycleForUsage else { return }
        hasObservedAppLifecycleForUsage = true
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(applicationDidBecomeActiveForUsageTracking),
            name: NSApplication.didBecomeActiveNotification,
            object: nil
        )
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(applicationWillResignActiveForUsageTracking),
            name: NSApplication.willResignActiveNotification,
            object: nil
        )
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(applicationWillTerminateForUsageTracking),
            name: NSApplication.willTerminateNotification,
            object: nil
        )
    }

    @objc private func applicationDidBecomeActiveForUsageTracking() {
        beginUsageTrackingSessionIfNeeded()
    }

    @objc private func applicationWillResignActiveForUsageTracking() {
        endUsageTrackingSession()
    }

    @objc private func applicationWillTerminateForUsageTracking() {
        endUsageTrackingSession()
    }

    private func scheduleRatingPromptAfterPremiumUpgrade() {
        guard !userHasRated else { return }
        let workItem = DispatchWorkItem { [weak self] in
            self?.requestAppRatingIfEligible(markAsRated: false)
        }
        premiumUpgradeRatingPromptWorkItem = workItem
        DispatchQueue.main.asyncAfter(deadline: .now() + 10, execute: workItem)
    }

    private func requestAppRatingIfEligible(markAsRated: Bool) {
        guard storeKitCoordinator.hasPremiumAccess, !userHasRated else { return }
        SKStoreReviewController.requestReview()
        if markAsRated {
            UserDefaults.standard.set(true, forKey: userHasRatedDefaultsKey)
        }
    }

    private func refreshScheduleCardsForPremiumStateChange() {
        if let stack = scheduleCardsStack {
            renderScheduleCards(into: stack, meetings: displayedScheduleMeetings)
        }
        applySchedulePageFiltersAndRender()
    }

    private func refreshSidebarPremiumButton() {
        let isPremium = storeKitCoordinator.hasPremiumAccess
        if isPremium {
            sidebarPremiumTitleLabel?.stringValue = "Manage Subscription"
            sidebarPremiumIconView?.image = premiumButtonSymbolImage(named: "crown.fill")
        } else {
            sidebarPremiumTitleLabel?.stringValue = "Get Premium"
            sidebarPremiumIconView?.image = premiumButtonSymbolImage(named: "star.fill")
        }
        sidebarPremiumIconView?.contentTintColor = .white
        sidebarPremiumButtonView?.onHoverChanged?(false)
    }

    private func premiumButtonSymbolImage(named symbolName: String) -> NSImage? {
        let configuration = NSImage.SymbolConfiguration(pointSize: 12, weight: .semibold)
        return NSImage(systemSymbolName: symbolName, accessibilityDescription: nil)?
            .withSymbolConfiguration(configuration)
    }

    private func presentLaunchPaywallIfNeeded() {
        guard hasCompletedInitialStoreKitSync, hasViewAppearedOnce, !hasPresentedLaunchPaywall else { return }
        hasPresentedLaunchPaywall = true
        if !storeKitCoordinator.hasPremiumAccess {
            launchPaywallWorkItem?.cancel()
            let workItem = DispatchWorkItem { [weak self] in
                guard let self else { return }
                self.launchPaywallWorkItem = nil
                guard !self.storeKitCoordinator.hasPremiumAccess else { return }
                self.showPaywall()
            }
            launchPaywallWorkItem = workItem
            DispatchQueue.main.asyncAfter(deadline: .now() + launchPaywallDelay, execute: workItem)
        }
    }

    @objc private func paywallContinueClicked(_ sender: Any?) {
        startSelectedPlanPurchase()
    }

    private func startSelectedPlanPurchase() {
        guard paywallContinueEnabled else {
            if storeKitCoordinator.hasPremiumAccess {
                showSimpleAlert(title: "Premium Active", message: "This Apple ID already has premium access.")
            } else {
                showSimpleAlert(title: "Please Wait", message: "A purchase is already being processed.")
            }
            return
        }
        if paywallUpgradeFlowEnabled,
           storeKitCoordinator.hasPremiumAccess,
           selectedPremiumPlan != .lifetime,
           !confirmPremiumUpgrade(for: selectedPremiumPlan) {
            return
        }
        paywallPurchaseTask?.cancel()
        updatePaywallContinueState(isLoading: true)
        let selectedPlan = selectedPremiumPlan
        paywallPurchaseTask = Task { [weak self] in
            guard let self else { return }
            let result = await self.storeKitCoordinator.purchase(plan: selectedPlan)
            self.updatePaywallContinueState(isLoading: false)
            self.refreshPaywallStoreUI()
            switch result {
            case .success:
                self.refreshPagesAfterPremiumStateUpdate()
                Task { [weak self] in
                    await self?.loadSchedule()
                }
                if selectedPlan == .lifetime, self.storeKitCoordinator.activeNonLifetimePlan != nil {
                    self.showSimpleAlert(
                        title: "Lifetime Premium Activated",
                        message: "You are premium for lifetime now. Please cancel your previous subscription in App Store Subscriptions to avoid future renewal charges."
                    )
                } else if selectedPlan == .lifetime {
                    self.showSimpleAlert(title: "Purchase Complete", message: "Lifetime premium has been unlocked successfully.")
                } else {
                    self.showSimpleAlert(title: "Purchase Complete", message: "Premium has been unlocked successfully.")
                }
                self.dismissPaywallIfPresented()
                self.scheduleRatingPromptAfterPremiumUpgrade()
            case .cancelled:
                break
            case .pending:
                self.showSimpleAlert(title: "Purchase Pending", message: "Your purchase is pending approval. You can continue once it completes.")
            case .unavailable:
                self.showSimpleAlert(title: "Product Not Available", message: "Unable to load this product. Check your StoreKit configuration and product IDs.")
            case .alreadyOwned:
                self.showSimpleAlert(title: "Already Purchased", message: "This plan is already active on your Apple ID.")
            case .failed(let message):
                self.showSimpleAlert(title: "Purchase Failed", message: message)
            }
        }
    }

    private func updatePaywallContinueState(isLoading: Bool) {
        if isLoading {
            paywallContinueEnabled = false
            paywallContinueLabel?.stringValue = "Processing..."
            paywallContinueButton?.alphaValue = 0.75
            return
        }
        if storeKitCoordinator.hasLifetimeAccess {
            paywallContinueEnabled = false
            paywallContinueLabel?.stringValue = "Premium Active"
            paywallContinueButton?.alphaValue = 0.75
        } else if paywallUpgradeFlowEnabled && storeKitCoordinator.hasPremiumAccess {
            paywallContinueEnabled = true
            paywallContinueLabel?.stringValue = "Continue"
            paywallContinueButton?.alphaValue = 1.0
        } else {
            paywallContinueEnabled = true
            paywallContinueLabel?.stringValue = (selectedPremiumPlan == .yearly) ? "Start with 3 day trial" : "Continue"
            paywallContinueButton?.alphaValue = 1.0
        }
    }

    private func applyPaywallPlanStyle(_ card: NSView, isSelected: Bool, hovering: Bool = false) {
        let selectedBorder = NSColor(calibratedRed: 1.0, green: 0.60, blue: 0.20, alpha: 1)
        let idleBorder = palette.inputBorder
        let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
        let hoverIdleBackground =
            palette.sectionCard.blended(withFraction: 0.10, of: hoverBlend) ?? palette.sectionCard
        let selectedBackground = darkModeEnabled
            ? NSColor(calibratedRed: 30.0 / 255.0, green: 34.0 / 255.0, blue: 42.0 / 255.0, alpha: 1)
            : NSColor(calibratedRed: 255.0 / 255.0, green: 246.0 / 255.0, blue: 236.0 / 255.0, alpha: 1)
        card.layer?.backgroundColor = (isSelected ? selectedBackground : (hovering ? hoverIdleBackground : palette.sectionCard)).cgColor
        card.layer?.borderColor = (isSelected ? selectedBorder : (hovering ? selectedBorder.withAlphaComponent(0.55) : idleBorder)).cgColor
        card.layer?.borderWidth = isSelected ? 2 : 1
        card.layer?.shadowColor = NSColor.black.cgColor
        card.layer?.shadowOpacity = isSelected ? (darkModeEnabled ? 0.26 : 0.10) : (hovering ? 0.18 : 0.12)
        card.layer?.shadowOffset = CGSize(width: 0, height: -1)
        card.layer?.shadowRadius = isSelected ? (darkModeEnabled ? 10 : 6) : (hovering ? 7 : 5)
    }

    private func viewForPage(_ page: SidebarPage) -> NSView {
        if let cached = pageCache[page] { return cached }
        let built: NSView
        switch page {
        case .joinMeetings:
            built = makeJoinMeetingsContent()
        case .photo:
            built = makeSchedulePageContent()
        case .video:
            built = makeCalendarPageContent()
        case .widgets:
            built = makeWidgetsPageContent()
        case .settings:
            built = makeSettingsPageContent()
        case .aiCompanion:
            built = makeAiCompanionPageContent()
        }
        pageCache[page] = built
        return built
    }

    private func makeWidgetsPageContent() -> NSView {
        let panel = NSView()
        panel.translatesAutoresizingMaskIntoConstraints = false

        let host = makeWidgetsPageHost(canAddWidgets: storeKitCoordinator.hasPremiumAccess) { [weak self] in
            self?.showPaywall()
        }
        panel.addSubview(host)

        NSLayoutConstraint.activate([
            host.leadingAnchor.constraint(equalTo: panel.leadingAnchor, constant: 28),
            host.trailingAnchor.constraint(equalTo: panel.trailingAnchor, constant: -28),
            host.topAnchor.constraint(equalTo: panel.topAnchor),
            host.bottomAnchor.constraint(lessThanOrEqualTo: panel.bottomAnchor, constant: -16)
        ])

        // Keep widgets anchored to the top instead of drifting vertically in tall windows.
        host.setContentHuggingPriority(.required, for: .vertical)
        host.setContentCompressionResistancePriority(.required, for: .vertical)

        return panel
    }

    private func makeAiCompanionPageContent() -> NSView {
        // Reset per-card mappings so stale buttons/labels from previous page builds don't linger.
        aiCompanionAudioPlayer?.pause()
        aiCompanionAudioPlayer = nil
        aiCompanionLocalAudioPlayer?.stop()
        aiCompanionLocalAudioPlayer = nil
        aiCompanionCurrentlyPlayingURL = nil
        aiCompanionCurrentlyPlayingButton = nil
        aiCompanionTimeControlObserver = nil
        aiCompanionNoProgressWorkItem?.cancel()
        aiCompanionNoProgressWorkItem = nil

        aiCompanionSpeechSynthesizer.stopSpeaking(at: .immediate)
        aiCompanionIsUsingSpeech = false
        aiCompanionCurrentlySpeakingButtonId = nil
        if let token = aiCompanionPlaybackEndObserver { NotificationCenter.default.removeObserver(token) }
        if let token = aiCompanionPlaybackFailedObserver { NotificationCenter.default.removeObserver(token) }
        aiCompanionPlaybackEndObserver = nil
        aiCompanionPlaybackFailedObserver = nil
        aiCompanionAudioURLByView.removeAll()
        aiCompanionAudioStatusLabelByView.removeAll()
        aiCompanionSpeechTextByView.removeAll()
        aiCompanionTranscriptMeetingIdByView.removeAll()
        aiCompanionTranscriptStatusLabelByView.removeAll()
        aiCompanionNotesMeetingIdByView.removeAll()
        aiCompanionNotesStatusLabelByView.removeAll()
        // Keep transcript requests and window state alive across AI Companion page rebuilds.
        // The page is rebuilt while processing starts/completes, and cancelling here interrupts
        // the active request before it can update the transcript view.

        let panel = NSView()
        panel.translatesAutoresizingMaskIntoConstraints = false
        panel.userInterfaceLayoutDirection = .leftToRight

        let scroll = NSScrollView()
        scroll.translatesAutoresizingMaskIntoConstraints = false
        scroll.drawsBackground = false
        scroll.hasHorizontalScroller = false
        scroll.hasVerticalScroller = true
        scroll.autohidesScrollers = true
        scroll.borderType = .noBorder
        scroll.scrollerStyle = .overlay
        scroll.automaticallyAdjustsContentInsets = false
        let clip = TopAlignedClipView()
        clip.drawsBackground = false
        scroll.contentView = clip
        panel.addSubview(scroll)

        let content = NSView()
        content.translatesAutoresizingMaskIntoConstraints = false
        scroll.documentView = content

        let contentStack = NSStackView()
        contentStack.translatesAutoresizingMaskIntoConstraints = false
        contentStack.userInterfaceLayoutDirection = .leftToRight
        contentStack.orientation = .vertical
        contentStack.spacing = 12
        contentStack.alignment = .width
        contentStack.distribution = .fill

        let titleLabel = textLabel("AI Companion", font: typography.pageTitle, color: palette.textPrimary)
        titleLabel.alignment = .left
        contentStack.addArrangedSubview(titleLabel)

        let subtitle = textLabel("Get notes from your previous meetings", font: typography.fieldLabel, color: palette.textSecondary)
        subtitle.alignment = .left
        contentStack.addArrangedSubview(subtitle)
        contentStack.setCustomSpacing(14, after: subtitle)

        titleLabel.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true
        subtitle.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true

        let signedIn = hasGoogleSessionAvailable()
        let activeEmail = aiCompanionActiveAccountEmail()

        if signedIn == false || activeEmail == nil {
            let locked = roundedContainer(cornerRadius: 14, color: palette.sectionCard)
            locked.translatesAutoresizingMaskIntoConstraints = false
            styleSurface(locked, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)

            let lockedStack = NSStackView()
            lockedStack.translatesAutoresizingMaskIntoConstraints = false
            lockedStack.orientation = .vertical
            lockedStack.alignment = .leading
            lockedStack.spacing = 10

            let msg = textLabel(
                "Connect your Google account to see your AI Companion meeting history.",
                font: NSFont.systemFont(ofSize: 14, weight: .semibold),
                color: palette.textPrimary
            )
            msg.alignment = .left
            msg.maximumNumberOfLines = 2
            msg.lineBreakMode = .byWordWrapping

            lockedStack.addArrangedSubview(msg)
            locked.addSubview(lockedStack)
            NSLayoutConstraint.activate([
                lockedStack.leadingAnchor.constraint(equalTo: locked.leadingAnchor, constant: 14),
                lockedStack.trailingAnchor.constraint(equalTo: locked.trailingAnchor, constant: -14),
                lockedStack.topAnchor.constraint(equalTo: locked.topAnchor, constant: 14),
                lockedStack.bottomAnchor.constraint(equalTo: locked.bottomAnchor, constant: -14)
            ])

            contentStack.addArrangedSubview(locked)
            locked.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true

            // If tokens exist but we haven't fetched the profile yet, try to hydrate it so we can scope history correctly.
            if signedIn, scheduleCurrentProfile == nil {
                Task { [weak self] in
                    guard let self else { return }
                    do {
                        let token = try await self.googleOAuth.validAccessToken(presentingWindow: self.view.window)
                        if let profile = try? await self.googleOAuth.fetchUserProfile(accessToken: token) {
                            await MainActor.run { [weak self] in
                                guard let self else { return }
                                self.applyGoogleProfile(self.makeGoogleProfileDisplay(from: profile))
                                self.redrawAiCompanionPageIfNeeded()
                            }
                        }
                    } catch {
                        // Leave UI in connect state; schedule page handles showing auth errors.
                    }
                }
            }

            content.addSubview(contentStack)
            NSLayoutConstraint.activate([
                scroll.leadingAnchor.constraint(equalTo: panel.leadingAnchor),
                scroll.trailingAnchor.constraint(equalTo: panel.trailingAnchor),
                scroll.topAnchor.constraint(equalTo: panel.topAnchor),
                scroll.bottomAnchor.constraint(equalTo: panel.bottomAnchor),

                content.leadingAnchor.constraint(equalTo: scroll.contentView.leadingAnchor),
                content.trailingAnchor.constraint(equalTo: scroll.contentView.trailingAnchor),
                content.topAnchor.constraint(equalTo: scroll.contentView.topAnchor),
                content.bottomAnchor.constraint(greaterThanOrEqualTo: scroll.contentView.bottomAnchor),
                content.widthAnchor.constraint(equalTo: scroll.contentView.widthAnchor),

                contentStack.leftAnchor.constraint(equalTo: content.leftAnchor, constant: 28),
                contentStack.rightAnchor.constraint(equalTo: content.rightAnchor, constant: -28),
                contentStack.topAnchor.constraint(equalTo: content.topAnchor, constant: 16),
                content.bottomAnchor.constraint(greaterThanOrEqualTo: contentStack.bottomAnchor, constant: 16)
            ])

            return panel
        }

        if let session = activeMeetingRecordingSession {
            let activeCard = aiCompanionActiveRecordingCard(session: session)
            contentStack.addArrangedSubview(activeCard)
            activeCard.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true
        }

        let scopedRecordings = aiCompanionRecordingsForActiveAccount()
        if scopedRecordings.isEmpty {
            let emptyLabel = textLabel(
                "No previous meetings yet for \(activeEmail ?? "this account"). End a meeting to save it here and generate notes.",
                font: typography.fieldLabel,
                color: palette.textMuted
            )
            emptyLabel.alignment = .left
            emptyLabel.maximumNumberOfLines = 2
            emptyLabel.lineBreakMode = .byWordWrapping
            contentStack.addArrangedSubview(emptyLabel)
            emptyLabel.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true
        } else {
            let filterRow = NSStackView()
            filterRow.translatesAutoresizingMaskIntoConstraints = false
            filterRow.userInterfaceLayoutDirection = .leftToRight
            filterRow.orientation = .horizontal
            filterRow.alignment = .centerY
            filterRow.spacing = 18
            filterRow.distribution = .fill

            let filterDropdown = makeAiCompanionRecordingsFilterDropdown()
            aiCompanionRecordingsFilterDropdown = filterDropdown
            filterRow.addArrangedSubview(filterDropdown)
            filterRow.setCustomSpacing(20, after: filterDropdown)

            let (fromShell, fromPicker) = makeFilterStyleDatePicker(
                date: aiCompanionFilterFromDate,
                changeAction: #selector(aiCompanionFilterDatePickerChanged(_:))
            )
            aiCompanionFilterFromDatePicker = fromPicker
            filterRow.addArrangedSubview(fromShell)
            filterRow.setCustomSpacing(16, after: fromShell)

            let (toShell, toPicker) = makeFilterStyleDatePicker(
                date: aiCompanionFilterToDate,
                changeAction: #selector(aiCompanionFilterDatePickerChanged(_:))
            )
            aiCompanionFilterToDatePicker = toPicker
            filterRow.addArrangedSubview(toShell)
            NSLayoutConstraint.activate([
                fromShell.widthAnchor.constraint(equalTo: toShell.widthAnchor),
                fromShell.widthAnchor.constraint(greaterThanOrEqualToConstant: 152)
            ])

            let filterRowSpacer = NSView()
            filterRowSpacer.translatesAutoresizingMaskIntoConstraints = false
            filterRowSpacer.setContentHuggingPriority(.defaultLow, for: .horizontal)
            filterRowSpacer.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
            filterRow.addArrangedSubview(filterRowSpacer)

            let applyFilterButton = makeSchedulePagePillButton(title: "Apply", action: #selector(aiCompanionRecordingsApplyPressed(_:)))
            filterRow.addArrangedSubview(applyFilterButton)
            filterRow.setCustomSpacing(22, after: applyFilterButton)
            let resetFilterButton = makeSchedulePagePillButton(title: "Reset", action: #selector(aiCompanionRecordingsResetPressed(_:)))
            filterRow.addArrangedSubview(resetFilterButton)
            filterRow.setCustomSpacing(22, after: resetFilterButton)
            filterRow.addArrangedSubview(
                makeScheduleRefreshButton(
                    action: #selector(aiCompanionRecordingsRefreshPressed(_:)),
                    accessibilityDescription: "Refresh saved meetings"
                )
            )

            contentStack.addArrangedSubview(filterRow)
            filterRow.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true

            let rangeError = textLabel(
                aiCompanionRecordingsRangeErrorMessage ?? "",
                font: NSFont.systemFont(ofSize: 12, weight: .semibold),
                color: .systemRed
            )
            rangeError.alignment = .left
            rangeError.isHidden = aiCompanionRecordingsRangeErrorMessage == nil
            rangeError.maximumNumberOfLines = 3
            rangeError.lineBreakMode = .byWordWrapping
            aiCompanionRecordingsRangeErrorLabel = rangeError
            contentStack.addArrangedSubview(rangeError)
            rangeError.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true

            let previousMeetingsLabel = textLabel("Previous meetings", font: NSFont.systemFont(ofSize: 14, weight: .semibold), color: palette.textPrimary)
            previousMeetingsLabel.alignment = .left
            contentStack.addArrangedSubview(previousMeetingsLabel)
            previousMeetingsLabel.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true
            contentStack.setCustomSpacing(10, after: previousMeetingsLabel)

            let displayedRecordings = filteredAiCompanionRecordings()
            if displayedRecordings.isEmpty {
                let emptyFiltered = textLabel(
                    aiCompanionRecordingsRangeErrorMessage == nil
                        ? "No meetings match the selected filters."
                        : "Adjust the date range and tap Apply.",
                    font: typography.fieldLabel,
                    color: palette.textMuted
                )
                emptyFiltered.alignment = .left
                emptyFiltered.maximumNumberOfLines = 2
                emptyFiltered.lineBreakMode = .byWordWrapping
                contentStack.addArrangedSubview(emptyFiltered)
                emptyFiltered.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true
            } else {
                for recording in displayedRecordings {
                    let card = aiCompanionMeetingCard(recording)
                    contentStack.addArrangedSubview(card)
                    card.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true
                }
            }

            refreshAiCompanionRecordingsFilterChrome()
        }

        content.addSubview(contentStack)
        NSLayoutConstraint.activate([
            scroll.leadingAnchor.constraint(equalTo: panel.leadingAnchor),
            scroll.trailingAnchor.constraint(equalTo: panel.trailingAnchor),
            scroll.topAnchor.constraint(equalTo: panel.topAnchor),
            scroll.bottomAnchor.constraint(equalTo: panel.bottomAnchor),

            content.leadingAnchor.constraint(equalTo: scroll.contentView.leadingAnchor),
            content.trailingAnchor.constraint(equalTo: scroll.contentView.trailingAnchor),
            content.topAnchor.constraint(equalTo: scroll.contentView.topAnchor),
            content.bottomAnchor.constraint(greaterThanOrEqualTo: scroll.contentView.bottomAnchor),
            content.widthAnchor.constraint(equalTo: scroll.contentView.widthAnchor),

            contentStack.leftAnchor.constraint(equalTo: content.leftAnchor, constant: 28),
            contentStack.rightAnchor.constraint(equalTo: content.rightAnchor, constant: -28),
            contentStack.topAnchor.constraint(equalTo: content.topAnchor, constant: 16),
            content.bottomAnchor.constraint(greaterThanOrEqualTo: contentStack.bottomAnchor, constant: 16)
        ])

        return panel
    }

    private func makeAiCompanionRecordingsFilterDropdown() -> NSPopUpButton {
        let button = HoverPopUpButton(frame: .zero, pullsDown: false)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.autoenablesItems = false
        button.isBordered = false
        button.bezelStyle = .regularSquare
        button.wantsLayer = true
        button.layer?.cornerRadius = 8
        button.layer?.masksToBounds = true
        button.layer?.backgroundColor = palette.inputBackground.cgColor
        button.layer?.borderColor = palette.inputBorder.cgColor
        button.layer?.borderWidth = 1
        button.font = typography.filterText
        button.contentTintColor = palette.textSecondary
        button.target = self
        button.action = #selector(aiCompanionRecordingsFilterChanged(_:))
        button.heightAnchor.constraint(equalToConstant: 34).isActive = true
        button.widthAnchor.constraint(equalToConstant: 268).isActive = true

        button.removeAllItems()
        button.addItems(withTitles: ["All", "Today", "This week", "Previous week", "Previous month", "Custom range"])
        button.selectItem(at: aiCompanionRecordingsFilter.rawValue)
        if let menu = button.menu {
            for (index, item) in menu.items.enumerated() {
                item.tag = index
            }
        }

        let baseColor = palette.inputBackground
        let baseBorder = palette.inputBorder
        let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
        let hoverColor = baseColor.blended(withFraction: 0.10, of: hoverBlend) ?? baseColor
        let hoverBorder = baseBorder.blended(withFraction: 0.16, of: hoverBlend) ?? baseBorder
        button.onHoverChanged = { [weak button] hovering in
            button?.layer?.backgroundColor = (hovering ? hoverColor : baseColor).cgColor
            button?.layer?.borderColor = (hovering ? hoverBorder : baseBorder).cgColor
        }
        button.onHoverChanged?(false)
        return button
    }

    private func aiCompanionHasValidCustomFilterRange() -> Bool {
        let calendar = Calendar.current
        let start = calendar.startOfDay(for: aiCompanionFilterFromDate)
        let end = calendar.startOfDay(for: aiCompanionFilterToDate)
        return start <= end
    }

    private func filteredAiCompanionRecordings() -> [MeetingRecordingSummary] {
        let calendar = Calendar.current
        let now = Date()
        let recordings = aiCompanionRecordingsForActiveAccount()

        func previousCalendarWeekBounds(reference: Date) -> (start: Date, end: Date)? {
            guard let thisWeek = calendar.dateInterval(of: .weekOfYear, for: reference),
                  let prevStart = calendar.date(byAdding: .weekOfYear, value: -1, to: thisWeek.start)
            else { return nil }
            return (prevStart, thisWeek.start)
        }

        func previousCalendarMonthBounds(reference: Date) -> (start: Date, end: Date)? {
            guard let thisMonth = calendar.dateInterval(of: .month, for: reference),
                  let prevStart = calendar.date(byAdding: .month, value: -1, to: thisMonth.start)
            else { return nil }
            return (prevStart, thisMonth.start)
        }

        switch aiCompanionRecordingsFilter {
        case .all:
            return recordings
        case .today:
            let dayStart = calendar.startOfDay(for: now)
            guard let nextDay = calendar.date(byAdding: .day, value: 1, to: dayStart) else { return [] }
            return recordings.filter { $0.endedAt >= dayStart && $0.endedAt < nextDay }
        case .week:
            guard let thisWeek = calendar.dateInterval(of: .weekOfYear, for: now) else { return [] }
            return recordings.filter { $0.endedAt >= thisWeek.start && $0.endedAt < thisWeek.end }
        case .previousWeek:
            guard let bounds = previousCalendarWeekBounds(reference: now) else { return [] }
            return recordings.filter { $0.endedAt >= bounds.start && $0.endedAt < bounds.end }
        case .previousMonth:
            guard let bounds = previousCalendarMonthBounds(reference: now) else { return [] }
            return recordings.filter { $0.endedAt >= bounds.start && $0.endedAt < bounds.end }
        case .customRange:
            guard aiCompanionHasValidCustomFilterRange() else { return [] }
            let start = calendar.startOfDay(for: aiCompanionFilterFromDate)
            let inclusiveEndDay = calendar.startOfDay(for: aiCompanionFilterToDate)
            guard let endExclusive = calendar.date(byAdding: .day, value: 1, to: inclusiveEndDay) else { return [] }
            return recordings.filter { $0.endedAt >= start && $0.endedAt < endExclusive }
        }
    }

    private func refreshAiCompanionRecordingsFilterChrome() {
        let isCustom = aiCompanionRecordingsFilter == .customRange
        aiCompanionFilterFromDatePicker?.isEnabled = isCustom
        aiCompanionFilterToDatePicker?.isEnabled = isCustom
        let dim: CGFloat = isCustom ? 1.0 : 0.65
        aiCompanionFilterFromDatePicker?.superview?.alphaValue = dim
        aiCompanionFilterToDatePicker?.superview?.alphaValue = dim
    }

    private func setAiCompanionRecordingsRangeError(_ message: String?) {
        aiCompanionRecordingsRangeErrorMessage = message
        aiCompanionRecordingsRangeErrorLabel?.stringValue = message ?? ""
        aiCompanionRecordingsRangeErrorLabel?.isHidden = message == nil
    }

    private func redrawAiCompanionPageIfNeeded() {
        guard selectedSidebarPage == .aiCompanion else { return }
        pageCache[.aiCompanion] = nil
        showSidebarPage(.aiCompanion)
    }

    private func aiCompanionActiveRecordingCard(session: ActiveMeetingRecordingSession) -> NSView {
        let card = roundedContainer(cornerRadius: 14, color: palette.sectionCard)
        card.translatesAutoresizingMaskIntoConstraints = false
        styleSurface(card, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)

        let stack = NSStackView()
        stack.translatesAutoresizingMaskIntoConstraints = false
        stack.userInterfaceLayoutDirection = .leftToRight
        stack.orientation = .vertical
        stack.alignment = .leading
        stack.spacing = 8

        let title = textLabel("Recording in progress: \(session.title)", font: NSFont.systemFont(ofSize: 15, weight: .semibold), color: palette.textPrimary)
        let started = DateFormatter.localizedString(from: session.startedAt, dateStyle: .medium, timeStyle: .short)
        let status = textLabel("Started: \(started)", font: typography.fieldLabel, color: palette.textSecondary)
        let stopButton = NSButton(title: "Stop Recording", target: self, action: #selector(aiCompanionStopRecordingTapped(_:)))
        stopButton.translatesAutoresizingMaskIntoConstraints = false
        stopButton.isBordered = false
        stopButton.bezelStyle = .inline
        stopButton.font = NSFont.systemFont(ofSize: 13, weight: .semibold)
        stopButton.contentTintColor = NSColor.systemRed
        stopButton.alignment = .left
        stopButton.setButtonType(.momentaryPushIn)
        aiCompanionStopRecordingButton = stopButton

        stack.addArrangedSubview(title)
        stack.addArrangedSubview(status)
        stack.addArrangedSubview(stopButton)

        card.addSubview(stack)
        NSLayoutConstraint.activate([
            stack.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 14),
            stack.trailingAnchor.constraint(equalTo: card.trailingAnchor, constant: -14),
            stack.topAnchor.constraint(equalTo: card.topAnchor, constant: 14),
            stack.bottomAnchor.constraint(equalTo: card.bottomAnchor, constant: -14)
        ])
        return card
    }

    private func aiCompanionMeetingCard(_ recording: MeetingRecordingSummary) -> NSView {
        let card = roundedContainer(cornerRadius: 14, color: palette.sectionCard)
        card.translatesAutoresizingMaskIntoConstraints = false
        styleSurface(card, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)

        let stack = NSStackView()
        stack.translatesAutoresizingMaskIntoConstraints = false
        stack.userInterfaceLayoutDirection = .leftToRight
        stack.orientation = .vertical
        stack.alignment = .leading
        stack.spacing = 8

        let title = textLabel(recording.title, font: NSFont.systemFont(ofSize: 15, weight: .semibold), color: palette.textPrimary)
        title.alignment = .left
        title.maximumNumberOfLines = 2
        title.lineBreakMode = .byTruncatingTail

        let dateText = DateFormatter.localizedString(from: recording.endedAt, dateStyle: .medium, timeStyle: .none)
        let dateLabel = textLabel("Date: \(dateText)", font: typography.fieldLabel, color: palette.textSecondary)
        dateLabel.alignment = .left

        let savedTimeText = DateFormatter.localizedString(from: recording.endedAt, dateStyle: .none, timeStyle: .short)
        let savedTimeLabel = textLabel("Saved time: \(savedTimeText)", font: typography.fieldLabel, color: palette.textMuted)
        savedTimeLabel.alignment = .left

        let notesButton = HoverButton(title: "Get Notes", target: self, action: #selector(aiCompanionNotesTapped(_:)))
        notesButton.translatesAutoresizingMaskIntoConstraints = false
        notesButton.isBordered = false
        notesButton.bezelStyle = .regularSquare
        notesButton.wantsLayer = true
        notesButton.layer?.cornerRadius = 16
        notesButton.layer?.masksToBounds = true
        notesButton.layer?.borderWidth = 1
        notesButton.font = NSFont.systemFont(ofSize: 13, weight: .semibold)
        notesButton.contentTintColor = palette.primaryBlue
        notesButton.alignment = .center
        notesButton.setButtonType(.momentaryChange)
        notesButton.focusRingType = .none
        notesButton.image = NSImage(systemSymbolName: "note.text", accessibilityDescription: "Get Notes")
        notesButton.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 13, weight: .semibold)
        notesButton.imagePosition = .imageLeading
        notesButton.imageHugsTitle = true
        notesButton.heightAnchor.constraint(equalToConstant: 32).isActive = true
        notesButton.widthAnchor.constraint(greaterThanOrEqualToConstant: 112).isActive = true
        let notesBaseFill = palette.primaryBlue.withAlphaComponent(darkModeEnabled ? 0.20 : 0.14)
        let notesHoverFill = palette.primaryBlue.withAlphaComponent(darkModeEnabled ? 0.30 : 0.22)
        let notesBaseBorder = palette.primaryBlue.withAlphaComponent(darkModeEnabled ? 0.65 : 0.52)
        let notesHoverBorder = palette.primaryBlue.withAlphaComponent(darkModeEnabled ? 0.90 : 0.72)
        notesButton.onHoverChanged = { [weak notesButton] hovering in
            notesButton?.layer?.backgroundColor = (hovering ? notesHoverFill : notesBaseFill).cgColor
            notesButton?.layer?.borderColor = (hovering ? notesHoverBorder : notesBaseBorder).cgColor
        }
        notesButton.onHoverChanged?(false)
        aiCompanionNotesMeetingIdByView[ObjectIdentifier(notesButton)] = recording.id

        let notesStatusLabel = textLabel(aiCompanionNotesStatusText(for: recording), font: typography.fieldLabel, color: palette.textMuted)
        notesStatusLabel.alignment = .left
        notesStatusLabel.maximumNumberOfLines = 2
        notesStatusLabel.lineBreakMode = .byTruncatingTail
        aiCompanionNotesStatusLabelByView[ObjectIdentifier(notesButton)] = notesStatusLabel

        stack.addArrangedSubview(title)
        stack.addArrangedSubview(dateLabel)
        stack.addArrangedSubview(savedTimeLabel)
        stack.addArrangedSubview(notesButton)
        stack.addArrangedSubview(notesStatusLabel)

        card.addSubview(stack)
        NSLayoutConstraint.activate([
            stack.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 14),
            stack.trailingAnchor.constraint(equalTo: card.trailingAnchor, constant: -14),
            stack.topAnchor.constraint(equalTo: card.topAnchor, constant: 14),
            stack.bottomAnchor.constraint(equalTo: card.bottomAnchor, constant: -14)
        ])

        if !storeKitCoordinator.hasPremiumAccess {
            // Keep the content present (so layout stays stable), but visually lock it and route clicks to the paywall.
            notesButton.isEnabled = false

            let lockOverlay = NSVisualEffectView()
            lockOverlay.translatesAutoresizingMaskIntoConstraints = false
            lockOverlay.material = darkModeEnabled ? .hudWindow : .popover
            lockOverlay.blendingMode = .withinWindow
            lockOverlay.state = .active
            lockOverlay.wantsLayer = true
            lockOverlay.layer?.cornerRadius = 14
            lockOverlay.layer?.masksToBounds = true
            lockOverlay.layer?.backgroundColor = NSColor.black.withAlphaComponent(darkModeEnabled ? 0.30 : 0.12).cgColor
            card.addSubview(lockOverlay)

            let message = textLabel(
                "Premium required. Click to unlock AI Companion notes.",
                font: NSFont.systemFont(ofSize: 13, weight: .semibold),
                color: darkModeEnabled ? .white : .black
            )
            message.alignment = .center
            message.maximumNumberOfLines = 2
            message.lineBreakMode = .byWordWrapping
            lockOverlay.addSubview(message)

            let hit = HoverTrackingView()
            hit.translatesAutoresizingMaskIntoConstraints = false
            hit.wantsLayer = true
            hit.layer?.backgroundColor = NSColor.clear.cgColor
            hit.onClick = { [weak self] in
                self?.showPaywall()
            }
            hit.toolTip = "Premium required. Click to open paywall."
            lockOverlay.addSubview(hit)

            NSLayoutConstraint.activate([
                lockOverlay.leadingAnchor.constraint(equalTo: card.leadingAnchor),
                lockOverlay.trailingAnchor.constraint(equalTo: card.trailingAnchor),
                lockOverlay.topAnchor.constraint(equalTo: card.topAnchor),
                lockOverlay.bottomAnchor.constraint(equalTo: card.bottomAnchor),

                message.centerXAnchor.constraint(equalTo: lockOverlay.centerXAnchor),
                message.centerYAnchor.constraint(equalTo: lockOverlay.centerYAnchor),
                message.leadingAnchor.constraint(greaterThanOrEqualTo: lockOverlay.leadingAnchor, constant: 18),
                message.trailingAnchor.constraint(lessThanOrEqualTo: lockOverlay.trailingAnchor, constant: -18),

                hit.leadingAnchor.constraint(equalTo: lockOverlay.leadingAnchor),
                hit.trailingAnchor.constraint(equalTo: lockOverlay.trailingAnchor),
                hit.topAnchor.constraint(equalTo: lockOverlay.topAnchor),
                hit.bottomAnchor.constraint(equalTo: lockOverlay.bottomAnchor)
            ])
        }

        return card
    }

    @objc private func aiCompanionAudioTapped(_ sender: NSButton) {
        let senderId = ObjectIdentifier(sender)
        guard let url = aiCompanionAudioURLByView[senderId] else { return }

        // Toggle play/pause if the same card is tapped.
        if aiCompanionCurrentlyPlayingURL == url {
            if aiCompanionIsUsingSpeech {
                if aiCompanionSpeechSynthesizer.isSpeaking {
                    aiCompanionSpeechSynthesizer.stopSpeaking(at: .immediate)
                    aiCompanionIsUsingSpeech = false
                    sender.title = "Play Audio"
                    aiCompanionAudioStatusLabelByView[senderId]?.stringValue = "Stopped"
                } else {
                    aiCompanionStartSpeech(forButtonId: senderId)
                    sender.title = "Pause Audio"
                    aiCompanionAudioStatusLabelByView[senderId]?.stringValue = "Speaking..."
                }
                return
            } else if let player = aiCompanionAudioPlayer {
                if player.rate != 0 {
                    player.pause()
                    sender.title = "Play Audio"
                    aiCompanionAudioStatusLabelByView[senderId]?.stringValue = "Paused"
                } else {
                    player.play()
                    sender.title = "Pause Audio"
                    aiCompanionAudioStatusLabelByView[senderId]?.stringValue = "Playing..."
                }
                return
            } else if let player = aiCompanionLocalAudioPlayer {
                if player.isPlaying {
                    player.pause()
                    sender.title = "Play Audio"
                    aiCompanionAudioStatusLabelByView[senderId]?.stringValue = "Paused"
                } else {
                    player.play()
                    sender.title = "Pause Audio"
                    aiCompanionAudioStatusLabelByView[senderId]?.stringValue = "Playing..."
                }
                return
            }
        }

        // Stop any previous playback and remove observers.
        aiCompanionAudioPlayer?.pause()
        aiCompanionLocalAudioPlayer?.stop()
        aiCompanionLocalAudioPlayer = nil
        aiCompanionSpeechSynthesizer.stopSpeaking(at: .immediate)
        aiCompanionIsUsingSpeech = false
        aiCompanionNoProgressWorkItem?.cancel()
        aiCompanionNoProgressWorkItem = nil
        aiCompanionCurrentlySpeakingButtonId = nil
        aiCompanionTimeControlObserver = nil
        if let token = aiCompanionPlaybackEndObserver { NotificationCenter.default.removeObserver(token) }
        if let token = aiCompanionPlaybackFailedObserver { NotificationCenter.default.removeObserver(token) }
        aiCompanionPlaybackEndObserver = nil
        aiCompanionPlaybackFailedObserver = nil

        // Revert previous playing UI (if any).
        if let previousButton = aiCompanionCurrentlyPlayingButton {
            let previousId = ObjectIdentifier(previousButton)
            previousButton.title = "Play Audio"
            aiCompanionAudioStatusLabelByView[previousId]?.stringValue = "Not playing"
        }

        aiCompanionCurrentlyPlayingURL = url
        aiCompanionCurrentlyPlayingButton = sender
        sender.title = "Pause Audio"
        aiCompanionAudioStatusLabelByView[senderId]?.stringValue = "Checking audio..."

        aiCompanionAudioRequestID = UUID()
        let requestID = aiCompanionAudioRequestID

        let urlToCheck = url
        let senderButton = sender

        if urlToCheck.isFileURL {
            guard FileManager.default.fileExists(atPath: urlToCheck.path) else {
                senderButton.title = "Play Audio"
                aiCompanionAudioStatusLabelByView[senderId]?.stringValue = "Audio file missing"
                return
            }
            do {
                let player = try AVAudioPlayer(contentsOf: urlToCheck)
                player.volume = 1.0
                player.delegate = self
                player.prepareToPlay()
                let didPlay = player.play()
                guard didPlay else {
                    senderButton.title = "Play Audio"
                    aiCompanionAudioStatusLabelByView[senderId]?.stringValue = "Could not play recording"
                    return
                }
                aiCompanionLocalAudioPlayer = player
                aiCompanionAudioStatusLabelByView[senderId]?.stringValue = "Playing..."
            } catch {
                senderButton.title = "Play Audio"
                aiCompanionAudioStatusLabelByView[senderId]?.stringValue = "Failed: \(error.localizedDescription)"
            }
            return
        }

        var request = URLRequest(url: urlToCheck)
        request.setValue("bytes=0-0", forHTTPHeaderField: "Range") // lightweight probe
        request.timeoutInterval = 10

        URLSession.shared.dataTask(with: request) { [weak self] _, response, error in
            guard let self else { return }

            DispatchQueue.main.async {
                guard self.aiCompanionAudioRequestID == requestID else { return } // stale tap

                if let error {
                    senderButton.title = "Play Audio"
                    self.aiCompanionAudioTimeControlObserverResetForFailure()
                    self.aiCompanionStartSpeech(forButtonId: senderId)
                    return
                }

                guard let http = response as? HTTPURLResponse else {
                    senderButton.title = "Play Audio"
                    self.aiCompanionAudioTimeControlObserverResetForFailure()
                    self.aiCompanionStartSpeech(forButtonId: senderId)
                    return
                }

                let mime = http.mimeType?.lowercased() ?? ""
                let okStatus = (200...299).contains(http.statusCode) || http.statusCode == 206
                guard okStatus else {
                    senderButton.title = "Play Audio"
                    self.aiCompanionAudioTimeControlObserverResetForFailure()
                    self.aiCompanionStartSpeech(forButtonId: senderId)
                    return
                }

                if !mime.isEmpty && mime.hasPrefix("audio/") == false {
                    senderButton.title = "Play Audio"
                    self.aiCompanionAudioTimeControlObserverResetForFailure()
                    self.aiCompanionStartSpeech(forButtonId: senderId)
                    return
                }

                self.aiCompanionAudioStatusLabelByView[senderId]?.stringValue = "Loading..."

                let player = AVPlayer(url: urlToCheck)
                player.volume = 1.0
                self.aiCompanionAudioPlayer = player

                if let item = player.currentItem {
                    self.aiCompanionPlaybackEndObserver = NotificationCenter.default.addObserver(
                        forName: .AVPlayerItemDidPlayToEndTime,
                        object: item,
                        queue: .main
                    ) { [weak self] _ in
                        self?.aiCompanionAudioDidFinish()
                    }

                    self.aiCompanionPlaybackFailedObserver = NotificationCenter.default.addObserver(
                        forName: .AVPlayerItemFailedToPlayToEndTime,
                        object: item,
                        queue: .main
                    ) { [weak self] notification in
                        self?.aiCompanionAudioDidFail(notification: notification)
                    }
                }

                // Update the UI only when playback actually starts (helps diagnose "playing but no audio").
                self.aiCompanionTimeControlObserver = player.observe(\.timeControlStatus, options: [.initial, .new]) { [weak self] p, _ in
                    guard let self else { return }
                    guard self.aiCompanionCurrentlyPlayingURL == urlToCheck else { return }

                    switch p.timeControlStatus {
                    case .playing:
                        self.aiCompanionAudioStatusLabelByView[senderId]?.stringValue = "Playing..."
                    case .waitingToPlayAtSpecifiedRate:
                        self.aiCompanionAudioStatusLabelByView[senderId]?.stringValue = "Buffering..."
                    case .paused:
                        self.aiCompanionAudioStatusLabelByView[senderId]?.stringValue = "Paused"
                    @unknown default:
                        self.aiCompanionAudioStatusLabelByView[senderId]?.stringValue = "Playing..."
                    }
                }

                // If the remote file is silent/unplayable, AVPlayer can still report "playing".
                // After a short grace period, fall back to text-to-speech so you can always hear something.
                let startSeconds = player.currentTime().seconds
                player.play()
                let playerRef = player
                let urlRef = urlToCheck

                self.aiCompanionNoProgressWorkItem?.cancel()
                let workItem = DispatchWorkItem { [weak self] in
                    guard let self else { return }
                    guard self.aiCompanionAudioPlayer === playerRef else { return }
                    guard self.aiCompanionCurrentlyPlayingURL == urlRef else { return }
                    guard self.aiCompanionIsUsingSpeech == false else { return }

                    let nowSeconds = playerRef.currentTime().seconds
                    let progressed = startSeconds.isFinite && nowSeconds.isFinite && (nowSeconds - startSeconds) > 0.5
                    let actuallyPlaying = playerRef.timeControlStatus == .playing

                    if actuallyPlaying == false || progressed == false {
                        self.aiCompanionStartSpeech(forButtonId: senderId)
                    }
                }
                self.aiCompanionNoProgressWorkItem = workItem
                DispatchQueue.main.asyncAfter(deadline: .now() + 3, execute: workItem)
            }
        }.resume()
    }

    @objc private func aiCompanionTranscriptTapped(_ sender: NSButton) {
        let senderId = ObjectIdentifier(sender)
        guard let meetingId = aiCompanionTranscriptMeetingIdByView[senderId] else { return }
        guard let recording = aiCompanionLocalRecordings.first(where: { $0.id == meetingId }) else {
            aiCompanionTranscriptStatusLabelByView[senderId]?.stringValue = "Transcript unavailable (tap to retry)"
            showSimpleAlert(title: "Transcript unavailable", message: "Could not find recording details for this meeting.")
            return
        }

        if aiCompanionTranscriptStatus(for: recording) == .ready,
           let cached = recording.transcriptText?.trimmingCharacters(in: .whitespacesAndNewlines),
           cached.isEmpty == false {
            aiCompanionPresentTranscriptWindow(meetingTitle: recording.title, initialText: cached)
            aiCompanionTranscriptStatusLabelByView[senderId]?.stringValue = aiCompanionTranscriptStatusText(for: recording)
            return
        }

        aiCompanionTranscriptStatusLabelByView[senderId]?.stringValue = "Transcript processing..."

        let requestId = UUID()
        aiCompanionTranscriptCurrentRequestId = requestId

        aiCompanionPresentTranscriptWindow(meetingTitle: recording.title, initialText: "Transcript processing...")
        aiCompanionStartTranscriptProcessing(forMeetingID: meetingId, requestId: requestId, interactiveAuth: true, forceRegenerate: true)
    }

    private func aiCompanionStartTranscriptProcessing(
        forMeetingID meetingId: String,
        requestId: UUID?,
        interactiveAuth: Bool,
        forceRegenerate: Bool
    ) {
        if !forceRegenerate,
           let recording = aiCompanionLocalRecordings.first(where: { $0.id == meetingId }),
           aiCompanionTranscriptStatus(for: recording) == .ready {
            return
        }

        aiCompanionTranscriptTaskByMeetingId[meetingId]?.cancel()
        _ = aiCompanionUpdateRecording(meetingId: meetingId) { recording in
            recording.transcriptStatusRaw = MeetingTranscriptStatus.processing.rawValue
            recording.transcriptErrorMessage = nil
            if forceRegenerate {
                recording.transcriptText = nil
                recording.transcriptSourceRaw = nil
                recording.notesStatusRaw = MeetingNotesStatus.notRequested.rawValue
                recording.notesText = nil
                recording.notesErrorMessage = nil
            }
        }
        aiCompanionRefreshTranscriptStatusLabels(forMeetingID: meetingId)
        if selectedSidebarPage == .aiCompanion {
            pageCache[.aiCompanion] = nil
            showSidebarPage(.aiCompanion)
        }

        let presentingWindow = view.window
        let task = Task { [weak self] in
            guard let self else { return }
            defer { Task { @MainActor [weak self] in self?.aiCompanionTranscriptTaskByMeetingId[meetingId] = nil } }

            do {
                let result = try await self.aiCompanionFetchOrGenerateTranscript(
                    meetingId: meetingId,
                    interactiveAuth: interactiveAuth,
                    presentingWindow: presentingWindow
                )
                await MainActor.run {
                    guard requestId == nil || self.aiCompanionTranscriptCurrentRequestId == requestId else { return }
                    self.aiCompanionTranscriptProgressByMeetingId[meetingId] = nil
                    _ = self.aiCompanionUpdateRecording(meetingId: meetingId) { recording in
                        recording.transcriptStatusRaw = MeetingTranscriptStatus.ready.rawValue
                        recording.transcriptSourceRaw = result.source.rawValue
                        recording.transcriptText = result.text
                        recording.transcriptSegmentsJSON = result.segmentsJSON
                        recording.transcriptErrorMessage = nil
                    }
                    self.aiCompanionTranscriptTextView?.string = result.text
                    self.aiCompanionRefreshTranscriptStatusLabels(forMeetingID: meetingId)
                    if self.selectedSidebarPage == .aiCompanion {
                        self.pageCache[.aiCompanion] = nil
                        self.showSidebarPage(.aiCompanion)
                    }
                }
            } catch {
                await MainActor.run {
                    guard requestId == nil || self.aiCompanionTranscriptCurrentRequestId == requestId else { return }
                    self.aiCompanionTranscriptProgressByMeetingId[meetingId] = nil
                    let msg = error.localizedDescription.isEmpty ? "Failed to load transcript." : error.localizedDescription
                    _ = self.aiCompanionUpdateRecording(meetingId: meetingId) { recording in
                        recording.transcriptStatusRaw = MeetingTranscriptStatus.failed.rawValue
                        recording.transcriptErrorMessage = msg
                    }
                    self.aiCompanionTranscriptTextView?.string = "Transcript unavailable.\n\n\(msg)"
                    self.aiCompanionRefreshTranscriptStatusLabels(forMeetingID: meetingId)
                    if self.selectedSidebarPage == .aiCompanion {
                        self.pageCache[.aiCompanion] = nil
                        self.showSidebarPage(.aiCompanion)
                    }
                }
            }
        }
        aiCompanionTranscriptTaskByMeetingId[meetingId] = task
    }

    private func aiCompanionFetchOrGenerateTranscript(
        meetingId: String,
        interactiveAuth: Bool,
        presentingWindow: NSWindow?
    ) async throws -> (text: String, segmentsJSON: String?, source: MeetingTranscriptSource) {
        guard let recording = aiCompanionLocalRecordings.first(where: { $0.id == meetingId }) else {
            throw NSError(domain: "AiCompanionTranscript", code: 10, userInfo: [NSLocalizedDescriptionKey: "Recording not found."])
        }
        _ = interactiveAuth
        _ = presentingWindow

        let micURL: URL? = recording.microphoneAudioFilePath
            .map { URL(fileURLWithPath: $0) }
            .flatMap { FileManager.default.fileExists(atPath: $0.path) ? $0 : nil }
        let systemURL: URL? = recording.systemAudioFilePath
            .map { URL(fileURLWithPath: $0) }
            .flatMap { FileManager.default.fileExists(atPath: $0.path) ? $0 : nil }

        let hasPerChannel = micURL != nil || systemURL != nil

        let mixedURL = URL(fileURLWithPath: recording.audioFilePath)
        if hasPerChannel == false {
            guard FileManager.default.fileExists(atPath: mixedURL.path) else {
                throw NSError(domain: "AiCompanionTranscript", code: 12, userInfo: [NSLocalizedDescriptionKey: "Local meeting audio is missing."])
            }
        }

        let preferredLocales = aiCompanionPreferredTranscriptionLocales()
        let progressHandler: @Sendable (MeetingTranscriptionProgress) -> Void = { [weak self] progress in
            Task { @MainActor [weak self] in
                guard let self else { return }
                let text: String
                if progress.totalChunks > 0 {
                    text = "Transcribing \(progress.completedChunks)/\(progress.totalChunks) chunks..."
                } else {
                    text = "Transcript processing..."
                }
                self.aiCompanionTranscriptProgressByMeetingId[meetingId] = text
                self.aiCompanionRefreshTranscriptStatusLabels(forMeetingID: meetingId)
            }
        }

        let segments: [TranscriptSegment]
        let source: MeetingTranscriptSource
        if hasPerChannel {
            segments = try await meetingTranscriptionService.transcribeMeeting(
                micURL: micURL,
                systemURL: systemURL,
                locales: preferredLocales,
                onProgress: progressHandler
            )
            source = .localMultiChannelAppleSpeech
        } else {
            // Backward compatibility: old recordings only have a mixed file.
            segments = try await meetingTranscriptionService.transcribeMeeting(
                micURL: nil,
                systemURL: mixedURL,
                locales: preferredLocales,
                onProgress: progressHandler
            )
            source = .localAudioAppleSpeech
        }

        let renderedText = segments.renderedTimelineText().trimmingCharacters(in: .whitespacesAndNewlines)
        guard renderedText.isEmpty == false else {
            throw NSError(domain: "AiCompanionTranscript", code: 14, userInfo: [NSLocalizedDescriptionKey: "Generated transcript was empty."])
        }

        let encoder = JSONEncoder()
        let segmentsJSON = (try? encoder.encode(segments)).flatMap { String(data: $0, encoding: .utf8) }

        return (renderedText, segmentsJSON, source)
    }

    private func aiCompanionPreferredTranscriptionLocales() -> [Locale] {
        let defaults = UserDefaults.standard
        let selectedIdentifiers = [
            defaults.string(forKey: aiCompanionPreferredLanguage1DefaultsKey),
            defaults.string(forKey: aiCompanionPreferredLanguage2DefaultsKey)
        ]
            .compactMap { $0?.trimmingCharacters(in: .whitespacesAndNewlines) }
            .filter { $0.isEmpty == false }

        var locales: [Locale] = []
        var seen = Set<String>()

        func appendIdentifier(_ identifier: String) {
            let locale = Locale(identifier: identifier)
            guard SFSpeechRecognizer(locale: locale)?.isAvailable == true else { return }
            let normalized = identifier.replacingOccurrences(of: "_", with: "-").lowercased()
            guard seen.contains(normalized) == false else { return }
            seen.insert(normalized)
            locales.append(locale)
        }

        for identifier in selectedIdentifiers {
            appendIdentifier(identifier)
        }

        // Safe defaults for mixed-language meetings if user has not configured preferences yet.
        appendIdentifier(Locale.current.identifier)
        appendIdentifier("en-US")

        if locales.isEmpty {
            return [Locale(identifier: "en-US")]
        }
        return locales
    }

    private func aiCompanionSupportedSpeechLocaleOptions() -> [SpeechLocaleOption] {
        let supported = SFSpeechRecognizer.supportedLocales()
        let currentIdentifier = Locale.current.identifier
        let englishUSIdentifier = "en-US"
        var candidates = Set<String>(supported.map { $0.identifier })
        for preferred in Locale.preferredLanguages {
            candidates.insert(preferred)
        }
        candidates.insert(currentIdentifier)
        candidates.insert(englishUSIdentifier)

        return candidates
            .map { identifier -> SpeechLocaleOption in
                let locale = Locale(identifier: identifier)
                let languageCode = locale.languageCode ?? Locale.components(fromIdentifier: identifier)[NSLocale.Key.languageCode.rawValue]
                let languageName = Locale.current.localizedString(forIdentifier: identifier)
                    ?? languageCode.flatMap { Locale.current.localizedString(forLanguageCode: $0) }
                    ?? identifier
                return SpeechLocaleOption(identifier: identifier, displayName: "\(languageName) (\(identifier))")
            }
            .sorted { $0.displayName.localizedCaseInsensitiveCompare($1.displayName) == .orderedAscending }
    }

    private func updateAiCompanionPreferredSpeechLanguages(primary: String, secondary: String?) {
        let normalizedPrimary = primary.trimmingCharacters(in: .whitespacesAndNewlines)
        guard normalizedPrimary.isEmpty == false else { return }
        UserDefaults.standard.set(normalizedPrimary, forKey: aiCompanionPreferredLanguage1DefaultsKey)

        let cleanedSecondary = secondary?.trimmingCharacters(in: .whitespacesAndNewlines)
        if let cleanedSecondary, cleanedSecondary.isEmpty == false {
            let normalizedPrimaryKey = normalizedPrimary.replacingOccurrences(of: "_", with: "-").lowercased()
            let normalizedSecondaryKey = cleanedSecondary.replacingOccurrences(of: "_", with: "-").lowercased()
            if normalizedPrimaryKey == normalizedSecondaryKey {
                UserDefaults.standard.removeObject(forKey: aiCompanionPreferredLanguage2DefaultsKey)
            } else {
                UserDefaults.standard.set(cleanedSecondary, forKey: aiCompanionPreferredLanguage2DefaultsKey)
            }
        } else {
            UserDefaults.standard.removeObject(forKey: aiCompanionPreferredLanguage2DefaultsKey)
        }
    }

    @objc private func aiCompanionNotesTapped(_ sender: NSButton) {
        guard storeKitCoordinator.hasPremiumAccess else {
            showPaywall()
            return
        }
        let senderId = ObjectIdentifier(sender)
        guard let meetingId = aiCompanionNotesMeetingIdByView[senderId] else { return }
        guard let recording = aiCompanionLocalRecordings.first(where: { $0.id == meetingId }) else {
            aiCompanionNotesStatusLabelByView[senderId]?.stringValue = "Notes unavailable (tap to retry)"
            showSimpleAlert(title: "Notes unavailable", message: "Could not find recording details for this meeting.")
            return
        }

        if aiCompanionNotesStatus(for: recording) == .ready,
           let cached = recording.notesText?.trimmingCharacters(in: .whitespacesAndNewlines),
           cached.isEmpty == false {
            aiCompanionPresentNotesWindow(meetingTitle: recording.title, initialText: cached)
            aiCompanionNotesStatusLabelByView[senderId]?.stringValue = aiCompanionNotesStatusText(for: recording)
            return
        }

        aiCompanionNotesStatusLabelByView[senderId]?.stringValue = "Preparing notes, please wait..."
        let requestId = UUID()
        aiCompanionNotesCurrentRequestId = requestId
        // Do NOT open the notes popup yet. It will be opened automatically
        // once the notes are ready (or stay closed if generation fails).
        aiCompanionStartNotesProcessing(forMeetingID: meetingId, requestId: requestId, autoPresentOnReady: true)
    }

    private func aiCompanionStartNotesProcessing(
        forMeetingID meetingId: String,
        requestId: UUID?,
        autoPresentOnReady: Bool = false
    ) {
        aiCompanionNotesTaskByMeetingId[meetingId]?.cancel()
        _ = aiCompanionUpdateRecording(meetingId: meetingId) { recording in
            recording.notesStatusRaw = MeetingNotesStatus.processing.rawValue
            recording.notesErrorMessage = nil
            recording.notesText = nil
        }
        aiCompanionNotesProgressByMeetingId[meetingId] = "Preparing notes, please wait..."
        aiCompanionRefreshNotesStatusLabels(forMeetingID: meetingId)
        if selectedSidebarPage == .aiCompanion {
            pageCache[.aiCompanion] = nil
            showSidebarPage(.aiCompanion)
        }

        let presentingWindow = view.window
        let task = Task { [weak self] in
            guard let self else { return }
            defer { Task { @MainActor [weak self] in self?.aiCompanionNotesTaskByMeetingId[meetingId] = nil } }

            do {
                let notes = try await self.aiCompanionGenerateNotesForMeeting(meetingId: meetingId, presentingWindow: presentingWindow)
                await MainActor.run {
                    guard requestId == nil || self.aiCompanionNotesCurrentRequestId == requestId else { return }
                    self.aiCompanionNotesProgressByMeetingId[meetingId] = nil
                    _ = self.aiCompanionUpdateRecording(meetingId: meetingId) { recording in
                        recording.notesStatusRaw = MeetingNotesStatus.ready.rawValue
                        recording.notesText = notes
                        recording.notesErrorMessage = nil
                    }
                    self.aiCompanionNotesTextView?.string = notes
                    self.aiCompanionRefreshNotesStatusLabels(forMeetingID: meetingId)
                    if self.selectedSidebarPage == .aiCompanion {
                        self.pageCache[.aiCompanion] = nil
                        self.showSidebarPage(.aiCompanion)
                    }
                    if autoPresentOnReady {
                        let title = self.aiCompanionLocalRecordings.first(where: { $0.id == meetingId })?.title ?? "Meeting"
                        self.aiCompanionPresentNotesWindow(meetingTitle: title, initialText: notes)
                    }
                }
            } catch {
                await MainActor.run {
                    guard requestId == nil || self.aiCompanionNotesCurrentRequestId == requestId else { return }
                    self.aiCompanionNotesProgressByMeetingId[meetingId] = nil
                    let msg = error.localizedDescription.isEmpty ? "Failed to generate notes." : error.localizedDescription
                    _ = self.aiCompanionUpdateRecording(meetingId: meetingId) { recording in
                        recording.notesStatusRaw = MeetingNotesStatus.failed.rawValue
                        recording.notesErrorMessage = msg
                    }
                    self.aiCompanionNotesTextView?.string = "Notes unavailable.\n\n\(msg)"
                    self.aiCompanionRefreshNotesStatusLabels(forMeetingID: meetingId)
                    if self.selectedSidebarPage == .aiCompanion {
                        self.pageCache[.aiCompanion] = nil
                        self.showSidebarPage(.aiCompanion)
                    }
                }
            }
        }
        aiCompanionNotesTaskByMeetingId[meetingId] = task
    }

    private func aiCompanionGenerateNotesForMeeting(meetingId: String, presentingWindow: NSWindow?) async throws -> String {
        let transcriptText: String
        if let existing = aiCompanionLocalRecordings.first(where: { $0.id == meetingId })?.transcriptText?.trimmingCharacters(in: .whitespacesAndNewlines),
           existing.isEmpty == false {
            transcriptText = existing
        } else {
            let transcript = try await aiCompanionFetchOrGenerateTranscript(
                meetingId: meetingId,
                interactiveAuth: true,
                presentingWindow: presentingWindow
            )
            await MainActor.run {
                _ = self.aiCompanionUpdateRecording(meetingId: meetingId) { recording in
                    recording.transcriptStatusRaw = MeetingTranscriptStatus.ready.rawValue
                    recording.transcriptSourceRaw = transcript.source.rawValue
                    recording.transcriptText = transcript.text
                    recording.transcriptSegmentsJSON = transcript.segmentsJSON
                    recording.transcriptErrorMessage = nil
                }
                self.aiCompanionRefreshTranscriptStatusLabels(forMeetingID: meetingId)
            }
            transcriptText = transcript.text
        }

        await MainActor.run {
            self.aiCompanionNotesProgressByMeetingId[meetingId] = "Preparing notes, please wait..."
            self.aiCompanionRefreshNotesStatusLabels(forMeetingID: meetingId)
        }
        let defaults = UserDefaults.standard
        let preferred1 = defaults.string(forKey: aiCompanionPreferredLanguage1DefaultsKey)
        let preferred2 = defaults.string(forKey: aiCompanionPreferredLanguage2DefaultsKey)
        return try await meetingNotesService.generateNotes(
            from: transcriptText,
            preferredLanguageIdentifier1: preferred1,
            preferredLanguageIdentifier2: preferred2
        )
    }

    @objc private func aiCompanionStopRecordingTapped(_ sender: NSButton) {
        finishActiveMeetingRecording()
    }

    private func aiCompanionAudioTimeControlObserverResetForFailure() {
        aiCompanionAudioPlayer?.pause()
        aiCompanionAudioPlayer = nil
        aiCompanionLocalAudioPlayer?.stop()
        aiCompanionLocalAudioPlayer = nil
        aiCompanionTimeControlObserver = nil

        if let token = aiCompanionPlaybackEndObserver { NotificationCenter.default.removeObserver(token) }
        if let token = aiCompanionPlaybackFailedObserver { NotificationCenter.default.removeObserver(token) }
        aiCompanionPlaybackEndObserver = nil
        aiCompanionPlaybackFailedObserver = nil
    }

    private func aiCompanionStartSpeech(forButtonId buttonId: ObjectIdentifier) {
        // Stop any remote audio playback first.
        aiCompanionAudioPlayer?.pause()
        aiCompanionAudioPlayer = nil
        aiCompanionTimeControlObserver = nil
        if let token = aiCompanionPlaybackEndObserver { NotificationCenter.default.removeObserver(token) }
        if let token = aiCompanionPlaybackFailedObserver { NotificationCenter.default.removeObserver(token) }
        aiCompanionPlaybackEndObserver = nil
        aiCompanionPlaybackFailedObserver = nil

        aiCompanionNoProgressWorkItem?.cancel()
        aiCompanionNoProgressWorkItem = nil

        aiCompanionIsUsingSpeech = true
        aiCompanionCurrentlySpeakingButtonId = buttonId

        if let button = aiCompanionCurrentlyPlayingButton, ObjectIdentifier(button) == buttonId {
            button.title = "Pause Audio"
        }

        aiCompanionAudioStatusLabelByView[buttonId]?.stringValue = "Speaking..."

        let text = aiCompanionSpeechTextByView[buttonId] ?? "Ended meeting."
        let utterance = AVSpeechUtterance(string: text)
        utterance.rate = 0.5
        utterance.volume = 1.0

        aiCompanionSpeechSynthesizer.stopSpeaking(at: .immediate)
        aiCompanionSpeechSynthesizer.speak(utterance)
    }

    private func aiCompanionAudioDidFinish() {
        guard let button = aiCompanionCurrentlyPlayingButton else { return }
        let buttonId = ObjectIdentifier(button)

        aiCompanionSpeechSynthesizer.stopSpeaking(at: .immediate)
        aiCompanionIsUsingSpeech = false
        aiCompanionCurrentlySpeakingButtonId = nil

        button.title = "Play Audio"
        aiCompanionAudioStatusLabelByView[buttonId]?.stringValue = "Finished"

        aiCompanionAudioPlayer?.pause()
        aiCompanionAudioPlayer = nil
        aiCompanionLocalAudioPlayer?.stop()
        aiCompanionLocalAudioPlayer = nil
        aiCompanionCurrentlyPlayingURL = nil
        aiCompanionCurrentlyPlayingButton = nil

        if let token = aiCompanionPlaybackEndObserver { NotificationCenter.default.removeObserver(token) }
        if let token = aiCompanionPlaybackFailedObserver { NotificationCenter.default.removeObserver(token) }
        aiCompanionPlaybackEndObserver = nil
        aiCompanionPlaybackFailedObserver = nil
        aiCompanionTimeControlObserver = nil
    }

    private func aiCompanionAudioDidFail(notification: Notification) {
        guard let button = aiCompanionCurrentlyPlayingButton else { return }
        let buttonId = ObjectIdentifier(button)

        aiCompanionSpeechSynthesizer.stopSpeaking(at: .immediate)
        aiCompanionIsUsingSpeech = false
        aiCompanionCurrentlySpeakingButtonId = nil

        button.title = "Play Audio"

        var message = "Failed to play audio"
        if let item = notification.object as? AVPlayerItem, let error = item.error {
            message = "Failed: \(error.localizedDescription)"
        }
        aiCompanionAudioStatusLabelByView[buttonId]?.stringValue = message

        aiCompanionAudioPlayer?.pause()
        aiCompanionAudioPlayer = nil
        aiCompanionLocalAudioPlayer?.stop()
        aiCompanionLocalAudioPlayer = nil
        aiCompanionCurrentlyPlayingURL = nil
        aiCompanionCurrentlyPlayingButton = nil

        if let token = aiCompanionPlaybackEndObserver { NotificationCenter.default.removeObserver(token) }
        if let token = aiCompanionPlaybackFailedObserver { NotificationCenter.default.removeObserver(token) }
        aiCompanionPlaybackEndObserver = nil
        aiCompanionPlaybackFailedObserver = nil
        aiCompanionTimeControlObserver = nil
    }

    @MainActor
    private func aiCompanionPresentTranscriptWindow(meetingTitle: String, initialText: String) {
        if let window = aiCompanionTranscriptWindow, let textView = aiCompanionTranscriptTextView {
            window.title = "Transcript - \(meetingTitle)"
            textView.string = initialText
            window.makeKeyAndOrderFront(nil)
            NSApp.activate(ignoringOtherApps: true)
            return
        }

        let windowWidth: CGFloat = 640
        let windowHeight: CGFloat = 560
        let window = NSWindow(
            contentRect: NSRect(x: 0, y: 0, width: windowWidth, height: windowHeight),
            styleMask: [.titled, .closable, .resizable],
            backing: .buffered,
            defer: false
        )
        window.isReleasedWhenClosed = false
        window.title = "Transcript - \(meetingTitle)"
        window.center()

        let root = NSView()
        root.translatesAutoresizingMaskIntoConstraints = false

        let scroll = NSScrollView()
        scroll.translatesAutoresizingMaskIntoConstraints = false
        scroll.drawsBackground = false
        scroll.hasVerticalScroller = true

        let textView = NSTextView()
        textView.isEditable = false
        textView.isSelectable = true
        textView.backgroundColor = .clear
        textView.font = NSFont.systemFont(ofSize: 13, weight: .regular)
        textView.string = initialText
        textView.textContainer?.widthTracksTextView = true

        scroll.documentView = textView
        root.addSubview(scroll)

        NSLayoutConstraint.activate([
            scroll.leadingAnchor.constraint(equalTo: root.leadingAnchor),
            scroll.trailingAnchor.constraint(equalTo: root.trailingAnchor),
            scroll.topAnchor.constraint(equalTo: root.topAnchor),
            scroll.bottomAnchor.constraint(equalTo: root.bottomAnchor)
        ])

        window.contentView = root
        window.makeKeyAndOrderFront(nil)
        NSApp.activate(ignoringOtherApps: true)

        aiCompanionTranscriptWindow = window
        aiCompanionTranscriptTextView = textView
    }

    @MainActor
    private func aiCompanionPresentNotesWindow(meetingTitle: String, initialText: String) {
        guard let hostWindow = view.window else { return }
        let hostIsDarkMode = darkModeEnabled
        let panelAppearanceName: NSAppearance.Name = hostIsDarkMode ? .darkAqua : .aqua
        let outerBackgroundColor: NSColor = hostIsDarkMode ? .windowBackgroundColor : NSColor(calibratedWhite: 0.98, alpha: 1.0)
        let headerBackgroundColor: NSColor = hostIsDarkMode ? .controlBackgroundColor : NSColor(calibratedWhite: 0.93, alpha: 1.0)

        if let panel = aiCompanionNotesPanel, let textView = aiCompanionNotesTextView {
            panel.title = "Notes - \(meetingTitle)"
            panel.appearance = NSAppearance(named: panelAppearanceName)
            panel.backgroundColor = outerBackgroundColor
            textView.string = initialText
            aiCompanionNotesRootView?.layer?.backgroundColor = outerBackgroundColor.cgColor
            aiCompanionNotesHeaderView?.layer?.backgroundColor = headerBackgroundColor.cgColor
            aiCompanionNotesTitleLabel?.textColor = hostIsDarkMode ? .labelColor : .black
            aiCompanionNotesSubtitleLabel?.stringValue = meetingTitle
            if hostWindow.attachedSheet !== panel {
                hostWindow.beginSheet(panel, completionHandler: nil)
            }
            aiCompanionStartNotesOutsideClickMonitor()
            panel.makeKeyAndOrderFront(nil)
            NSApp.activate(ignoringOtherApps: true)
            return
        }

        let panelWidth: CGFloat = 720
        let panelHeight: CGFloat = 540
        let panel = NSPanel(
            contentRect: NSRect(x: 0, y: 0, width: panelWidth, height: panelHeight),
            styleMask: [.titled, .closable],
            backing: .buffered,
            defer: false
        )
        panel.isReleasedWhenClosed = false
        panel.title = "Notes - \(meetingTitle)"
        panel.isFloatingPanel = false
        panel.hidesOnDeactivate = false
        panel.delegate = self
        panel.appearance = NSAppearance(named: panelAppearanceName)
        panel.backgroundColor = outerBackgroundColor
        panel.standardWindowButton(.zoomButton)?.isHidden = true
        panel.standardWindowButton(.miniaturizeButton)?.isHidden = true

        let root = NSView()
        root.translatesAutoresizingMaskIntoConstraints = false
        root.wantsLayer = true
        root.layer?.backgroundColor = outerBackgroundColor.cgColor

        let header = NSView()
        header.translatesAutoresizingMaskIntoConstraints = false
        header.wantsLayer = true
        header.layer?.backgroundColor = headerBackgroundColor.cgColor
        header.layer?.cornerRadius = 10

        let headingColor: NSColor = hostIsDarkMode ? .labelColor : .black
        let titleLabel = textLabel("Meeting Notes", font: NSFont.systemFont(ofSize: 15, weight: .semibold), color: headingColor)
        titleLabel.translatesAutoresizingMaskIntoConstraints = false
        let subtitleLabel = textLabel(meetingTitle, font: NSFont.systemFont(ofSize: 12, weight: .regular), color: .secondaryLabelColor)
        subtitleLabel.translatesAutoresizingMaskIntoConstraints = false
        subtitleLabel.lineBreakMode = .byTruncatingTail

        let scroll = NSScrollView()
        scroll.translatesAutoresizingMaskIntoConstraints = false
        scroll.drawsBackground = true
        scroll.backgroundColor = NSColor.textBackgroundColor
        scroll.hasVerticalScroller = true
        scroll.hasHorizontalScroller = false
        scroll.borderType = .bezelBorder

        let textView = NSTextView()
        textView.isEditable = false
        textView.isSelectable = true
        textView.backgroundColor = NSColor.textBackgroundColor
        textView.textColor = NSColor.labelColor
        textView.font = NSFont.systemFont(ofSize: 13, weight: .regular)
        textView.string = initialText
        textView.textContainer?.widthTracksTextView = true
        textView.textContainerInset = NSSize(width: 10, height: 10)

        let copyButton = NSButton(title: "Copy", target: self, action: #selector(aiCompanionCopyNotesTapped(_:)))
        copyButton.translatesAutoresizingMaskIntoConstraints = false
        copyButton.bezelStyle = .rounded

        let closeButton = NSButton(title: "Close", target: self, action: #selector(aiCompanionCloseNotesTapped(_:)))
        closeButton.translatesAutoresizingMaskIntoConstraints = false
        closeButton.bezelStyle = .rounded

        scroll.documentView = textView
        header.addSubview(titleLabel)
        header.addSubview(subtitleLabel)
        header.addSubview(copyButton)
        header.addSubview(closeButton)
        root.addSubview(header)
        root.addSubview(scroll)

        NSLayoutConstraint.activate([
            header.topAnchor.constraint(equalTo: root.topAnchor, constant: 12),
            header.leadingAnchor.constraint(equalTo: root.leadingAnchor, constant: 16),
            header.trailingAnchor.constraint(equalTo: root.trailingAnchor, constant: -16),

            titleLabel.topAnchor.constraint(equalTo: header.topAnchor, constant: 12),
            titleLabel.leadingAnchor.constraint(equalTo: header.leadingAnchor, constant: 12),
            titleLabel.trailingAnchor.constraint(lessThanOrEqualTo: copyButton.leadingAnchor, constant: -12),

            subtitleLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 4),
            subtitleLabel.leadingAnchor.constraint(equalTo: header.leadingAnchor, constant: 12),
            subtitleLabel.trailingAnchor.constraint(lessThanOrEqualTo: copyButton.leadingAnchor, constant: -12),
            subtitleLabel.bottomAnchor.constraint(equalTo: header.bottomAnchor, constant: -12),

            copyButton.centerYAnchor.constraint(equalTo: header.centerYAnchor),
            copyButton.trailingAnchor.constraint(equalTo: closeButton.leadingAnchor, constant: -8),

            closeButton.centerYAnchor.constraint(equalTo: header.centerYAnchor),
            closeButton.trailingAnchor.constraint(equalTo: header.trailingAnchor, constant: -12),

            scroll.topAnchor.constraint(equalTo: header.bottomAnchor, constant: 12),
            scroll.leadingAnchor.constraint(equalTo: root.leadingAnchor, constant: 16),
            scroll.trailingAnchor.constraint(equalTo: root.trailingAnchor, constant: -16),
            scroll.bottomAnchor.constraint(equalTo: root.bottomAnchor, constant: -16)
        ])

        panel.contentView = root
        hostWindow.beginSheet(panel, completionHandler: nil)
        aiCompanionStartNotesOutsideClickMonitor()
        panel.makeKeyAndOrderFront(nil)
        NSApp.activate(ignoringOtherApps: true)

        aiCompanionNotesPanel = panel
        aiCompanionNotesRootView = root
        aiCompanionNotesHeaderView = header
        aiCompanionNotesTitleLabel = titleLabel
        aiCompanionNotesSubtitleLabel = subtitleLabel
        aiCompanionNotesTextView = textView
        aiCompanionNotesCopyButton = copyButton
        aiCompanionNotesCloseButton = closeButton
    }

    @objc private func aiCompanionCopyNotesTapped(_ sender: NSButton) {
        guard let notes = aiCompanionNotesTextView?.string, notes.isEmpty == false else { return }
        NSPasteboard.general.clearContents()
        NSPasteboard.general.setString(notes, forType: .string)
        sender.title = "Copied"
        DispatchQueue.main.asyncAfter(deadline: .now() + 1.2) { [weak self] in
            guard self?.aiCompanionNotesCopyButton === sender else { return }
            sender.title = "Copy"
        }
    }

    @objc private func aiCompanionCloseNotesTapped(_ sender: NSButton) {
        aiCompanionCloseNotesPanel()
    }

    private func aiCompanionStartNotesOutsideClickMonitor() {
        guard aiCompanionNotesOutsideClickMonitor == nil else { return }
        aiCompanionNotesOutsideClickMonitor = NSEvent.addLocalMonitorForEvents(
            matching: [.leftMouseDown, .rightMouseDown, .otherMouseDown]
        ) { [weak self] event in
            guard let self, let panel = self.aiCompanionNotesPanel else { return event }
            if event.window === panel { return event }
            self.aiCompanionCloseNotesPanel()
            return event
        }
    }

    private func aiCompanionStopNotesOutsideClickMonitor() {
        guard let monitor = aiCompanionNotesOutsideClickMonitor else { return }
        NSEvent.removeMonitor(monitor)
        aiCompanionNotesOutsideClickMonitor = nil
    }

    private func aiCompanionCloseNotesPanel() {
        guard let panel = aiCompanionNotesPanel else { return }
        aiCompanionStopNotesOutsideClickMonitor()
        if let hostWindow = view.window, hostWindow.attachedSheet === panel {
            hostWindow.endSheet(panel)
        }
        panel.orderOut(nil)
    }

    private func aiCompanionMeetMeetingCode(from meetURL: URL) -> String? {
        // Typical: https://meet.google.com/abc-defg-hij
        // But scheduled events can include trailing slashes and extra segments/query params.
        guard let host = meetURL.host?.lowercased(),
              host == "meet.google.com" || host.hasSuffix(".meet.google.com") else { return nil }

        // Prefer path segments (ignoring the "/" components that URL.pathComponents includes).
        let rawSegments = meetURL.pathComponents
            .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
            .filter { $0.isEmpty == false && $0 != "/" }

        for segment in rawSegments {
            if isValidMeetMeetingCode(segment) {
                return segment.lowercased()
            }
        }

        // Fallback: handle weird path formats by scanning the trimmed path.
        let trimmedPath = meetURL.path.trimmingCharacters(in: CharacterSet(charactersIn: "/"))
        if let first = trimmedPath.split(separator: "/").first.map(String.init),
           isValidMeetMeetingCode(first) {
            return first.lowercased()
        }

        return nil
    }

    private func aiCompanionSelectConferenceRecord(for meeting: ScheduledMeeting, from records: [ConferenceRecord]) -> ConferenceRecord? {
        // Prefer a record whose time window overlaps the calendar meeting.
        let overlapping = records.filter { r in
            guard let start = r.startTime, let end = r.endTime else { return false }
            return start <= meeting.endDate && end >= meeting.startDate
        }
        if let best = overlapping.sorted(by: { ($0.endTime ?? .distantPast) > ($1.endTime ?? .distantPast) }).first {
            return best
        }
        // Fallback: choose the most recent one we can.
        return records.sorted(by: { ($0.startTime ?? .distantPast) > ($1.startTime ?? .distantPast) }).first
    }

    private func aiCompanionSelectTranscript(for meeting: ScheduledMeeting, from transcripts: [Transcript]) -> Transcript? {
        let overlapping = transcripts.filter { t in
            guard let start = t.startTime, let end = t.endTime else { return false }
            return start <= meeting.endDate && end >= meeting.startDate
        }
        if let best = overlapping.sorted(by: { ($0.endTime ?? .distantPast) > ($1.endTime ?? .distantPast) }).first {
            return best
        }
        return transcripts.sorted(by: { ($0.startTime ?? .distantPast) > ($1.startTime ?? .distantPast) }).first
    }

    private func aiCompanionFormatTranscriptText(entries: [TranscriptEntry]) -> String {
        let lines = entries.compactMap { entry -> String? in
            guard let raw = entry.text else { return nil }
            let t = raw.trimmingCharacters(in: .whitespacesAndNewlines)
            guard t.isEmpty == false else { return nil }

            let speaker = entry.participant?.trimmingCharacters(in: .whitespacesAndNewlines)
            guard let speaker, speaker.isEmpty == false else { return t }
            return "\(speaker): \(t)"
        }

        if lines.isEmpty { return "(No transcript entries found.)" }
        return lines.joined(separator: "\n")
    }

    private func aiCompanionFetchTranscriptText(for meeting: ScheduledMeeting, accessToken: String) async throws -> String {
        guard let meetingCode = aiCompanionMeetMeetingCode(from: meeting.meetURL) else {
            throw NSError(
                domain: "AiCompanionTranscript",
                code: 1,
                userInfo: [NSLocalizedDescriptionKey: "Couldn't determine Meet meeting code from URL."]
            )
        }

        // Resolve `spaces/{meetingCode}` into a stable space resource name (`spaces/{spaceId}`).
        let space = try await googleMeetClient.getSpace(accessToken: accessToken, spaceNameOrMeetingCode: "spaces/\(meetingCode)")
        let spaceName = space.name ?? "spaces/\(meetingCode)"

        let records = try await googleMeetClient.listConferenceRecords(accessToken: accessToken, spaceResourceName: spaceName)
        guard let conferenceRecord = aiCompanionSelectConferenceRecord(for: meeting, from: records),
              let conferenceRecordName = conferenceRecord.name else {
            throw NSError(
                domain: "AiCompanionTranscript",
                code: 2,
                userInfo: [NSLocalizedDescriptionKey: "No conference record found for this meeting."]
            )
        }

        let transcripts = try await googleMeetClient.listTranscripts(accessToken: accessToken, conferenceRecordName: conferenceRecordName)
        guard let transcript = aiCompanionSelectTranscript(for: meeting, from: transcripts),
              let transcriptName = transcript.name else {
            throw NSError(
                domain: "AiCompanionTranscript",
                code: 3,
                userInfo: [NSLocalizedDescriptionKey: "No transcript found for this meeting."]
            )
        }

        let entries = try await googleMeetClient.listTranscriptEntries(accessToken: accessToken, transcriptName: transcriptName)
        return aiCompanionFormatTranscriptText(entries: entries)
    }

    private func makePlaceholderPage(title: String, subtitle: String) -> NSView {
        let panel = NSView()
        panel.translatesAutoresizingMaskIntoConstraints = false
        let titleLabel = textLabel(title, font: typography.pageTitle, color: palette.textPrimary)
        titleLabel.translatesAutoresizingMaskIntoConstraints = false
        let sub = textLabel(subtitle, font: typography.fieldLabel, color: palette.textSecondary)
        sub.translatesAutoresizingMaskIntoConstraints = false
        panel.addSubview(titleLabel)
        panel.addSubview(sub)
        NSLayoutConstraint.activate([
            titleLabel.leadingAnchor.constraint(equalTo: panel.leadingAnchor, constant: 28),
            titleLabel.topAnchor.constraint(equalTo: panel.topAnchor),
            sub.leadingAnchor.constraint(equalTo: titleLabel.leadingAnchor),
            sub.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 8)
        ])
        return panel
    }

    private func makeSettingsPageContent() -> NSView {
        let panel = NSView()
        panel.translatesAutoresizingMaskIntoConstraints = false

        let scroll = NSScrollView()
        scroll.translatesAutoresizingMaskIntoConstraints = false
        scroll.drawsBackground = false
        scroll.hasHorizontalScroller = false
        scroll.hasVerticalScroller = true
        scroll.autohidesScrollers = true
        scroll.borderType = .noBorder
        scroll.scrollerStyle = .overlay
        scroll.automaticallyAdjustsContentInsets = false
        let clip = TopAlignedClipView()
        clip.drawsBackground = false
        scroll.contentView = clip
        panel.addSubview(scroll)

        let content = NSView()
        content.translatesAutoresizingMaskIntoConstraints = false
        scroll.documentView = content

        let card = roundedContainer(cornerRadius: 16, color: palette.sectionCard)
        card.translatesAutoresizingMaskIntoConstraints = false
        styleSurface(card, borderColor: palette.inputBorder, borderWidth: 1, shadow: true)
        content.addSubview(card)

        let stack = NSStackView()
        stack.translatesAutoresizingMaskIntoConstraints = false
        stack.orientation = .vertical
        stack.spacing = 18
        stack.alignment = .leading
        card.addSubview(stack)

        let pageTitle = textLabel("Settings", font: typography.pageTitle, color: palette.textPrimary)
        let pageSubtitle = textLabel("Manage appearance, account, and app options.", font: typography.fieldLabel, color: palette.textSecondary)
        stack.addArrangedSubview(pageTitle)
        stack.addArrangedSubview(pageSubtitle)
        stack.setCustomSpacing(24, after: pageSubtitle)

        let appearanceTitle = textLabel("Appearance", font: typography.joinWithURLTitle, color: palette.textPrimary)
        stack.addArrangedSubview(appearanceTitle)
        let darkModeRow = makeSettingsDarkModeRow()
        stack.addArrangedSubview(darkModeRow)
        darkModeRow.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
        stack.setCustomSpacing(24, after: darkModeRow)

        let aiCompanionTitle = textLabel("AI Companion", font: typography.joinWithURLTitle, color: palette.textPrimary)
        stack.addArrangedSubview(aiCompanionTitle)
        let language1Row = makeSettingsSpeechLanguageRow(title: "Preferred Language 1", isPrimary: true)
        stack.addArrangedSubview(language1Row)
        language1Row.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
        let language2Row = makeSettingsSpeechLanguageRow(title: "Preferred Language 2", isPrimary: false)
        stack.addArrangedSubview(language2Row)
        language2Row.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
        stack.setCustomSpacing(24, after: language2Row)

        let accountTitle = textLabel("Account", font: typography.joinWithURLTitle, color: palette.textPrimary)
        stack.addArrangedSubview(accountTitle)
        let googleAccountRow = makeSettingsGoogleAccountRow()
        stack.addArrangedSubview(googleAccountRow)
        googleAccountRow.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
        stack.setCustomSpacing(24, after: googleAccountRow)

        let appTitle = textLabel("App", font: typography.joinWithURLTitle, color: palette.textPrimary)
        stack.addArrangedSubview(appTitle)

        if shouldShowRateUsInSettings {
            let rateButton = makeSettingsActionButton(icon: "★", title: "Rate Us", action: .rateUs)
            stack.addArrangedSubview(rateButton)
            rateButton.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
        }
        let shareButton = makeSettingsActionButton(icon: "⤴︎", title: "Share App", action: .shareApp)
        stack.addArrangedSubview(shareButton)
        shareButton.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
        if storeKitCoordinator.hasPremiumAccess && !storeKitCoordinator.hasLifetimeAccess {
            let upgradeButton = makeSettingsActionButton(icon: "⬆︎", title: "Upgrade", action: .upgrade)
            stack.addArrangedSubview(upgradeButton)
            upgradeButton.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
            stack.setCustomSpacing(24, after: upgradeButton)
        } else {
            stack.setCustomSpacing(24, after: shareButton)
        }

        if storeKitCoordinator.hasPremiumAccess {
            let notificationsTitle = textLabel("Notifications", font: typography.joinWithURLTitle, color: palette.textPrimary)
            stack.addArrangedSubview(notificationsTitle)
            let remindersSection = makeSettingsRemindersSection()
            stack.addArrangedSubview(remindersSection)
            remindersSection.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
            stack.setCustomSpacing(24, after: remindersSection)
        }

        let legalTitle = textLabel("Help & Legal", font: typography.joinWithURLTitle, color: palette.textPrimary)
        stack.addArrangedSubview(legalTitle)
        let privacyButton = makeSettingsActionButton(icon: "🔒", title: "Privacy Policy", action: .privacyPolicy)
        stack.addArrangedSubview(privacyButton)
        privacyButton.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
        let supportButton = makeSettingsActionButton(icon: "💬", title: "Support", action: .support)
        stack.addArrangedSubview(supportButton)
        supportButton.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
        let termsButton = makeSettingsActionButton(icon: "📄", title: "Terms of Services", action: .termsOfServices)
        stack.addArrangedSubview(termsButton)
        termsButton.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
        NSLayoutConstraint.activate([
            scroll.leadingAnchor.constraint(equalTo: panel.leadingAnchor),
            scroll.trailingAnchor.constraint(equalTo: panel.trailingAnchor),
            scroll.topAnchor.constraint(equalTo: panel.topAnchor),
            scroll.bottomAnchor.constraint(equalTo: panel.bottomAnchor),

            content.leadingAnchor.constraint(equalTo: scroll.contentView.leadingAnchor),
            content.trailingAnchor.constraint(equalTo: scroll.contentView.trailingAnchor),
            content.topAnchor.constraint(equalTo: scroll.contentView.topAnchor),
            content.bottomAnchor.constraint(greaterThanOrEqualTo: scroll.contentView.bottomAnchor),
            content.widthAnchor.constraint(equalTo: scroll.contentView.widthAnchor),

            card.centerXAnchor.constraint(equalTo: content.centerXAnchor),
            card.topAnchor.constraint(equalTo: content.topAnchor, constant: 36),
            content.bottomAnchor.constraint(greaterThanOrEqualTo: card.bottomAnchor, constant: 36),
            card.widthAnchor.constraint(lessThanOrEqualToConstant: 620),
            card.widthAnchor.constraint(greaterThanOrEqualToConstant: 460),
            card.leadingAnchor.constraint(greaterThanOrEqualTo: content.leadingAnchor, constant: 30),
            card.trailingAnchor.constraint(lessThanOrEqualTo: content.trailingAnchor, constant: -30),

            stack.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 28),
            stack.trailingAnchor.constraint(equalTo: card.trailingAnchor, constant: -28),
            stack.topAnchor.constraint(equalTo: card.topAnchor, constant: 24),
            stack.bottomAnchor.constraint(equalTo: card.bottomAnchor, constant: -24)
        ])

        return panel
    }

    private func makeSettingsDarkModeRow() -> NSView {
        let row = roundedContainer(cornerRadius: 10, color: palette.inputBackground)
        row.translatesAutoresizingMaskIntoConstraints = false
        row.heightAnchor.constraint(equalToConstant: 52).isActive = true
        styleSurface(row, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)

        let icon = textLabel("◐", font: NSFont.systemFont(ofSize: 18, weight: .medium), color: palette.textPrimary)
        let title = textLabel("Dark Mode", font: NSFont.systemFont(ofSize: 15, weight: .semibold), color: palette.textPrimary)
        let toggle = NSSwitch()
        toggle.translatesAutoresizingMaskIntoConstraints = false
        toggle.state = darkModeEnabled ? .on : .off
        toggle.target = self
        toggle.action = #selector(settingsPageDarkModeToggled(_:))

        row.addSubview(icon)
        row.addSubview(title)
        row.addSubview(toggle)
        NSLayoutConstraint.activate([
            icon.leadingAnchor.constraint(equalTo: row.leadingAnchor, constant: 14),
            icon.centerYAnchor.constraint(equalTo: row.centerYAnchor),
            title.leadingAnchor.constraint(equalTo: icon.trailingAnchor, constant: 10),
            title.centerYAnchor.constraint(equalTo: row.centerYAnchor),
            toggle.trailingAnchor.constraint(equalTo: row.trailingAnchor, constant: -14),
            toggle.centerYAnchor.constraint(equalTo: row.centerYAnchor)
        ])
        return row
    }

    private func makeSettingsSpeechLanguageRow(title: String, isPrimary: Bool) -> NSView {
        let row = roundedContainer(cornerRadius: 10, color: palette.inputBackground)
        row.translatesAutoresizingMaskIntoConstraints = false
        row.heightAnchor.constraint(equalToConstant: 72).isActive = true
        styleSurface(row, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)

        let titleLabel = textLabel(title, font: NSFont.systemFont(ofSize: 13, weight: .semibold), color: palette.textPrimary)
        let popup = NSPopUpButton(frame: .zero, pullsDown: false)
        popup.translatesAutoresizingMaskIntoConstraints = false
        popup.target = self
        popup.action = #selector(settingsPageSpeechLanguageChanged(_:))

        let options = aiCompanionSupportedSpeechLocaleOptions()
        if isPrimary == false {
            popup.addItem(withTitle: "None")
            popup.lastItem?.representedObject = ""
        }
        for option in options {
            popup.addItem(withTitle: option.displayName)
            popup.lastItem?.representedObject = option.identifier
        }

        if isPrimary {
            let selected = UserDefaults.standard.string(forKey: aiCompanionPreferredLanguage1DefaultsKey)
                ?? options.first?.identifier
                ?? Locale.current.identifier
            selectSettingsPageLanguage(identifier: selected, in: popup)
            settingsPagePrimaryLanguagePopup = popup
        } else {
            if let selected = UserDefaults.standard.string(forKey: aiCompanionPreferredLanguage2DefaultsKey),
               selected.isEmpty == false {
                selectSettingsPageLanguage(identifier: selected, in: popup)
            } else {
                popup.selectItem(at: 0)
            }
            settingsPageSecondaryLanguagePopup = popup
        }

        row.addSubview(titleLabel)
        row.addSubview(popup)
        NSLayoutConstraint.activate([
            titleLabel.leadingAnchor.constraint(equalTo: row.leadingAnchor, constant: 14),
            titleLabel.topAnchor.constraint(equalTo: row.topAnchor, constant: 10),
            titleLabel.trailingAnchor.constraint(equalTo: row.trailingAnchor, constant: -14),

            popup.leadingAnchor.constraint(equalTo: row.leadingAnchor, constant: 14),
            popup.trailingAnchor.constraint(equalTo: row.trailingAnchor, constant: -14),
            popup.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 8),
            popup.heightAnchor.constraint(equalToConstant: 28)
        ])
        return row
    }

    private func selectSettingsPageLanguage(identifier: String, in popup: NSPopUpButton) {
        for item in popup.itemArray {
            if let value = item.representedObject as? String, value == identifier {
                popup.select(item)
                return
            }
        }
    }

    @objc private func settingsPageSpeechLanguageChanged(_ sender: NSPopUpButton) {
        guard let primary = settingsPagePrimaryLanguagePopup?.selectedItem?.representedObject as? String,
              primary.isEmpty == false else { return }
        var secondary: String? = settingsPageSecondaryLanguagePopup?.selectedItem?.representedObject as? String
        if secondary?.isEmpty == true {
            secondary = nil
        }
        if let secondaryValue = secondary,
           secondaryValue.replacingOccurrences(of: "_", with: "-").lowercased() == primary.replacingOccurrences(of: "_", with: "-").lowercased() {
            secondary = nil
            settingsPageSecondaryLanguagePopup?.selectItem(at: 0)
        }
        updateAiCompanionPreferredSpeechLanguages(primary: primary, secondary: secondary)
    }

    private func makeSettingsRemindersSection() -> NSView {
        let container = NSStackView()
        container.translatesAutoresizingMaskIntoConstraints = false
        container.orientation = .vertical
        container.spacing = 1
        container.alignment = .leading

        let masterRow = makeReminderToggleRow(
            icon: "🔔",
            title: "Reminders",
            state: ReminderPreferences.remindersEnabled,
            action: #selector(settingsReminderMasterToggled(_:)),
            isSubRow: false
        )
        container.addArrangedSubview(masterRow)
        masterRow.widthAnchor.constraint(equalTo: container.widthAnchor).isActive = true

        let subAlpha: CGFloat = ReminderPreferences.remindersEnabled ? 1.0 : 0.4

        let day1Row = makeReminderToggleRow(
            icon: "📅",
            title: "1 Day Before",
            state: ReminderPreferences.remind1Day,
            action: #selector(settingsReminder1DayToggled(_:)),
            isSubRow: true
        )
        day1Row.alphaValue = subAlpha
        container.addArrangedSubview(day1Row)
        day1Row.widthAnchor.constraint(equalTo: container.widthAnchor).isActive = true

        let hours12Row = makeReminderToggleRow(
            icon: "🕛",
            title: "12 Hours Before",
            state: ReminderPreferences.remind12Hours,
            action: #selector(settingsReminder12HoursToggled(_:)),
            isSubRow: true
        )
        hours12Row.alphaValue = subAlpha
        container.addArrangedSubview(hours12Row)
        hours12Row.widthAnchor.constraint(equalTo: container.widthAnchor).isActive = true

        let hour1Row = makeReminderToggleRow(
            icon: "⏰",
            title: "1 Hour Before",
            state: ReminderPreferences.remind1Hour,
            action: #selector(settingsReminder1HourToggled(_:)),
            isSubRow: true
        )
        hour1Row.alphaValue = subAlpha
        container.addArrangedSubview(hour1Row)
        hour1Row.widthAnchor.constraint(equalTo: container.widthAnchor).isActive = true

        settingsReminderMasterSwitch = masterRow.subviews.compactMap { $0 as? NSSwitch }.first
        settingsReminder1DaySwitch = day1Row.subviews.compactMap { $0 as? NSSwitch }.first
        settingsReminder12HoursSwitch = hours12Row.subviews.compactMap { $0 as? NSSwitch }.first
        settingsReminder1HourSwitch = hour1Row.subviews.compactMap { $0 as? NSSwitch }.first

        return container
    }

    private func makeReminderToggleRow(icon: String, title: String, state: Bool, action: Selector, isSubRow: Bool) -> NSView {
        let row = roundedContainer(cornerRadius: 10, color: isSubRow ? palette.inputBackground.withAlphaComponent(0.6) : palette.inputBackground)
        row.translatesAutoresizingMaskIntoConstraints = false
        row.heightAnchor.constraint(equalToConstant: 48).isActive = true
        styleSurface(row, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)

        let iconLabel = textLabel(icon, font: NSFont.systemFont(ofSize: isSubRow ? 15 : 17, weight: .medium), color: palette.textPrimary)
        let titleLabel = textLabel(title, font: NSFont.systemFont(ofSize: isSubRow ? 14 : 15, weight: isSubRow ? .regular : .semibold), color: palette.textPrimary)
        if isSubRow {
            titleLabel.textColor = palette.textSecondary
        }

        let toggle = NSSwitch()
        toggle.translatesAutoresizingMaskIntoConstraints = false
        toggle.state = state ? .on : .off
        toggle.target = self
        toggle.action = action

        row.addSubview(iconLabel)
        row.addSubview(titleLabel)
        row.addSubview(toggle)
        NSLayoutConstraint.activate([
            iconLabel.leadingAnchor.constraint(equalTo: row.leadingAnchor, constant: isSubRow ? 30 : 14),
            iconLabel.centerYAnchor.constraint(equalTo: row.centerYAnchor),
            titleLabel.leadingAnchor.constraint(equalTo: iconLabel.trailingAnchor, constant: 10),
            titleLabel.centerYAnchor.constraint(equalTo: row.centerYAnchor),
            toggle.trailingAnchor.constraint(equalTo: row.trailingAnchor, constant: -14),
            toggle.centerYAnchor.constraint(equalTo: row.centerYAnchor)
        ])
        return row
    }

    @objc private func settingsReminderMasterToggled(_ sender: NSSwitch) {
        let enabled = sender.state == .on
        ReminderPreferences.remindersEnabled = enabled
        let subAlpha: CGFloat = enabled ? 1.0 : 0.4
        settingsReminder1DaySwitch?.superview?.alphaValue = subAlpha
        settingsReminder12HoursSwitch?.superview?.alphaValue = subAlpha
        settingsReminder1HourSwitch?.superview?.alphaValue = subAlpha
        if enabled {
            MeetingReminderManager.shared.requestPermissionIfNeeded { [weak self] _ in
                guard let self else { return }
                MeetingReminderManager.shared.scheduleReminders(for: self.scheduleCachedMeetings)
            }
        } else {
            MeetingReminderManager.shared.cancelAllReminders()
        }
    }

    @objc private func settingsReminder1DayToggled(_ sender: NSSwitch) {
        ReminderPreferences.remind1Day = sender.state == .on
        MeetingReminderManager.shared.scheduleReminders(for: scheduleCachedMeetings)
    }

    @objc private func settingsReminder12HoursToggled(_ sender: NSSwitch) {
        ReminderPreferences.remind12Hours = sender.state == .on
        MeetingReminderManager.shared.scheduleReminders(for: scheduleCachedMeetings)
    }

    @objc private func settingsReminder1HourToggled(_ sender: NSSwitch) {
        ReminderPreferences.remind1Hour = sender.state == .on
        MeetingReminderManager.shared.scheduleReminders(for: scheduleCachedMeetings)
    }

    private func makeSettingsGoogleAccountRow() -> NSView {
        let row = roundedContainer(cornerRadius: 10, color: palette.inputBackground)
        row.translatesAutoresizingMaskIntoConstraints = false
        styleSurface(row, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)

        let signedIn = hasGoogleSessionAvailable()
        let titleText = signedIn ? (scheduleCurrentProfile?.name ?? "Google account connected") : "Google account not connected"
        let subtitleText = signedIn ? (scheduleCurrentProfile?.email ?? "Signed in") : "Sign in to sync your meetings and calendar."

        let title = textLabel(titleText, font: NSFont.systemFont(ofSize: 15, weight: .semibold), color: palette.textPrimary)
        let subtitle = textLabel(subtitleText, font: NSFont.systemFont(ofSize: 13, weight: .regular), color: palette.textSecondary)
        subtitle.maximumNumberOfLines = 2
        subtitle.lineBreakMode = .byTruncatingTail

        let actionButton = NSButton(title: signedIn ? "Sign Out" : "Sign in with Google", target: self, action: #selector(settingsGoogleActionButtonClicked(_:)))
        actionButton.translatesAutoresizingMaskIntoConstraints = false
        actionButton.bezelStyle = .rounded
        actionButton.controlSize = .regular

        row.addSubview(title)
        row.addSubview(subtitle)
        row.addSubview(actionButton)
        NSLayoutConstraint.activate([
            row.heightAnchor.constraint(equalToConstant: 78),
            title.leadingAnchor.constraint(equalTo: row.leadingAnchor, constant: 14),
            title.topAnchor.constraint(equalTo: row.topAnchor, constant: 12),
            subtitle.leadingAnchor.constraint(equalTo: title.leadingAnchor),
            subtitle.topAnchor.constraint(equalTo: title.bottomAnchor, constant: 4),
            subtitle.trailingAnchor.constraint(lessThanOrEqualTo: actionButton.leadingAnchor, constant: -14),
            actionButton.trailingAnchor.constraint(equalTo: row.trailingAnchor, constant: -14),
            actionButton.centerYAnchor.constraint(equalTo: row.centerYAnchor)
        ])

        return row
    }

    private func makeSettingsActionButton(icon: String, title: String, action: SettingsAction) -> NSButton {
        let button = HoverButton(title: "", target: self, action: #selector(settingsPageActionButtonClicked(_:)))
        button.translatesAutoresizingMaskIntoConstraints = false
        button.isBordered = false
        button.wantsLayer = true
        button.layer?.cornerRadius = 10
        button.layer?.backgroundColor = palette.inputBackground.cgColor
        styleSurface(button, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
        button.heightAnchor.constraint(equalToConstant: 46).isActive = true
        button.tag = action.rawValue

        let iconLabel = textLabel(icon, font: NSFont.systemFont(ofSize: 17, weight: .medium), color: palette.textPrimary)
        let titleLabel = textLabel(title, font: NSFont.systemFont(ofSize: 15, weight: .semibold), color: palette.textPrimary)
        button.addSubview(iconLabel)
        button.addSubview(titleLabel)
        NSLayoutConstraint.activate([
            iconLabel.leadingAnchor.constraint(equalTo: button.leadingAnchor, constant: 14),
            iconLabel.centerYAnchor.constraint(equalTo: button.centerYAnchor),
            titleLabel.leadingAnchor.constraint(equalTo: iconLabel.trailingAnchor, constant: 10),
            titleLabel.centerYAnchor.constraint(equalTo: button.centerYAnchor)
        ])
        return button
    }

    @objc private func settingsPageDarkModeToggled(_ sender: NSSwitch) {
        setDarkMode(sender.state == .on)
    }

    @objc private func settingsPageActionButtonClicked(_ sender: NSButton) {
        guard let action = SettingsAction(rawValue: sender.tag) else { return }
        let clickPoint: NSPoint?
        if let event = NSApp.currentEvent {
            let pointInWindow = event.locationInWindow
            clickPoint = sender.convert(pointInWindow, from: nil)
        } else {
            clickPoint = nil
        }
        handleSettingsAction(action, sourceView: sender, clickLocationInSourceView: clickPoint)
    }

    @objc private func settingsGoogleActionButtonClicked(_ sender: NSButton) {
        if hasGoogleSessionAvailable() == false {
            scheduleConnectClicked()
        } else {
            performGoogleSignOut()
        }
    }

    func makeBrowseWebContent() -> NSView {
        let panel = NSView()
        panel.translatesAutoresizingMaskIntoConstraints = false

        let titleLabel = textLabel("Browse the web", font: typography.pageTitle, color: palette.textPrimary)
        titleLabel.translatesAutoresizingMaskIntoConstraints = false
        let sub = textLabel(
            "Open sites in the in-app browser (back, forward, reload, address bar). OAuth and “Continue in browser” flows stay inside the app.",
            font: typography.fieldLabel,
            color: palette.textSecondary
        )
        sub.translatesAutoresizingMaskIntoConstraints = false
        sub.maximumNumberOfLines = 0
        sub.lineBreakMode = .byWordWrapping

        let fieldShell = roundedContainer(cornerRadius: 8, color: palette.inputBackground)
        fieldShell.translatesAutoresizingMaskIntoConstraints = false
        fieldShell.heightAnchor.constraint(equalToConstant: 44).isActive = true
        styleSurface(fieldShell, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)

        let field = NSTextField(string: "")
        field.translatesAutoresizingMaskIntoConstraints = false
        field.isEditable = true
        field.isBordered = false
        field.drawsBackground = false
        field.focusRingType = .none
        field.font = NSFont.systemFont(ofSize: 14, weight: .regular)
        field.textColor = palette.textPrimary
        field.placeholderString = "https://example.com or example.com"
        field.delegate = self
        browseAddressField = field
        fieldShell.addSubview(field)

        let openBtn = meetActionButton(
            title: "Open in app browser",
            color: palette.primaryBlue,
            textColor: .white,
            width: 220,
            action: #selector(browseOpenAddressClicked(_:))
        )

        let quickTitle = textLabel("Quick links", font: typography.joinWithURLTitle, color: palette.textPrimary)
        quickTitle.translatesAutoresizingMaskIntoConstraints = false

        let quickRow = NSStackView()
        quickRow.translatesAutoresizingMaskIntoConstraints = false
        quickRow.orientation = .horizontal
        quickRow.spacing = 10
        quickRow.addArrangedSubview(browseQuickLinkButton(title: "Google Meet", action: #selector(browseQuickLinkMeetClicked(_:))))
        quickRow.addArrangedSubview(browseQuickLinkButton(title: "Meet help", action: #selector(browseQuickLinkMeetHelpClicked(_:))))
        quickRow.addArrangedSubview(browseQuickLinkButton(title: "Zoom help", action: #selector(browseQuickLinkZoomHelpClicked(_:))))

        panel.addSubview(titleLabel)
        panel.addSubview(sub)
        panel.addSubview(fieldShell)
        panel.addSubview(openBtn)
        panel.addSubview(quickTitle)
        panel.addSubview(quickRow)

        NSLayoutConstraint.activate([
            titleLabel.leadingAnchor.constraint(equalTo: panel.leadingAnchor, constant: 28),
            titleLabel.topAnchor.constraint(equalTo: panel.topAnchor, constant: 26),
            titleLabel.trailingAnchor.constraint(lessThanOrEqualTo: panel.trailingAnchor, constant: -28),

            sub.leadingAnchor.constraint(equalTo: titleLabel.leadingAnchor),
            sub.trailingAnchor.constraint(lessThanOrEqualTo: panel.trailingAnchor, constant: -28),
            sub.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 10),

            fieldShell.leadingAnchor.constraint(equalTo: titleLabel.leadingAnchor),
            fieldShell.trailingAnchor.constraint(equalTo: panel.trailingAnchor, constant: -28),
            fieldShell.topAnchor.constraint(equalTo: sub.bottomAnchor, constant: 18),

            field.leadingAnchor.constraint(equalTo: fieldShell.leadingAnchor, constant: 12),
            field.trailingAnchor.constraint(equalTo: fieldShell.trailingAnchor, constant: -12),
            field.centerYAnchor.constraint(equalTo: fieldShell.centerYAnchor),

            openBtn.leadingAnchor.constraint(equalTo: titleLabel.leadingAnchor),
            openBtn.topAnchor.constraint(equalTo: fieldShell.bottomAnchor, constant: 12),
            openBtn.heightAnchor.constraint(equalToConstant: 36),

            quickTitle.leadingAnchor.constraint(equalTo: titleLabel.leadingAnchor),
            quickTitle.topAnchor.constraint(equalTo: openBtn.bottomAnchor, constant: 28),

            quickRow.leadingAnchor.constraint(equalTo: titleLabel.leadingAnchor),
            quickRow.topAnchor.constraint(equalTo: quickTitle.bottomAnchor, constant: 10)
        ])

        return panel
    }

    private func browseQuickLinkButton(title: String, action: Selector) -> NSButton {
        let b = NSButton(title: title, target: self, action: action)
        b.translatesAutoresizingMaskIntoConstraints = false
        b.bezelStyle = .rounded
        b.font = NSFont.systemFont(ofSize: 13, weight: .medium)
        return b
    }

    private func applyWindowTitle(for page: SidebarPage) {
        let title: String
        switch page {
        case .joinMeetings:
            title = "App for Google Meet"
        case .photo:
            title = "Schedule"
        case .video:
            title = "Calendar"
        case .widgets:
            title = "Widgets"
        case .settings:
            title = "Settings"
        case .aiCompanion:
            title = "AI Companion"
        }
        view.window?.title = title
    }

    private func configureMainWindowChrome(_ window: NSWindow) {
        window.styleMask.insert(.fullSizeContentView)
        window.titleVisibility = .hidden
        window.titlebarAppearsTransparent = true
        window.isMovableByWindowBackground = true
    }

    private func updateSidebarAppearance() {
        for (page, row) in sidebarRowViews {
            applySidebarRowStyle(row, page: page, logoTemplate: logoTemplateForSidebarPage(page))
        }
    }

    private func logoTemplateForSidebarPage(_ page: SidebarPage) -> Bool {
        switch page {
        case .photo: return false
        case .joinMeetings, .video, .widgets, .settings, .aiCompanion: return true
        }
    }

    func makeSidebar() -> NSView {
        let sidebar = NSView()
        sidebar.translatesAutoresizingMaskIntoConstraints = false
        sidebar.wantsLayer = true
        sidebar.layer?.backgroundColor = palette.sidebarBackground.cgColor
        sidebar.layer?.borderColor = palette.separator.cgColor
        sidebar.layer?.borderWidth = 1
        sidebar.layer?.shadowColor = NSColor.black.cgColor
        sidebar.layer?.shadowOpacity = 0.18
        sidebar.layer?.shadowOffset = CGSize(width: 2, height: 0)
        sidebar.layer?.shadowRadius = 10
        sidebar.widthAnchor.constraint(equalToConstant: 210).isActive = true
        let sidebarTopInset: CGFloat = 44

        let appIconView = NSImageView()
        if let brandLogo = NSImage(named: "SidebarBrandLogo") {
            brandLogo.isTemplate = false
            appIconView.image = brandLogo
        } else if let appIconImage = NSApplication.shared.applicationIconImage {
            appIconImage.isTemplate = false
            appIconView.image = appIconImage
        }
        appIconView.translatesAutoresizingMaskIntoConstraints = false
        appIconView.imageScaling = NSImageScaling.scaleProportionallyDown
        appIconView.imageAlignment = NSImageAlignment.alignCenter
        appIconView.contentTintColor = nil
        appIconView.widthAnchor.constraint(equalToConstant: 44).isActive = true
        appIconView.heightAnchor.constraint(equalToConstant: 44).isActive = true

        let titleRow = NSStackView(views: [
            appIconView,
            textLabel("Meetings", font: typography.sidebarBrand, color: palette.textPrimary)
        ])
        titleRow.translatesAutoresizingMaskIntoConstraints = false
        titleRow.orientation = NSUserInterfaceLayoutOrientation.horizontal
        titleRow.alignment = NSLayoutConstraint.Attribute.centerY
        titleRow.spacing = 16

        let menuStack = NSStackView()
        menuStack.translatesAutoresizingMaskIntoConstraints = false
        menuStack.orientation = .vertical
        menuStack.alignment = .leading
        menuStack.spacing = 10

        menuStack.addArrangedSubview(sidebarSectionTitle("Meetings"))
        let joinRow = sidebarItem("Join Meetings", icon: "􀉣", page: .joinMeetings, logoImageName: "JoinMeetingsLogo", logoIconWidth: 24, logoHeightMultiplier: 56.0 / 52.0)
        menuStack.addArrangedSubview(joinRow)
        sidebarRowViews[.joinMeetings] = joinRow
        menuStack.addArrangedSubview(sidebarSectionTitle("Planning"))
        let photoRow = sidebarItem("Schedule", icon: "􀏂", page: .photo, systemSymbolName: "clock.badge.checkmark")
        menuStack.addArrangedSubview(photoRow)
        sidebarRowViews[.photo] = photoRow
        let videoRow = sidebarItem("Calendar", icon: "􀎚", page: .video, systemSymbolName: "calendar")
        menuStack.addArrangedSubview(videoRow)
        sidebarRowViews[.video] = videoRow
        let widgetsRow = sidebarItem("Widgets", icon: "􀏅", page: .widgets, systemSymbolName: "square.grid.2x2.fill")
        menuStack.addArrangedSubview(widgetsRow)
        sidebarRowViews[.widgets] = widgetsRow
        let aiCompanionRow = sidebarItem("AI Companion", icon: "􀁚", page: .aiCompanion, systemSymbolName: "waveform")
        menuStack.addArrangedSubview(aiCompanionRow)
        sidebarRowViews[.aiCompanion] = aiCompanionRow
        menuStack.addArrangedSubview(sidebarSectionTitle("Additional"))
        let settingsRow = sidebarItem("Settings", icon: "􀍟", page: .settings, systemSymbolName: "gearshape.fill", logoHeightMultiplier: 1, showsDisclosure: true)
        menuStack.addArrangedSubview(settingsRow)
        sidebarRowViews[.settings] = settingsRow

        let premiumButton = sidebarPremiumButton()

        sidebar.addSubview(titleRow)
        sidebar.addSubview(menuStack)
        sidebar.addSubview(premiumButton)

        NSLayoutConstraint.activate([
            titleRow.leadingAnchor.constraint(equalTo: sidebar.leadingAnchor, constant: 16),
            titleRow.topAnchor.constraint(equalTo: sidebar.topAnchor, constant: sidebarTopInset),
            titleRow.trailingAnchor.constraint(lessThanOrEqualTo: sidebar.trailingAnchor, constant: -16),

            menuStack.leadingAnchor.constraint(equalTo: sidebar.leadingAnchor, constant: 12),
            menuStack.trailingAnchor.constraint(equalTo: sidebar.trailingAnchor, constant: -12),
            menuStack.topAnchor.constraint(equalTo: titleRow.bottomAnchor, constant: 20),
            menuStack.bottomAnchor.constraint(lessThanOrEqualTo: premiumButton.topAnchor, constant: -16),

            premiumButton.leadingAnchor.constraint(equalTo: sidebar.leadingAnchor, constant: 12),
            premiumButton.trailingAnchor.constraint(equalTo: sidebar.trailingAnchor, constant: -12),
            premiumButton.bottomAnchor.constraint(equalTo: sidebar.bottomAnchor, constant: -14)
        ])

        for subview in menuStack.arrangedSubviews {
            subview.widthAnchor.constraint(equalTo: menuStack.widthAnchor).isActive = true
        }

        return sidebar
    }

    func sidebarPremiumButton() -> NSView {
        let button = HoverTrackingView()
        button.translatesAutoresizingMaskIntoConstraints = false
        button.wantsLayer = true
        button.layer?.cornerRadius = 17
        button.layer?.backgroundColor = palette.primaryBlue.cgColor
        button.heightAnchor.constraint(equalToConstant: 34).isActive = true
        styleSurface(button, borderColor: palette.primaryBlueBorder, borderWidth: 1, shadow: false)

        let icon = NSImageView()
        icon.translatesAutoresizingMaskIntoConstraints = false
        icon.imageScaling = .scaleProportionallyUpOrDown
        icon.contentTintColor = .white
        icon.image = premiumButtonSymbolImage(named: "star.fill")
        let title = textLabel("Get Premium", font: NSFont.systemFont(ofSize: 14, weight: .semibold), color: .white)
        button.addSubview(icon)
        button.addSubview(title)

        NSLayoutConstraint.activate([
            icon.leadingAnchor.constraint(equalTo: button.leadingAnchor, constant: 12),
            icon.centerYAnchor.constraint(equalTo: button.centerYAnchor),
            icon.widthAnchor.constraint(equalToConstant: 14),
            icon.heightAnchor.constraint(equalToConstant: 14),
            title.leadingAnchor.constraint(equalTo: icon.trailingAnchor, constant: 8),
            title.centerYAnchor.constraint(equalTo: button.centerYAnchor),
            title.trailingAnchor.constraint(lessThanOrEqualTo: button.trailingAnchor, constant: -12)
        ])

        button.onHoverChanged = { [weak self, weak button] hovering in
            guard let self, let button else { return }
            let isPremium = self.storeKitCoordinator.hasPremiumAccess
            let baseColor = isPremium
                ? NSColor(calibratedRed: 0.93, green: 0.73, blue: 0.16, alpha: 1.0)
                : self.palette.primaryBlue
            let borderColor = isPremium
                ? NSColor(calibratedRed: 0.78, green: 0.56, blue: 0.10, alpha: 1.0)
                : self.palette.primaryBlueBorder
            let hoverColor: NSColor
            let hoverBorderColor: NSColor
            if isPremium {
                // Darker rich-gold hover for stronger premium feedback.
                hoverColor = NSColor(calibratedRed: 0.84, green: 0.62, blue: 0.11, alpha: 1.0)
                hoverBorderColor = NSColor(calibratedRed: 0.67, green: 0.46, blue: 0.07, alpha: 1.0)
            } else {
                let hoverBlend = self.darkModeEnabled ? NSColor.white : NSColor.black
                hoverColor = baseColor.blended(withFraction: 0.10, of: hoverBlend) ?? baseColor
                hoverBorderColor = borderColor
            }
            button.layer?.backgroundColor = (hovering ? hoverColor : baseColor).cgColor
            button.layer?.shadowColor = NSColor.black.cgColor
            button.layer?.shadowOpacity = hovering ? (isPremium ? 0.30 : 0.20) : 0.14
            button.layer?.shadowOffset = CGSize(width: 0, height: -1)
            button.layer?.shadowRadius = hovering ? (isPremium ? 8 : 6) : 4
            self.styleSurface(button, borderColor: (hovering ? hoverBorderColor : borderColor), borderWidth: hovering ? 1.5 : 1, shadow: false)
        }
        button.onHoverChanged?(false)
        sidebarPremiumTitleLabel = title
        sidebarPremiumIconView = icon
        sidebarPremiumButtonView = button
        refreshSidebarPremiumButton()

        let click = NSClickGestureRecognizer(target: self, action: #selector(premiumButtonClicked(_:)))
        button.addGestureRecognizer(click)
        return button
    }

    func makeMainPanel() -> NSView {
        let panel = NSView()
        panel.translatesAutoresizingMaskIntoConstraints = false
        panel.wantsLayer = true
        panel.layer?.backgroundColor = palette.pageBackground.cgColor

        let authBar = scheduleTopAuthRow()
        authBar.translatesAutoresizingMaskIntoConstraints = false
        panel.addSubview(authBar)

        let host = NSView()
        host.translatesAutoresizingMaskIntoConstraints = false
        panel.addSubview(host)
        let hostTopToAuth = host.topAnchor.constraint(equalTo: authBar.bottomAnchor, constant: 20)
        let hostTopToPanel = host.topAnchor.constraint(equalTo: panel.topAnchor)
        hostTopToPanel.isActive = false
        NSLayoutConstraint.activate([
            authBar.leadingAnchor.constraint(equalTo: panel.leadingAnchor, constant: 28),
            authBar.trailingAnchor.constraint(equalTo: panel.trailingAnchor, constant: -28),
            authBar.topAnchor.constraint(equalTo: panel.safeAreaLayoutGuide.topAnchor, constant: 26),

            host.leadingAnchor.constraint(equalTo: panel.leadingAnchor),
            host.trailingAnchor.constraint(equalTo: panel.trailingAnchor),
            hostTopToAuth,
            host.bottomAnchor.constraint(equalTo: panel.bottomAnchor)
        ])
        mainContentHost = host
        mainPanelAuthBar = authBar
        mainContentHostTopToAuthConstraint = hostTopToAuth
        mainContentHostTopToPanelConstraint = hostTopToPanel

        if hasGoogleSessionAvailable(), let profile = scheduleCurrentProfile {
            applyGoogleProfile(profile)
        }

        // Preserve the currently selected page during rebuilds (e.g. dark mode toggle).
        showSidebarPage(selectedSidebarPage)

        return panel
    }

    func makeJoinMeetingsContent() -> NSView {
        let panel = NSView()
        panel.translatesAutoresizingMaskIntoConstraints = false

        let contentStack = NSStackView()
        contentStack.translatesAutoresizingMaskIntoConstraints = false
        contentStack.orientation = .vertical
        contentStack.spacing = 14
        contentStack.alignment = .leading

        let joinRow = meetJoinSectionRow()
        let joinActions = meetJoinActionsRow()
        contentStack.addArrangedSubview(textLabel("Join Meetings", font: typography.pageTitle, color: palette.textPrimary))
        contentStack.addArrangedSubview(joinRow)
        contentStack.addArrangedSubview(joinActions)
        contentStack.setCustomSpacing(26, after: joinActions)
        let scheduleHeaderView = scheduleHeader()
        contentStack.addArrangedSubview(scheduleHeaderView)
        contentStack.setCustomSpacing(joinPageScheduleHeaderToDateSpacing, after: scheduleHeaderView)

        let dateHeading = textLabel(scheduleInitialHeadingText(), font: typography.dateHeading, color: palette.textSecondary)
        scheduleDateHeadingLabel = dateHeading
        contentStack.addArrangedSubview(dateHeading)
        contentStack.setCustomSpacing(joinPageDateToMeetingCardsSpacing, after: dateHeading)

        let cardsRow = scheduleCardsRow(meetings: [])
        contentStack.addArrangedSubview(cardsRow)

        panel.addSubview(contentStack)

        NSLayoutConstraint.activate([
            contentStack.leadingAnchor.constraint(equalTo: panel.leadingAnchor, constant: 28),
            contentStack.trailingAnchor.constraint(equalTo: panel.trailingAnchor, constant: -28),
            contentStack.topAnchor.constraint(equalTo: panel.topAnchor)
        ])

        // `contentStack` uses `.leading` alignment, so key rows must opt in to stretching.
        joinRow.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true
        joinActions.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true

        Task { [weak self] in
            await self?.loadSchedule()
        }

        return panel
    }

    func makeSchedulePageContent() -> NSView {
        let panel = NSView()
        panel.translatesAutoresizingMaskIntoConstraints = false
        panel.userInterfaceLayoutDirection = .leftToRight

        let contentStack = NSStackView()
        contentStack.translatesAutoresizingMaskIntoConstraints = false
        contentStack.userInterfaceLayoutDirection = .leftToRight
        contentStack.orientation = .vertical
        contentStack.spacing = schedulePageStackSpacing
        contentStack.alignment = .width
        contentStack.distribution = .fill

        let header = schedulePageHeader()
        header.setContentHuggingPriority(.required, for: .vertical)
        header.setContentCompressionResistancePriority(.required, for: .vertical)
        contentStack.addArrangedSubview(header)
        contentStack.setCustomSpacing(schedulePageHeaderToDateSpacing, after: header)

        let heading = textLabel(schedulePageInitialHeadingText(), font: typography.dateHeading, color: palette.textSecondary)
        heading.alignment = .left
        heading.setContentHuggingPriority(.required, for: .vertical)
        heading.setContentCompressionResistancePriority(.required, for: .vertical)
        schedulePageDateHeadingLabel = heading
        contentStack.addArrangedSubview(heading)

        let rangeError = textLabel("", font: NSFont.systemFont(ofSize: 12, weight: .semibold), color: .systemRed)
        rangeError.alignment = .left
        rangeError.isHidden = true
        rangeError.setContentHuggingPriority(.required, for: .vertical)
        rangeError.setContentCompressionResistancePriority(.required, for: .vertical)
        schedulePageRangeErrorLabel = rangeError
        contentStack.addArrangedSubview(rangeError)

        let cardsContainer = makeSchedulePageCardsContainer()
        cardsContainer.setContentHuggingPriority(.defaultLow, for: .vertical)
        contentStack.addArrangedSubview(cardsContainer)

        panel.addSubview(contentStack)

        NSLayoutConstraint.activate([
            contentStack.leftAnchor.constraint(equalTo: panel.leftAnchor, constant: schedulePageLeadingInset),
            contentStack.rightAnchor.constraint(equalTo: panel.rightAnchor, constant: -schedulePageTrailingInset),
            contentStack.topAnchor.constraint(equalTo: panel.topAnchor),
            contentStack.bottomAnchor.constraint(equalTo: panel.bottomAnchor, constant: -16),
            header.widthAnchor.constraint(equalTo: contentStack.widthAnchor),
            heading.widthAnchor.constraint(equalTo: contentStack.widthAnchor),
            rangeError.widthAnchor.constraint(equalTo: contentStack.widthAnchor),
            cardsContainer.widthAnchor.constraint(equalTo: contentStack.widthAnchor)
        ])

        Task { [weak self] in
            await self?.loadSchedule()
        }

        return panel
    }

    func makeCalendarPageContent() -> NSView {
        let panel = NSView()
        panel.translatesAutoresizingMaskIntoConstraints = false
        panel.userInterfaceLayoutDirection = .leftToRight

        let contentStack = NSStackView()
        contentStack.translatesAutoresizingMaskIntoConstraints = false
        contentStack.userInterfaceLayoutDirection = .leftToRight
        contentStack.orientation = .vertical
        contentStack.spacing = 14
        contentStack.alignment = .width
        contentStack.distribution = .fill

        let titleRow = NSStackView()
        titleRow.translatesAutoresizingMaskIntoConstraints = false
        titleRow.userInterfaceLayoutDirection = .leftToRight
        titleRow.orientation = .horizontal
        titleRow.alignment = .centerY
        titleRow.distribution = .fill
        titleRow.spacing = 10

        let titleLabel = textLabel("Calendar", font: typography.pageTitle, color: palette.textPrimary)
        titleLabel.alignment = .left
        titleLabel.maximumNumberOfLines = 1
        titleLabel.lineBreakMode = .byTruncatingTail
        titleLabel.setContentHuggingPriority(.required, for: .horizontal)
        titleLabel.setContentCompressionResistancePriority(.required, for: .horizontal)

        let spacer = NSView()
        spacer.translatesAutoresizingMaskIntoConstraints = false
        spacer.setContentHuggingPriority(.defaultLow, for: .horizontal)
        spacer.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)

        let prevButton = makeCalendarHeaderPillButton(title: "‹", action: #selector(calendarPrevMonthPressed(_:)))
        prevButton.widthAnchor.constraint(equalToConstant: 46).isActive = true
        let nextButton = makeCalendarHeaderPillButton(title: "›", action: #selector(calendarNextMonthPressed(_:)))
        nextButton.widthAnchor.constraint(equalToConstant: 46).isActive = true

        let monthLabel = textLabel("", font: NSFont.systemFont(ofSize: 16, weight: .semibold), color: palette.textSecondary)
        monthLabel.alignment = .right
        monthLabel.maximumNumberOfLines = 1
        monthLabel.lineBreakMode = .byTruncatingTail
        monthLabel.setContentHuggingPriority(.required, for: .horizontal)
        monthLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
        calendarPageMonthLabel = monthLabel

        let refreshButton = HoverButton(title: "", target: self, action: #selector(calendarRefreshPressed(_:)))
        refreshButton.translatesAutoresizingMaskIntoConstraints = false
        refreshButton.isBordered = false
        refreshButton.bezelStyle = .regularSquare
        refreshButton.wantsLayer = true
        refreshButton.layer?.cornerRadius = 15
        refreshButton.layer?.masksToBounds = true
        refreshButton.layer?.backgroundColor = palette.inputBackground.cgColor
        refreshButton.layer?.borderColor = palette.inputBorder.cgColor
        refreshButton.layer?.borderWidth = 1
        refreshButton.setButtonType(.momentaryChange)
        refreshButton.contentTintColor = palette.textSecondary
        refreshButton.image = NSImage(systemSymbolName: "arrow.clockwise", accessibilityDescription: "Sync calendar")
        refreshButton.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 14, weight: .semibold)
        refreshButton.imagePosition = .imageOnly
        refreshButton.imageScaling = .scaleProportionallyDown
        refreshButton.focusRingType = .none
        refreshButton.heightAnchor.constraint(equalToConstant: 32).isActive = true
        refreshButton.widthAnchor.constraint(equalToConstant: 32).isActive = true

        titleRow.addArrangedSubview(titleLabel)
        titleRow.addArrangedSubview(spacer)
        titleRow.addArrangedSubview(prevButton)
        titleRow.addArrangedSubview(nextButton)
        titleRow.addArrangedSubview(monthLabel)
        titleRow.addArrangedSubview(refreshButton)

        let weekdayRow = NSStackView()
        weekdayRow.translatesAutoresizingMaskIntoConstraints = false
        weekdayRow.userInterfaceLayoutDirection = .leftToRight
        weekdayRow.orientation = .horizontal
        weekdayRow.alignment = .centerY
        weekdayRow.distribution = .fillEqually
        weekdayRow.spacing = 12

        for symbol in calendarWeekdaySymbolsStartingAtFirstWeekday() {
            let label = textLabel(symbol, font: NSFont.systemFont(ofSize: 12, weight: .semibold), color: palette.textMuted)
            label.alignment = .center
            label.maximumNumberOfLines = 1
            label.lineBreakMode = .byClipping
            weekdayRow.addArrangedSubview(label)
        }

        let gridStack = NSStackView()
        gridStack.translatesAutoresizingMaskIntoConstraints = false
        gridStack.userInterfaceLayoutDirection = .leftToRight
        gridStack.orientation = .vertical
        gridStack.alignment = .width
        gridStack.distribution = .fillEqually
        gridStack.spacing = 10
        calendarPageGridStack = gridStack

        let gridCard = roundedContainer(cornerRadius: 14, color: palette.sectionCard)
        gridCard.translatesAutoresizingMaskIntoConstraints = false
        styleSurface(gridCard, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
        let gridHeightConstraint = gridCard.heightAnchor.constraint(equalToConstant: 360)
        gridHeightConstraint.isActive = true
        calendarPageGridHeightConstraint = gridHeightConstraint
        gridCard.heightAnchor.constraint(greaterThanOrEqualToConstant: 360).isActive = true
        gridCard.addSubview(gridStack)
        NSLayoutConstraint.activate([
            gridStack.leadingAnchor.constraint(equalTo: gridCard.leadingAnchor, constant: 16),
            gridStack.trailingAnchor.constraint(equalTo: gridCard.trailingAnchor, constant: -16),
            gridStack.topAnchor.constraint(equalTo: gridCard.topAnchor, constant: 16),
            gridStack.bottomAnchor.constraint(equalTo: gridCard.bottomAnchor, constant: -16)
        ])

        let daySummary = textLabel("", font: typography.dateHeading, color: palette.textSecondary)
        daySummary.alignment = .left
        daySummary.maximumNumberOfLines = 2
        daySummary.lineBreakMode = .byWordWrapping
        calendarPageDaySummaryLabel = daySummary

        contentStack.addArrangedSubview(titleRow)
        contentStack.setCustomSpacing(16, after: titleRow)
        contentStack.addArrangedSubview(weekdayRow)
        contentStack.setCustomSpacing(10, after: weekdayRow)
        contentStack.addArrangedSubview(gridCard)
        contentStack.setCustomSpacing(16, after: gridCard)
        contentStack.addArrangedSubview(daySummary)

        panel.addSubview(contentStack)
        NSLayoutConstraint.activate([
            contentStack.leftAnchor.constraint(equalTo: panel.leftAnchor, constant: 28),
            contentStack.rightAnchor.constraint(equalTo: panel.rightAnchor, constant: -28),
            contentStack.topAnchor.constraint(equalTo: panel.topAnchor),
            contentStack.bottomAnchor.constraint(lessThanOrEqualTo: panel.bottomAnchor, constant: -16),
            titleRow.widthAnchor.constraint(equalTo: contentStack.widthAnchor),
            weekdayRow.widthAnchor.constraint(equalTo: contentStack.widthAnchor),
            gridCard.widthAnchor.constraint(equalTo: contentStack.widthAnchor),
            daySummary.widthAnchor.constraint(equalTo: contentStack.widthAnchor)
        ])

        if !storeKitCoordinator.hasPremiumAccess {
            let lockOverlay = NSVisualEffectView()
            lockOverlay.translatesAutoresizingMaskIntoConstraints = false
            lockOverlay.material = darkModeEnabled ? .hudWindow : .popover
            lockOverlay.blendingMode = .withinWindow
            lockOverlay.state = .active
            lockOverlay.wantsLayer = true
            lockOverlay.layer?.cornerRadius = 14
            lockOverlay.layer?.masksToBounds = true
            lockOverlay.layer?.backgroundColor = NSColor.black.withAlphaComponent(darkModeEnabled ? 0.30 : 0.12).cgColor
            panel.addSubview(lockOverlay)

            let message = textLabel("Premium required. Get Premium now to unlock Calendar.", font: NSFont.systemFont(ofSize: 14, weight: .semibold), color: darkModeEnabled ? .white : .black)
            message.alignment = .center
            message.maximumNumberOfLines = 2
            message.lineBreakMode = .byWordWrapping
            lockOverlay.addSubview(message)

            let hit = HoverTrackingView()
            hit.translatesAutoresizingMaskIntoConstraints = false
            hit.wantsLayer = true
            hit.layer?.backgroundColor = NSColor.clear.cgColor
            hit.onClick = { [weak self] in
                self?.showPaywall()
            }
            hit.toolTip = "Premium required. Click to open paywall."
            lockOverlay.addSubview(hit)

            NSLayoutConstraint.activate([
                lockOverlay.leadingAnchor.constraint(equalTo: contentStack.leadingAnchor),
                lockOverlay.trailingAnchor.constraint(equalTo: contentStack.trailingAnchor),
                lockOverlay.topAnchor.constraint(equalTo: contentStack.topAnchor),
                lockOverlay.bottomAnchor.constraint(equalTo: contentStack.bottomAnchor),

                message.centerXAnchor.constraint(equalTo: lockOverlay.centerXAnchor),
                message.centerYAnchor.constraint(equalTo: lockOverlay.centerYAnchor),
                message.leadingAnchor.constraint(greaterThanOrEqualTo: lockOverlay.leadingAnchor, constant: 22),
                message.trailingAnchor.constraint(lessThanOrEqualTo: lockOverlay.trailingAnchor, constant: -22),

                hit.leadingAnchor.constraint(equalTo: lockOverlay.leadingAnchor),
                hit.trailingAnchor.constraint(equalTo: lockOverlay.trailingAnchor),
                hit.topAnchor.constraint(equalTo: lockOverlay.topAnchor),
                hit.bottomAnchor.constraint(equalTo: lockOverlay.bottomAnchor)
            ])
        }

        let calendar = Calendar.current
        calendarPageMonthAnchor = calendarStartOfMonth(for: Date())
        calendarPageSelectedDate = calendar.startOfDay(for: Date())
        calendarPageMonthLabel?.stringValue = calendarMonthTitleText(for: calendarPageMonthAnchor)
        renderCalendarMonthGrid()
        renderCalendarSelectedDay()

        Task { [weak self] in
            await self?.loadSchedule()
        }

        return panel
    }

    func meetJoinSectionRow() -> NSView {
        let row = NSStackView()
        row.translatesAutoresizingMaskIntoConstraints = false
        row.orientation = .horizontal
        row.spacing = 12
        row.alignment = .top
        row.distribution = .fillEqually
        let minWidth = row.widthAnchor.constraint(greaterThanOrEqualToConstant: 880)
        minWidth.priority = .defaultLow
        minWidth.isActive = true
        row.heightAnchor.constraint(equalToConstant: 140).isActive = true

        let instant = HoverSurfaceView()
        instant.translatesAutoresizingMaskIntoConstraints = false
        instant.wantsLayer = true
        instant.layer?.cornerRadius = 14
        instant.layer?.backgroundColor = palette.sectionCard.cgColor
        styleSurface(instant, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)

        let iconWrap = roundedContainer(cornerRadius: 12, color: NSColor.clear)
        iconWrap.translatesAutoresizingMaskIntoConstraints = false
        iconWrap.widthAnchor.constraint(equalToConstant: 58).isActive = true
        iconWrap.heightAnchor.constraint(equalToConstant: 58).isActive = true
        iconWrap.layer?.borderWidth = 0
        let meetLogoImage = NSImage(named: "MeetLogo") ?? NSImage()
        meetLogoImage.isTemplate = false
        let meetLogo = NSImageView(image: meetLogoImage)
        meetLogo.translatesAutoresizingMaskIntoConstraints = false
        meetLogo.imageScaling = .scaleProportionallyDown
        meetLogo.contentTintColor = nil
        iconWrap.addSubview(meetLogo)

        let instantTitle = textLabel("New Instant Meet", font: NSFont.systemFont(ofSize: 40 / 2, weight: .semibold), color: palette.textPrimary)
        let instantSub = textLabel("Start instant Meet in more section with\nGoogle Meet meet.", font: NSFont.systemFont(ofSize: 16 / 2, weight: .medium), color: palette.textSecondary)
        instantSub.maximumNumberOfLines = 2
        instant.addSubview(iconWrap)
        instant.addSubview(instantTitle)
        instant.addSubview(instantSub)

        let codeCard = HoverSurfaceView()
        codeCard.translatesAutoresizingMaskIntoConstraints = false
        codeCard.wantsLayer = true
        codeCard.layer?.cornerRadius = 14
        codeCard.layer?.backgroundColor = palette.sectionCard.cgColor
        styleSurface(codeCard, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
        let codeTitle = textLabel("Join with Link", font: NSFont.systemFont(ofSize: 40 / 2, weight: .semibold), color: palette.textPrimary)
        let codeInputShell = roundedContainer(cornerRadius: 8, color: palette.inputBackground)
        codeInputShell.translatesAutoresizingMaskIntoConstraints = false
        codeInputShell.heightAnchor.constraint(equalToConstant: 52).isActive = true
        styleSurface(codeInputShell, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
        let codeField = NSTextField(string: "")
        codeField.translatesAutoresizingMaskIntoConstraints = false
        codeField.isEditable = true
        codeField.isBordered = false
        codeField.drawsBackground = false
        codeField.focusRingType = .none
        codeField.font = NSFont.systemFont(ofSize: 36 / 2, weight: .regular)
        codeField.textColor = palette.textPrimary
        codeField.placeholderString = "Code or meet.google.com/…"
        codeInputShell.addSubview(codeField)
        meetLinkField = codeField
        codeCard.addSubview(codeTitle)
        codeCard.addSubview(codeInputShell)

        NSLayoutConstraint.activate([
            meetLogo.centerXAnchor.constraint(equalTo: iconWrap.centerXAnchor),
            meetLogo.centerYAnchor.constraint(equalTo: iconWrap.centerYAnchor),
            meetLogo.widthAnchor.constraint(equalToConstant: 46),
            meetLogo.heightAnchor.constraint(equalToConstant: 46),

            iconWrap.leadingAnchor.constraint(equalTo: instant.leadingAnchor, constant: 18),
            iconWrap.topAnchor.constraint(equalTo: instant.topAnchor, constant: 22),
            instantTitle.leadingAnchor.constraint(equalTo: iconWrap.trailingAnchor, constant: 14),
            instantTitle.topAnchor.constraint(equalTo: instant.topAnchor, constant: 24),
            instantSub.leadingAnchor.constraint(equalTo: instantTitle.leadingAnchor),
            instantSub.topAnchor.constraint(equalTo: instantTitle.bottomAnchor, constant: 6),
            instantSub.trailingAnchor.constraint(lessThanOrEqualTo: instant.trailingAnchor, constant: -16),

            codeTitle.leadingAnchor.constraint(equalTo: codeCard.leadingAnchor, constant: 18),
            codeTitle.topAnchor.constraint(equalTo: codeCard.topAnchor, constant: 22),
            codeInputShell.leadingAnchor.constraint(equalTo: codeCard.leadingAnchor, constant: 18),
            codeInputShell.trailingAnchor.constraint(equalTo: codeCard.trailingAnchor, constant: -18),
            codeInputShell.topAnchor.constraint(equalTo: codeTitle.bottomAnchor, constant: 12),
            codeField.leadingAnchor.constraint(equalTo: codeInputShell.leadingAnchor, constant: 14),
            codeField.trailingAnchor.constraint(equalTo: codeInputShell.trailingAnchor, constant: -14),
            codeField.centerYAnchor.constraint(equalTo: codeInputShell.centerYAnchor)
        ])

        let baseColor = palette.sectionCard
        let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
        let hoverColor = baseColor.blended(withFraction: 0.10, of: hoverBlend) ?? baseColor
        instant.onHoverChanged = { [weak self] hovering in
            guard let self else { return }
            instant.layer?.backgroundColor = (hovering ? hoverColor : baseColor).cgColor
        }
        codeCard.onHoverChanged = { [weak self] hovering in
            guard let self else { return }
            codeCard.layer?.backgroundColor = (hovering ? hoverColor : baseColor).cgColor
        }
        instant.onHoverChanged?(false)
        codeCard.onHoverChanged?(false)

        let instantClick = NSClickGestureRecognizer(target: self, action: #selector(instantMeetClicked(_:)))
        instant.addGestureRecognizer(instantClick)
        let joinWithLinkClick = NSClickGestureRecognizer(target: self, action: #selector(joinWithLinkCardClicked(_:)))
        codeCard.addGestureRecognizer(joinWithLinkClick)
        instantMeetCardView = instant
        instantMeetTitleLabel = instantTitle
        instantMeetSubtitleLabel = instantSub
        joinWithLinkCardView = codeCard
        joinWithLinkTitleLabel = codeTitle
        refreshInstantMeetPremiumState()

        row.addArrangedSubview(instant)
        row.addArrangedSubview(codeCard)
        return row
    }

    func meetJoinActionsRow() -> NSView {
        let row = NSStackView()
        row.translatesAutoresizingMaskIntoConstraints = false
        row.orientation = .horizontal
        row.spacing = 12
        row.alignment = .centerY
        let minWidth = row.widthAnchor.constraint(greaterThanOrEqualToConstant: 880)
        minWidth.priority = .defaultLow
        minWidth.isActive = true

        let spacer = NSView()
        spacer.translatesAutoresizingMaskIntoConstraints = false
        row.addArrangedSubview(spacer)
        row.addArrangedSubview(meetActionButton(
            title: "Cancel",
            color: palette.cancelButton,
            textColor: palette.textSecondary,
            width: 110,
            action: #selector(cancelMeetJoinClicked(_:))
        ))
        let joinButton = meetActionButton(
            title: "Join",
            color: palette.primaryBlue,
            textColor: .white,
            width: 116,
            action: #selector(joinMeetClicked(_:))
        )
        joinMeetPrimaryButton = joinButton
        row.addArrangedSubview(joinButton)
        refreshInstantMeetPremiumState()
        return row
    }

    func meetActionButton(title: String, color: NSColor, textColor: NSColor, width: CGFloat, action: Selector) -> NSButton {
        let button = HoverButton(title: title, target: self, action: action)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.isBordered = false
        button.bezelStyle = .regularSquare
        button.wantsLayer = true
        button.layer?.cornerRadius = 9
        let baseBackground = color
        let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
        let hoverBackground = baseBackground.blended(withFraction: 0.10, of: hoverBlend) ?? baseBackground

        let baseBorder = (title == "Cancel" ? palette.inputBorder : palette.primaryBlueBorder)
        let hoverBorder = baseBorder.blended(withFraction: 0.18, of: hoverBlend) ?? baseBorder

        button.layer?.backgroundColor = baseBackground.cgColor
        button.layer?.borderColor = baseBorder.cgColor
        button.layer?.borderWidth = 1
        button.font = typography.buttonText
        button.contentTintColor = textColor
        button.widthAnchor.constraint(equalToConstant: width).isActive = true
        button.heightAnchor.constraint(equalToConstant: 36).isActive = true
        button.onHoverChanged = { [weak self, weak button] hovering in
            guard let self, let button else { return }
            button.layer?.backgroundColor = (hovering ? hoverBackground : baseBackground).cgColor
            button.layer?.borderColor = (hovering ? hoverBorder : baseBorder).cgColor
            if title == "Cancel" {
                button.contentTintColor = hovering ? (self.darkModeEnabled ? .white : self.palette.textPrimary) : textColor
            }
        }
        button.onHoverChanged?(false)
        return button
    }

    func makePaywallContent() -> NSView {
        paywallPlanViews.removeAll()
        premiumPlanByView.removeAll()
        paywallPriceLabels.removeAll()
        paywallSubtitleLabels.removeAll()
        paywallBadgeLabels.removeAll()
        paywallStrikePriceLabels.removeAll()

        let panel = NSView()
        panel.translatesAutoresizingMaskIntoConstraints = false
        panel.wantsLayer = true
        panel.layer?.backgroundColor = palette.pageBackground.cgColor

        let contentStack = NSStackView()
        contentStack.translatesAutoresizingMaskIntoConstraints = false
        contentStack.orientation = .vertical
        contentStack.spacing = 12
        contentStack.distribution = .fill
        contentStack.alignment = .centerX
        panel.addSubview(contentStack)
        let paywallLayoutWidth: CGFloat = 980

        let topRow = NSStackView()
        topRow.translatesAutoresizingMaskIntoConstraints = false
        topRow.orientation = .horizontal
        topRow.alignment = .centerY
        topRow.distribution = .fill
        topRow.spacing = 10
        topRow.addArrangedSubview(textLabel("Meetings Pro", font: NSFont.systemFont(ofSize: 27, weight: .bold), color: palette.textPrimary))
        var closeButton: HoverButton?
        if storeKitCoordinator.hasPremiumAccess {
            let button = HoverButton(title: "✕", target: self, action: #selector(closePaywallClicked(_:)))
            button.translatesAutoresizingMaskIntoConstraints = false
            button.isBordered = false
            button.bezelStyle = .regularSquare
            button.wantsLayer = true
            button.layer?.cornerRadius = 14
            button.layer?.backgroundColor = palette.inputBackground.cgColor
            button.layer?.borderColor = palette.inputBorder.cgColor
            button.layer?.borderWidth = 1
            button.font = typography.iconButton
            button.contentTintColor = palette.textSecondary
            button.widthAnchor.constraint(equalToConstant: 28).isActive = true
            button.heightAnchor.constraint(equalToConstant: 28).isActive = true
            button.onHoverChanged = { [weak button, weak self] hovering in
                guard let button, let self else { return }
                let base = self.palette.inputBackground
                let hoverBlend = self.darkModeEnabled ? NSColor.white : NSColor.black
                let hover = base.blended(withFraction: 0.10, of: hoverBlend) ?? base
                button.layer?.backgroundColor = (hovering ? hover : base).cgColor
                button.contentTintColor = hovering ? (self.darkModeEnabled ? .white : self.palette.textPrimary) : self.palette.textSecondary
            }
            panel.addSubview(button)
            closeButton = button
        }
        contentStack.addArrangedSubview(topRow)
        topRow.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true

        let hero = roundedContainer(cornerRadius: 16, color: palette.sectionCard)
        hero.translatesAutoresizingMaskIntoConstraints = false
        styleSurface(hero, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
        contentStack.addArrangedSubview(hero)
        hero.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true

        let heroBadge = textLabel("PREMIUM EXPERIENCE", font: NSFont.systemFont(ofSize: 10, weight: .bold), color: NSColor(calibratedRed: 0.42, green: 0.93, blue: 0.70, alpha: 1))
        hero.addSubview(heroBadge)
        let heroTitle = textLabel("Elevate your meetings workflow", font: NSFont.systemFont(ofSize: 22, weight: .bold), color: palette.textPrimary)
        let heroSubtitle = textLabel("Unlock automation, premium meeting tools, and priority support for every session.", font: NSFont.systemFont(ofSize: 13, weight: .medium), color: palette.textSecondary)
        heroTitle.maximumNumberOfLines = 2
        heroSubtitle.maximumNumberOfLines = 3
        hero.addSubview(heroTitle)
        hero.addSubview(heroSubtitle)
        NSLayoutConstraint.activate([
            heroBadge.leadingAnchor.constraint(equalTo: hero.leadingAnchor, constant: 16),
            heroBadge.topAnchor.constraint(equalTo: hero.topAnchor, constant: 14),
            heroTitle.leadingAnchor.constraint(equalTo: hero.leadingAnchor, constant: 16),
            heroTitle.trailingAnchor.constraint(lessThanOrEqualTo: hero.trailingAnchor, constant: -16),
            heroTitle.topAnchor.constraint(equalTo: heroBadge.bottomAnchor, constant: 10),
            heroSubtitle.leadingAnchor.constraint(equalTo: heroTitle.leadingAnchor),
            heroSubtitle.trailingAnchor.constraint(equalTo: hero.trailingAnchor, constant: -16),
            heroSubtitle.topAnchor.constraint(equalTo: heroTitle.bottomAnchor, constant: 8),
            heroSubtitle.bottomAnchor.constraint(equalTo: hero.bottomAnchor, constant: -16)
        ])

        let benefitsRow = NSStackView()
        benefitsRow.translatesAutoresizingMaskIntoConstraints = false
        benefitsRow.orientation = .horizontal
        benefitsRow.spacing = 8
        benefitsRow.distribution = .fillEqually
        benefitsRow.alignment = .centerY
        benefitsRow.addArrangedSubview(paywallBenefitItem(icon: "📅", text: "Manage meetings"))
        benefitsRow.addArrangedSubview(paywallBenefitItem(icon: "🧠", text: "Smart scheduling"))
        benefitsRow.addArrangedSubview(paywallBenefitItem(icon: "⚡", text: "Faster workflow"))
        benefitsRow.addArrangedSubview(paywallBenefitItem(icon: "🔔", text: "Reminder notifications"))
        contentStack.addArrangedSubview(benefitsRow)
        benefitsRow.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true

        let plansRow = NSStackView()
        plansRow.translatesAutoresizingMaskIntoConstraints = false
        plansRow.orientation = .horizontal
        plansRow.spacing = 10
        plansRow.distribution = .fillEqually
        plansRow.alignment = .centerY

        let weeklyCard = paywallPlanCard(
            title: "Weekly",
            price: fallbackPriceText(for: .weekly),
            badge: "Basic",
            badgeColor: NSColor(calibratedRed: 1.0, green: 0.60, blue: 0.20, alpha: 1),
            subtitle: nil,
            plan: .weekly,
            strikePrice: nil
        )
        let monthlyCard = paywallPlanCard(
            title: "Monthly",
            price: fallbackPriceText(for: .monthly),
            badge: "Popular",
            badgeColor: NSColor(calibratedRed: 0.19, green: 0.82, blue: 0.39, alpha: 1),
            subtitle: nil,
            plan: .monthly,
            strikePrice: nil
        )
        let yearlyCard = paywallPlanCard(
            title: "Yearly",
            price: fallbackPriceText(for: .yearly),
            badge: yearlySavingsBadgeText(),
            badgeColor: NSColor(calibratedRed: 1.0, green: 0.60, blue: 0.20, alpha: 1),
            subtitle: "3 days free trial",
            plan: .yearly,
            strikePrice: nil
        )
        let lifetimeCard = paywallPlanCard(
            title: "Lifetime",
            price: fallbackPriceText(for: .lifetime),
            badge: "Best Value",
            badgeColor: NSColor(calibratedRed: 1.0, green: 0.60, blue: 0.20, alpha: 1),
            subtitle: nil,
            plan: .lifetime,
            strikePrice: nil
        )
        plansRow.addArrangedSubview(weeklyCard)
        plansRow.addArrangedSubview(monthlyCard)
        plansRow.addArrangedSubview(yearlyCard)
        plansRow.addArrangedSubview(lifetimeCard)
        contentStack.addArrangedSubview(plansRow)
        plansRow.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true
        updatePaywallPlanSelection()

        let trustRow = NSStackView()
        trustRow.translatesAutoresizingMaskIntoConstraints = false
        trustRow.orientation = .horizontal
        trustRow.spacing = 8
        trustRow.distribution = .fillEqually
        trustRow.alignment = .centerY
        trustRow.addArrangedSubview(paywallMetaItem(title: "Cancel anytime", subtitle: "No lock-in"))
        trustRow.addArrangedSubview(paywallMetaItem(title: "Instant access", subtitle: "Unlock all tools"))
        trustRow.addArrangedSubview(paywallMetaItem(title: "Secure billing", subtitle: "Handled by Apple"))
        contentStack.addArrangedSubview(trustRow)
        trustRow.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true

        let offer = textLabel(paywallOfferText(for: selectedPremiumPlan), font: NSFont.systemFont(ofSize: 13, weight: .semibold), color: palette.textPrimary)
        offer.alignment = .center
        paywallOfferLabel = offer
        let offerWrap = NSView()
        offerWrap.translatesAutoresizingMaskIntoConstraints = false
        offerWrap.addSubview(offer)
        contentStack.addArrangedSubview(offerWrap)
        offerWrap.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true
        NSLayoutConstraint.activate([
            offer.centerXAnchor.constraint(equalTo: offerWrap.centerXAnchor),
            offer.topAnchor.constraint(equalTo: offerWrap.topAnchor, constant: 4),
            offer.bottomAnchor.constraint(equalTo: offerWrap.bottomAnchor, constant: -2)
        ])

        let continueButton = HoverButton(title: "", target: self, action: #selector(paywallContinueClicked(_:)))
        continueButton.translatesAutoresizingMaskIntoConstraints = false
        continueButton.isBordered = false
        continueButton.bezelStyle = .regularSquare
        continueButton.wantsLayer = true
        continueButton.layer?.cornerRadius = 12
        continueButton.layer?.backgroundColor = palette.primaryBlue.cgColor
        continueButton.heightAnchor.constraint(equalToConstant: 36).isActive = true
        styleSurface(continueButton, borderColor: palette.primaryBlueBorder, borderWidth: 1, shadow: true)
        let continueLabel = textLabel("Continue", font: NSFont.systemFont(ofSize: 14, weight: .bold), color: .white)
        continueButton.addSubview(continueLabel)
        NSLayoutConstraint.activate([
            continueLabel.centerXAnchor.constraint(equalTo: continueButton.centerXAnchor),
            continueLabel.centerYAnchor.constraint(equalTo: continueButton.centerYAnchor)
        ])
        let baseBlue = palette.primaryBlue
        let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
        let hoverBlue = baseBlue.blended(withFraction: 0.10, of: hoverBlend) ?? baseBlue
        continueButton.onHoverChanged = { hovering in
            continueButton.layer?.backgroundColor = (hovering ? hoverBlue : baseBlue).cgColor
        }
        continueButton.onHoverChanged?(false)
        paywallContinueButton = continueButton
        paywallContinueLabel = continueLabel
        contentStack.addArrangedSubview(continueButton)
        continueButton.widthAnchor.constraint(equalToConstant: 360).isActive = true

        let secure = textLabel("Secured by Apple. Cancel anytime.", font: NSFont.systemFont(ofSize: 12, weight: .semibold), color: palette.textSecondary)
        secure.alignment = .center
        let secureWrap = NSView()
        secureWrap.translatesAutoresizingMaskIntoConstraints = false
        secureWrap.addSubview(secure)
        contentStack.addArrangedSubview(secureWrap)
        secureWrap.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true
        NSLayoutConstraint.activate([
            secure.centerXAnchor.constraint(equalTo: secureWrap.centerXAnchor),
            secure.topAnchor.constraint(equalTo: secureWrap.topAnchor, constant: 2),
            secure.bottomAnchor.constraint(equalTo: secureWrap.bottomAnchor, constant: -4)
        ])

        let footer = paywallFooterLinks()
        contentStack.addArrangedSubview(footer)
        footer.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true

        var panelConstraints: [NSLayoutConstraint] = [
            contentStack.centerXAnchor.constraint(equalTo: panel.centerXAnchor),
            contentStack.widthAnchor.constraint(equalToConstant: paywallLayoutWidth),
            contentStack.topAnchor.constraint(equalTo: panel.topAnchor, constant: 80),
            contentStack.bottomAnchor.constraint(equalTo: panel.bottomAnchor, constant: -12)
        ]
        if let closeButton {
            panelConstraints.append(closeButton.topAnchor.constraint(equalTo: panel.topAnchor, constant: 30))
            panelConstraints.append(closeButton.trailingAnchor.constraint(equalTo: panel.trailingAnchor, constant: -30))
        }
        NSLayoutConstraint.activate(panelConstraints)

        refreshPaywallStoreUI()
        return panel
    }

    func paywallPlanCard(
        title: String,
        price: String,
        badge: String,
        badgeColor: NSColor,
        subtitle: String?,
        plan: PremiumPlan,
        strikePrice: String?
    ) -> NSView {
        let wrapper = HoverButton(title: "", target: self, action: #selector(paywallPlanButtonClicked(_:)))
        wrapper.translatesAutoresizingMaskIntoConstraints = false
        wrapper.isBordered = false
        wrapper.bezelStyle = .regularSquare
        wrapper.wantsLayer = true
        wrapper.layer?.backgroundColor = NSColor.clear.cgColor
        wrapper.widthAnchor.constraint(greaterThanOrEqualToConstant: 160).isActive = true
        wrapper.heightAnchor.constraint(equalToConstant: 162).isActive = true
        wrapper.tag = plan.rawValue

        let card = HoverTrackingView()
        card.translatesAutoresizingMaskIntoConstraints = false
        card.wantsLayer = true
        card.layer?.cornerRadius = 16
        card.layer?.backgroundColor = palette.sectionCard.cgColor
        card.heightAnchor.constraint(equalToConstant: 150).isActive = true
        wrapper.addSubview(card)
        NSLayoutConstraint.activate([
            card.leadingAnchor.constraint(equalTo: wrapper.leadingAnchor),
            card.trailingAnchor.constraint(equalTo: wrapper.trailingAnchor),
            card.topAnchor.constraint(equalTo: wrapper.topAnchor, constant: 12),
            card.bottomAnchor.constraint(equalTo: wrapper.bottomAnchor)
        ])
        styleSurface(card, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)

        let badgeLabel = textLabel(badge, font: NSFont.systemFont(ofSize: 10, weight: .bold), color: .white)
        paywallBadgeLabels[plan] = badgeLabel
        let badgeWrap = roundedContainer(cornerRadius: 10, color: badgeColor)
        badgeWrap.translatesAutoresizingMaskIntoConstraints = false
        badgeWrap.wantsLayer = true
        badgeWrap.layer?.borderColor = NSColor(calibratedWhite: 1, alpha: 0.22).cgColor
        badgeWrap.layer?.borderWidth = 1
        badgeWrap.layer?.shadowColor = NSColor.black.cgColor
        badgeWrap.layer?.shadowOpacity = 0.20
        badgeWrap.layer?.shadowOffset = CGSize(width: 0, height: -1)
        badgeWrap.layer?.shadowRadius = 3
        badgeWrap.addSubview(badgeLabel)
        NSLayoutConstraint.activate([
            badgeLabel.leadingAnchor.constraint(equalTo: badgeWrap.leadingAnchor, constant: 8),
            badgeLabel.trailingAnchor.constraint(equalTo: badgeWrap.trailingAnchor, constant: -8),
            badgeLabel.topAnchor.constraint(equalTo: badgeWrap.topAnchor, constant: 2),
            badgeLabel.bottomAnchor.constraint(equalTo: badgeWrap.bottomAnchor, constant: -2)
        ])
        wrapper.addSubview(badgeWrap)

        let titleLabel = textLabel(title, font: NSFont.systemFont(ofSize: 15, weight: .bold), color: palette.primaryBlue)
        card.addSubview(titleLabel)
        let priceLabel = textLabel(price, font: NSFont.systemFont(ofSize: 12, weight: .bold), color: palette.textPrimary)
        card.addSubview(priceLabel)
        paywallPriceLabels[plan] = priceLabel

        NSLayoutConstraint.activate([
            badgeWrap.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 12),
            badgeWrap.centerYAnchor.constraint(equalTo: card.topAnchor),

            titleLabel.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 12),
            titleLabel.topAnchor.constraint(equalTo: card.topAnchor, constant: 34),

            priceLabel.leadingAnchor.constraint(equalTo: titleLabel.leadingAnchor),
            priceLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 10),
            priceLabel.trailingAnchor.constraint(lessThanOrEqualTo: card.trailingAnchor, constant: -12)
        ])

        if let subtitle {
            let sub = textLabel(subtitle, font: NSFont.systemFont(ofSize: 10, weight: .semibold), color: palette.textSecondary)
            card.addSubview(sub)
            paywallSubtitleLabels[plan] = sub
            NSLayoutConstraint.activate([
                sub.leadingAnchor.constraint(equalTo: priceLabel.leadingAnchor),
                sub.topAnchor.constraint(equalTo: priceLabel.bottomAnchor, constant: 2),
                sub.trailingAnchor.constraint(lessThanOrEqualTo: card.trailingAnchor, constant: -12)
            ])
        }

        if let strikePrice {
            let strike = textLabel(strikePrice, font: NSFont.systemFont(ofSize: 12, weight: .medium), color: NSColor.systemRed)
            card.addSubview(strike)
            paywallStrikePriceLabels[plan] = strike
            NSLayoutConstraint.activate([
                strike.leadingAnchor.constraint(equalTo: priceLabel.leadingAnchor),
                strike.topAnchor.constraint(equalTo: priceLabel.bottomAnchor, constant: 4),
                strike.trailingAnchor.constraint(lessThanOrEqualTo: card.trailingAnchor, constant: -12)
            ])
        }

        paywallPlanViews[plan] = card
        wrapper.onHoverChanged = { [weak self, weak card] hovering in
            guard let self, let card else { return }
            self.applyPaywallPlanStyle(card, isSelected: plan == self.selectedPremiumPlan, hovering: hovering)
        }
        wrapper.onHoverChanged?(false)

        return wrapper
    }

    func paywallFooterLinks() -> NSView {
        let wrap = NSView()
        wrap.translatesAutoresizingMaskIntoConstraints = false
        wrap.heightAnchor.constraint(equalToConstant: 40).isActive = true
        paywallFooterActionByView.removeAll()

        let row = NSStackView()
        row.translatesAutoresizingMaskIntoConstraints = false
        row.orientation = .horizontal
        row.distribution = .fillEqually
        row.alignment = .centerY
        row.spacing = 0
        wrap.addSubview(row)

        if storeKitCoordinator.hasPremiumAccess {
            row.addArrangedSubview(footerLink("Manage Subscription", action: .manageSubscription))
            row.addArrangedSubview(footerLink("Restore Purchase", action: .restorePurchase))
        } else {
            row.addArrangedSubview(footerLink("Continue with free plan", action: .continueWithFreePlan))
        }
        row.addArrangedSubview(footerLink("Privacy Policy", action: .privacyPolicy))
        row.addArrangedSubview(footerLink("Support", action: .support))
        row.addArrangedSubview(footerLink("Terms of Services", action: .termsOfServices))

        NSLayoutConstraint.activate([
            row.leadingAnchor.constraint(equalTo: wrap.leadingAnchor),
            row.trailingAnchor.constraint(equalTo: wrap.trailingAnchor),
            row.topAnchor.constraint(equalTo: wrap.topAnchor),
            row.bottomAnchor.constraint(equalTo: wrap.bottomAnchor)
        ])

        return wrap
    }

    private func footerLink(_ title: String, action: PaywallFooterAction) -> NSView {
        let button = HoverButton(title: title, target: self, action: #selector(paywallFooterButtonPressed(_:)))
        button.translatesAutoresizingMaskIntoConstraints = false
        button.isBordered = false
        button.bezelStyle = .regularSquare
        button.focusRingType = .none
        button.font = NSFont.systemFont(ofSize: 12, weight: .semibold)
        button.alignment = .center
        button.setButtonType(.momentaryChange)
        button.contentTintColor = palette.textSecondary
        paywallFooterActionByView[ObjectIdentifier(button)] = action
        button.onHoverChanged = { [weak self, weak button] hovering in
            guard let self, let button else { return }
            button.contentTintColor = hovering ? (self.darkModeEnabled ? .white : self.palette.textPrimary) : self.palette.textSecondary
        }
        button.onHoverChanged?(false)
        return button
    }

    func paywallMetaItem(title: String, subtitle: String) -> NSView {
        let card = HoverTrackingView()
        card.translatesAutoresizingMaskIntoConstraints = false
        card.wantsLayer = true
        card.layer?.cornerRadius = 10
        card.layer?.backgroundColor = palette.inputBackground.cgColor
        card.heightAnchor.constraint(equalToConstant: 44).isActive = true
        styleSurface(card, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)

        let titleLabel = textLabel(title, font: NSFont.systemFont(ofSize: 11, weight: .semibold), color: palette.textPrimary)
        let subtitleLabel = textLabel(subtitle, font: NSFont.systemFont(ofSize: 10, weight: .medium), color: palette.textSecondary)
        card.addSubview(titleLabel)
        card.addSubview(subtitleLabel)
        NSLayoutConstraint.activate([
            titleLabel.centerXAnchor.constraint(equalTo: card.centerXAnchor),
            titleLabel.topAnchor.constraint(equalTo: card.topAnchor, constant: 7),
            subtitleLabel.centerXAnchor.constraint(equalTo: card.centerXAnchor),
            subtitleLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 1),
            subtitleLabel.bottomAnchor.constraint(lessThanOrEqualTo: card.bottomAnchor, constant: -6)
        ])

        let base = palette.inputBackground
        let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
        let hover = base.blended(withFraction: 0.10, of: hoverBlend) ?? base
        card.onHoverChanged = { [weak card] hovering in
            card?.layer?.backgroundColor = (hovering ? hover : base).cgColor
        }
        card.onHoverChanged?(false)
        return card
    }

    func paywallBenefitsSection() -> NSView {
        let stack = NSStackView()
        stack.translatesAutoresizingMaskIntoConstraints = false
        stack.orientation = .vertical
        stack.spacing = 8
        stack.alignment = .leading
        stack.widthAnchor.constraint(greaterThanOrEqualToConstant: paywallContentWidth).isActive = true

        let rowOne = NSStackView()
        rowOne.translatesAutoresizingMaskIntoConstraints = false
        rowOne.orientation = .horizontal
        rowOne.spacing = 10
        rowOne.distribution = .fillEqually
        rowOne.alignment = .centerY
        rowOne.addArrangedSubview(paywallBenefitItem(icon: "📅", text: "Manage meetings"))
        rowOne.addArrangedSubview(paywallBenefitItem(icon: "🖼️", text: "Virtual backgrounds"))

        let rowTwo = NSStackView()
        rowTwo.translatesAutoresizingMaskIntoConstraints = false
        rowTwo.orientation = .horizontal
        rowTwo.spacing = 10
        rowTwo.distribution = .fillEqually
        rowTwo.alignment = .centerY
        rowTwo.addArrangedSubview(paywallBenefitItem(icon: "⚡", text: "Tools for productivity"))
        rowTwo.addArrangedSubview(paywallBenefitItem(icon: "🛟", text: "24/7 support"))

        stack.addArrangedSubview(rowOne)
        stack.addArrangedSubview(rowTwo)
        return stack
    }

    func paywallBenefitItem(icon: String, text: String) -> NSView {
        let card = HoverTrackingView()
        card.translatesAutoresizingMaskIntoConstraints = false
        card.wantsLayer = true
        card.layer?.cornerRadius = 10
        card.layer?.backgroundColor = palette.inputBackground.cgColor
        card.heightAnchor.constraint(equalToConstant: 36).isActive = true
        styleSurface(card, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)

        let iconWrap = roundedContainer(cornerRadius: 8, color: palette.inputBackground)
        iconWrap.translatesAutoresizingMaskIntoConstraints = false
        iconWrap.widthAnchor.constraint(equalToConstant: 24).isActive = true
        iconWrap.heightAnchor.constraint(equalToConstant: 24).isActive = true
        styleSurface(iconWrap, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)

        let iconLabel = textLabel(icon, font: NSFont.systemFont(ofSize: 12, weight: .medium), color: palette.primaryBlue)
        iconWrap.addSubview(iconLabel)
        NSLayoutConstraint.activate([
            iconLabel.centerXAnchor.constraint(equalTo: iconWrap.centerXAnchor),
            iconLabel.centerYAnchor.constraint(equalTo: iconWrap.centerYAnchor)
        ])

        let title = textLabel(text, font: NSFont.systemFont(ofSize: 11, weight: .medium), color: palette.textPrimary)

        card.addSubview(iconWrap)
        card.addSubview(title)
        NSLayoutConstraint.activate([
            iconWrap.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 8),
            iconWrap.centerYAnchor.constraint(equalTo: card.centerYAnchor),
            title.leadingAnchor.constraint(equalTo: iconWrap.trailingAnchor, constant: 10),
            title.centerYAnchor.constraint(equalTo: card.centerYAnchor),
            title.trailingAnchor.constraint(lessThanOrEqualTo: card.trailingAnchor, constant: -8)
        ])

        let base = palette.inputBackground
        let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
        let hover = base.blended(withFraction: 0.10, of: hoverBlend) ?? base
        let hoverBorder = palette.primaryBlueBorder.withAlphaComponent(0.55)
        card.onHoverChanged = { [weak card, weak iconWrap] hovering in
            guard let card else { return }
            card.layer?.backgroundColor = (hovering ? hover : base).cgColor
            card.layer?.borderColor = (hovering ? hoverBorder : self.palette.inputBorder).cgColor
            iconWrap?.layer?.borderColor = (hovering ? hoverBorder : self.palette.inputBorder).cgColor
        }
        card.onHoverChanged?(false)
        return card
    }

    func zoomJoinModeTabs() -> NSView {
        let row = NSStackView()
        row.translatesAutoresizingMaskIntoConstraints = false
        row.orientation = .horizontal
        row.alignment = .centerY
        row.spacing = 28
        row.widthAnchor.constraint(greaterThanOrEqualToConstant: 780).isActive = true

        let idTab = joinModeTab("Join with ID", mode: .id)
        let urlTab = joinModeTab("Join with URL", mode: .url)
        row.addArrangedSubview(idTab)
        row.addArrangedSubview(urlTab)
        let spacer = NSView()
        spacer.translatesAutoresizingMaskIntoConstraints = false
        row.addArrangedSubview(spacer)

        zoomJoinModeViews[.id] = idTab
        zoomJoinModeViews[.url] = urlTab
        updateZoomJoinModeAppearance()
        return row
    }

    func joinModeTab(_ title: String, mode: ZoomJoinMode) -> NSView {
        let tab = HoverTrackingView()
        tab.translatesAutoresizingMaskIntoConstraints = false
        tab.wantsLayer = true
        tab.layer?.cornerRadius = 6
        tab.layer?.backgroundColor = NSColor.clear.cgColor
        tab.heightAnchor.constraint(equalToConstant: 30).isActive = true
        zoomJoinModeByView[ObjectIdentifier(tab)] = mode

        let label = textLabel(title, font: NSFont.systemFont(ofSize: 33 / 2, weight: .medium), color: palette.textPrimary)
        tab.addSubview(label)
        NSLayoutConstraint.activate([
            label.leadingAnchor.constraint(equalTo: tab.leadingAnchor, constant: 4),
            label.trailingAnchor.constraint(equalTo: tab.trailingAnchor, constant: -4),
            label.topAnchor.constraint(equalTo: tab.topAnchor, constant: 4),
            label.bottomAnchor.constraint(equalTo: tab.bottomAnchor, constant: -6)
        ])

        let click = NSClickGestureRecognizer(target: self, action: #selector(zoomJoinModeClicked(_:)))
        tab.addGestureRecognizer(click)
        return tab
    }

    func updateZoomJoinModeAppearance() {
        for (mode, tab) in zoomJoinModeViews {
            let selected = (mode == selectedZoomJoinMode)
            let textColor = selected ? palette.textPrimary : palette.textSecondary
            let label = tab.subviews.first { $0 is NSTextField } as? NSTextField
            label?.textColor = textColor

            // Keep the active tab visually underlined like the reference.
            if selected {
                if tab.subviews.contains(where: { $0.identifier?.rawValue == "modeUnderline" }) == false {
                    let underline = NSView()
                    underline.identifier = NSUserInterfaceItemIdentifier("modeUnderline")
                    underline.translatesAutoresizingMaskIntoConstraints = false
                    underline.wantsLayer = true
                    underline.layer?.backgroundColor = palette.primaryBlue.cgColor
                    tab.addSubview(underline)
                    NSLayoutConstraint.activate([
                        underline.leadingAnchor.constraint(equalTo: tab.leadingAnchor),
                        underline.trailingAnchor.constraint(equalTo: tab.trailingAnchor),
                        underline.bottomAnchor.constraint(equalTo: tab.bottomAnchor),
                        underline.heightAnchor.constraint(equalToConstant: 2)
                    ])
                }
            } else {
                tab.subviews
                    .filter { $0.identifier?.rawValue == "modeUnderline" }
                    .forEach { $0.removeFromSuperview() }
            }
        }
    }

    func joinWithIDHeading() -> NSView {
        let container = NSView()
        container.translatesAutoresizingMaskIntoConstraints = false

        let title = textLabel("Join with ID", font: typography.joinWithURLTitle, color: palette.textPrimary)
        title.alignment = .left
        title.setContentHuggingPriority(.defaultHigh, for: .horizontal)
        title.setContentCompressionResistancePriority(.required, for: .horizontal)

        let bar = NSView()
        bar.translatesAutoresizingMaskIntoConstraints = false
        bar.wantsLayer = true
        bar.layer?.backgroundColor = palette.primaryBlue.cgColor
        bar.heightAnchor.constraint(equalToConstant: 3).isActive = true

        container.addSubview(title)
        container.addSubview(bar)

        NSLayoutConstraint.activate([
            title.leadingAnchor.constraint(equalTo: container.leadingAnchor),
            title.topAnchor.constraint(equalTo: container.topAnchor),

            bar.leadingAnchor.constraint(equalTo: title.leadingAnchor),
            bar.topAnchor.constraint(equalTo: title.bottomAnchor, constant: 6),
            bar.widthAnchor.constraint(equalTo: title.widthAnchor),
            bar.bottomAnchor.constraint(equalTo: container.bottomAnchor),

            container.trailingAnchor.constraint(equalTo: title.trailingAnchor)
        ])

        return container
    }

    func zoomMeetingIDSection() -> NSView {
        let wrapper = NSView()
        wrapper.translatesAutoresizingMaskIntoConstraints = false

        let fieldsRow = NSStackView()
        fieldsRow.translatesAutoresizingMaskIntoConstraints = false
        fieldsRow.orientation = .horizontal
        fieldsRow.alignment = .top
        fieldsRow.distribution = .fillEqually
        fieldsRow.spacing = 12
        fieldsRow.addArrangedSubview(zoomInputField(title: "Meeting ID", placeholder: "Enter meeting ID..."))
        fieldsRow.addArrangedSubview(zoomInputField(title: "Meeting Passcode", placeholder: "Enter meeting passcode..."))

        let actions = NSStackView()
        actions.orientation = .horizontal
        actions.spacing = 10
        actions.translatesAutoresizingMaskIntoConstraints = false
        actions.alignment = .centerY
        actions.addArrangedSubview(actionButton(title: "Cancel", color: palette.cancelButton, textColor: palette.textSecondary, width: 110))
        actions.addArrangedSubview(actionButton(title: "Join", color: palette.primaryBlue, textColor: .white, width: 116))

        wrapper.addSubview(fieldsRow)
        wrapper.addSubview(actions)

        NSLayoutConstraint.activate([
            wrapper.widthAnchor.constraint(greaterThanOrEqualToConstant: 780),

            fieldsRow.leadingAnchor.constraint(equalTo: wrapper.leadingAnchor),
            fieldsRow.trailingAnchor.constraint(equalTo: wrapper.trailingAnchor),
            fieldsRow.topAnchor.constraint(equalTo: wrapper.topAnchor),

            actions.trailingAnchor.constraint(equalTo: wrapper.trailingAnchor),
            actions.topAnchor.constraint(equalTo: fieldsRow.bottomAnchor, constant: 14),
            actions.bottomAnchor.constraint(equalTo: wrapper.bottomAnchor)
        ])

        return wrapper
    }

    func zoomInputField(title: String, placeholder: String) -> NSView {
        let wrapper = NSView()
        wrapper.translatesAutoresizingMaskIntoConstraints = false

        let heading = textLabel(title, font: typography.fieldLabel, color: palette.textPrimary)
        let textFieldContainer = roundedContainer(cornerRadius: 10, color: palette.inputBackground)
        textFieldContainer.translatesAutoresizingMaskIntoConstraints = false
        textFieldContainer.heightAnchor.constraint(equalToConstant: 40).isActive = true
        styleSurface(textFieldContainer, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)

        let field = NSTextField(string: "")
        field.translatesAutoresizingMaskIntoConstraints = false
        field.isEditable = true
        field.isSelectable = true
        field.isBordered = false
        field.drawsBackground = false
        field.placeholderString = placeholder
        field.font = typography.inputPlaceholder
        field.textColor = palette.textPrimary
        field.focusRingType = .none
        textFieldContainer.addSubview(field)

        wrapper.addSubview(heading)
        wrapper.addSubview(textFieldContainer)

        NSLayoutConstraint.activate([
            heading.leadingAnchor.constraint(equalTo: wrapper.leadingAnchor),
            heading.topAnchor.constraint(equalTo: wrapper.topAnchor),

            textFieldContainer.leadingAnchor.constraint(equalTo: wrapper.leadingAnchor),
            textFieldContainer.trailingAnchor.constraint(equalTo: wrapper.trailingAnchor),
            textFieldContainer.topAnchor.constraint(equalTo: heading.bottomAnchor, constant: 10),
            textFieldContainer.bottomAnchor.constraint(equalTo: wrapper.bottomAnchor),

            field.leadingAnchor.constraint(equalTo: textFieldContainer.leadingAnchor, constant: 12),
            field.trailingAnchor.constraint(equalTo: textFieldContainer.trailingAnchor, constant: -12),
            field.centerYAnchor.constraint(equalTo: textFieldContainer.centerYAnchor)
        ])

        return wrapper
    }

    func joinWithURLHeading() -> NSView {
        let container = NSView()
        container.translatesAutoresizingMaskIntoConstraints = false

        let title = textLabel("Join with URL", font: typography.joinWithURLTitle, color: palette.textPrimary)
        title.alignment = .left
        title.setContentHuggingPriority(.defaultHigh, for: .horizontal)
        title.setContentCompressionResistancePriority(.required, for: .horizontal)

        let bar = NSView()
        bar.translatesAutoresizingMaskIntoConstraints = false
        bar.wantsLayer = true
        bar.layer?.backgroundColor = palette.primaryBlue.cgColor
        bar.heightAnchor.constraint(equalToConstant: 3).isActive = true

        container.addSubview(title)
        container.addSubview(bar)

        NSLayoutConstraint.activate([
            title.leadingAnchor.constraint(equalTo: container.leadingAnchor),
            title.topAnchor.constraint(equalTo: container.topAnchor),

            bar.leadingAnchor.constraint(equalTo: title.leadingAnchor),
            bar.topAnchor.constraint(equalTo: title.bottomAnchor, constant: 6),
            bar.widthAnchor.constraint(equalTo: title.widthAnchor),
            bar.bottomAnchor.constraint(equalTo: container.bottomAnchor),

            container.trailingAnchor.constraint(equalTo: title.trailingAnchor)
        ])

        return container
    }

    func meetingUrlSection() -> NSView {
        let wrapper = NSView()
        wrapper.translatesAutoresizingMaskIntoConstraints = false

        let title = textLabel("Meeting URL", font: typography.fieldLabel, color: palette.textSecondary)
        let textFieldContainer = roundedContainer(cornerRadius: 10, color: palette.inputBackground)
        textFieldContainer.translatesAutoresizingMaskIntoConstraints = false
        textFieldContainer.heightAnchor.constraint(equalToConstant: 40).isActive = true
        styleSurface(textFieldContainer, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)

        let urlField = NSTextField(string: "")
        urlField.translatesAutoresizingMaskIntoConstraints = false
        urlField.isEditable = true
        urlField.isSelectable = true
        urlField.isBordered = false
        urlField.drawsBackground = false
        urlField.placeholderString = "Enter meeting URL..."
        urlField.font = typography.inputPlaceholder
        urlField.textColor = palette.textPrimary
        urlField.focusRingType = .none
        textFieldContainer.addSubview(urlField)

        let actions = NSStackView()
        actions.orientation = .horizontal
        actions.spacing = 10
        actions.translatesAutoresizingMaskIntoConstraints = false
        actions.alignment = .centerY
        actions.addArrangedSubview(actionButton(title: "Cancel", color: palette.cancelButton, textColor: palette.textSecondary, width: 110))
        actions.addArrangedSubview(actionButton(title: "Join", color: palette.primaryBlue, textColor: .white, width: 116))

        wrapper.addSubview(title)
        wrapper.addSubview(textFieldContainer)
        wrapper.addSubview(actions)

        NSLayoutConstraint.activate([
            wrapper.widthAnchor.constraint(greaterThanOrEqualToConstant: 780),

            title.leadingAnchor.constraint(equalTo: wrapper.leadingAnchor),
            title.topAnchor.constraint(equalTo: wrapper.topAnchor),

            textFieldContainer.leadingAnchor.constraint(equalTo: wrapper.leadingAnchor),
            textFieldContainer.trailingAnchor.constraint(equalTo: wrapper.trailingAnchor),
            textFieldContainer.topAnchor.constraint(equalTo: title.bottomAnchor, constant: 10),

            urlField.leadingAnchor.constraint(equalTo: textFieldContainer.leadingAnchor, constant: 12),
            urlField.trailingAnchor.constraint(equalTo: textFieldContainer.trailingAnchor, constant: -12),
            urlField.centerYAnchor.constraint(equalTo: textFieldContainer.centerYAnchor),

            actions.trailingAnchor.constraint(equalTo: wrapper.trailingAnchor),
            actions.topAnchor.constraint(equalTo: textFieldContainer.bottomAnchor, constant: 14),
            actions.bottomAnchor.constraint(equalTo: wrapper.bottomAnchor)
        ])

        return wrapper
    }

    func scheduleHeader() -> NSView {
        let row = NSStackView()
        row.translatesAutoresizingMaskIntoConstraints = false
        row.orientation = .horizontal
        row.alignment = .centerY
        row.distribution = .fill
        row.spacing = 12

        row.addArrangedSubview(textLabel("Schedule", font: typography.sectionTitleBold, color: palette.textPrimary))

        let spacer = NSView()
        spacer.translatesAutoresizingMaskIntoConstraints = false
        row.addArrangedSubview(spacer)
        spacer.setContentHuggingPriority(.defaultLow, for: .horizontal)

        row.addArrangedSubview(makeScheduleRefreshButton())

        row.addArrangedSubview(makeScheduleFilterDropdown())
        row.widthAnchor.constraint(greaterThanOrEqualToConstant: 780).isActive = true
        return row
    }

    private func schedulePageHeader() -> NSView {
        let container = NSStackView()
        container.translatesAutoresizingMaskIntoConstraints = false
        container.userInterfaceLayoutDirection = .leftToRight
        container.orientation = .vertical
        container.spacing = 8
        container.alignment = .width

        let titleRow = NSStackView()
        titleRow.translatesAutoresizingMaskIntoConstraints = false
        titleRow.userInterfaceLayoutDirection = .leftToRight
        titleRow.orientation = .horizontal
        titleRow.alignment = .centerY
        titleRow.distribution = .fill
        titleRow.spacing = 0

        let titleLabel = textLabel("Schedule", font: typography.pageTitle, color: palette.textPrimary)
        titleLabel.alignment = .left
        titleLabel.userInterfaceLayoutDirection = .leftToRight
        titleLabel.maximumNumberOfLines = 1
        titleLabel.lineBreakMode = .byTruncatingTail
        titleLabel.setContentHuggingPriority(.required, for: .horizontal)
        titleLabel.setContentCompressionResistancePriority(.required, for: .horizontal)

        let titleRowSpacer = NSView()
        titleRowSpacer.translatesAutoresizingMaskIntoConstraints = false
        titleRowSpacer.setContentHuggingPriority(.defaultLow, for: .horizontal)
        titleRowSpacer.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)

        titleRow.addArrangedSubview(titleLabel)
        if hasGoogleSessionAvailable() && storeKitCoordinator.hasPremiumAccess {
            titleRow.addArrangedSubview(makeSchedulePageAddButton())
            titleRow.setCustomSpacing(12, after: titleLabel)
        }
        titleRow.addArrangedSubview(titleRowSpacer)
        container.addArrangedSubview(titleRow)

        let filterRow = NSStackView()
        filterRow.translatesAutoresizingMaskIntoConstraints = false
        filterRow.userInterfaceLayoutDirection = .leftToRight
        filterRow.orientation = .horizontal
        filterRow.alignment = .centerY
        filterRow.spacing = 18
        filterRow.distribution = .fill

        let filterDropdown = makeSchedulePageFilterDropdown()
        schedulePageFilterDropdown = filterDropdown
        filterRow.addArrangedSubview(filterDropdown)
        filterRow.setCustomSpacing(20, after: filterDropdown)

        let (fromShell, fromPicker) = makeScheduleDatePicker(date: schedulePageFromDate)
        schedulePageFromDatePicker = fromPicker
        filterRow.addArrangedSubview(fromShell)
        filterRow.setCustomSpacing(16, after: fromShell)

        let (toShell, toPicker) = makeScheduleDatePicker(date: schedulePageToDate)
        schedulePageToDatePicker = toPicker
        filterRow.addArrangedSubview(toShell)
        NSLayoutConstraint.activate([
            fromShell.widthAnchor.constraint(equalTo: toShell.widthAnchor),
            fromShell.widthAnchor.constraint(greaterThanOrEqualToConstant: 152)
        ])

        let filterRowSpacer = NSView()
        filterRowSpacer.translatesAutoresizingMaskIntoConstraints = false
        filterRowSpacer.setContentHuggingPriority(.defaultLow, for: .horizontal)
        filterRowSpacer.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
        filterRow.addArrangedSubview(filterRowSpacer)

        let applyButton = makeSchedulePagePillButton(title: "Apply", action: #selector(schedulePageApplyDateRangePressed(_:)))
        filterRow.addArrangedSubview(applyButton)
        filterRow.setCustomSpacing(22, after: applyButton)
        let resetButton = makeSchedulePagePillButton(title: "Reset", action: #selector(schedulePageResetFiltersPressed(_:)))
        filterRow.addArrangedSubview(resetButton)
        filterRow.setCustomSpacing(22, after: resetButton)
        filterRow.addArrangedSubview(makeScheduleRefreshButton())

        container.addArrangedSubview(filterRow)
        NSLayoutConstraint.activate([
            titleRow.widthAnchor.constraint(equalTo: container.widthAnchor),
            filterRow.widthAnchor.constraint(equalTo: container.widthAnchor)
        ])
        refreshSchedulePageDateFilterUI()
        return container
    }

    private func makeSchedulePageFilterDropdown() -> NSPopUpButton {
        let button = HoverPopUpButton(frame: .zero, pullsDown: false)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.autoenablesItems = false
        button.isBordered = false
        button.bezelStyle = .regularSquare
        button.wantsLayer = true
        button.layer?.cornerRadius = 8
        button.layer?.masksToBounds = true
        button.layer?.backgroundColor = palette.inputBackground.cgColor
        button.layer?.borderColor = palette.inputBorder.cgColor
        button.layer?.borderWidth = 1
        button.font = typography.filterText
        button.contentTintColor = palette.textSecondary
        button.target = self
        button.action = #selector(schedulePageFilterDropdownChanged(_:))
        button.heightAnchor.constraint(equalToConstant: 34).isActive = true
        button.widthAnchor.constraint(equalToConstant: 228).isActive = true

        button.removeAllItems()
        button.addItems(withTitles: ["All", "Today", "This week", "This month", "Custom range"])
        button.selectItem(at: schedulePageFilter.rawValue)
        if let menu = button.menu {
            for (index, item) in menu.items.enumerated() {
                item.tag = index
            }
        }

        let baseColor = palette.inputBackground
        let baseBorder = palette.inputBorder
        let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
        let hoverColor = baseColor.blended(withFraction: 0.10, of: hoverBlend) ?? baseColor
        let hoverBorder = baseBorder.blended(withFraction: 0.16, of: hoverBlend) ?? baseBorder
        button.onHoverChanged = { [weak button] hovering in
            button?.layer?.backgroundColor = (hovering ? hoverColor : baseColor).cgColor
            button?.layer?.borderColor = (hovering ? hoverBorder : baseBorder).cgColor
        }
        button.onHoverChanged?(false)
        return button
    }

    /// Rounded shell matching `makeSchedulePageFilterDropdown` (34pt, 8pt corner, border + hover). Both pickers use the same field+stepper style inside the shell.
    private func makeFilterStyleDatePicker(date: Date, changeAction: Selector) -> (NSView, NSDatePicker) {
        let shell = HoverSurfaceView()
        shell.translatesAutoresizingMaskIntoConstraints = false
        shell.wantsLayer = true
        shell.layer?.cornerRadius = 8
        shell.layer?.masksToBounds = true
        shell.layer?.borderWidth = 1

        let baseColor = palette.inputBackground
        let baseBorder = palette.inputBorder
        let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
        let hoverBackground = baseColor.blended(withFraction: 0.10, of: hoverBlend) ?? baseColor
        let hoverBorder = baseBorder.blended(withFraction: 0.16, of: hoverBlend) ?? baseBorder

        func applyShellIdleAppearance() {
            shell.layer?.backgroundColor = baseColor.cgColor
            shell.layer?.borderColor = baseBorder.cgColor
        }
        applyShellIdleAppearance()

        shell.onHoverChanged = { [weak shell] hovering in
            guard let shell else { return }
            shell.layer?.backgroundColor = (hovering ? hoverBackground : baseColor).cgColor
            shell.layer?.borderColor = (hovering ? hoverBorder : baseBorder).cgColor
        }

        let picker = NSDatePicker()
        picker.translatesAutoresizingMaskIntoConstraints = false
        picker.isBordered = false
        picker.drawsBackground = false
        picker.focusRingType = .none
        picker.datePickerStyle = .textFieldAndStepper
        picker.datePickerElements = [.yearMonthDay]
        picker.dateValue = date
        picker.font = typography.filterText
        picker.textColor = palette.textSecondary
        picker.setContentHuggingPriority(.defaultLow, for: .horizontal)
        picker.target = self
        picker.action = changeAction

        shell.addSubview(picker)
        NSLayoutConstraint.activate([
            shell.heightAnchor.constraint(equalToConstant: 34),
            picker.leadingAnchor.constraint(equalTo: shell.leadingAnchor, constant: 8),
            picker.trailingAnchor.constraint(equalTo: shell.trailingAnchor, constant: -8),
            picker.centerYAnchor.constraint(equalTo: shell.centerYAnchor)
        ])

        return (shell, picker)
    }

    private func makeScheduleDatePicker(date: Date) -> (NSView, NSDatePicker) {
        makeFilterStyleDatePicker(date: date, changeAction: #selector(schedulePageDatePickerChanged(_:)))
    }

    private func makeSchedulePagePillButton(title: String, action: Selector) -> NSButton {
        let button = makeSchedulePillButton(title: title)
        button.target = self
        button.action = action
        button.widthAnchor.constraint(equalToConstant: 100).isActive = true
        return button
    }

    private func makeSchedulePageCardsContainer() -> NSView {
        if let observer = schedulePageScrollObservation {
            NotificationCenter.default.removeObserver(observer)
        }
        schedulePageScrollObservation = nil

        let wrapper = NSView()
        wrapper.translatesAutoresizingMaskIntoConstraints = false
        wrapper.userInterfaceLayoutDirection = .leftToRight

        let scroll = NSScrollView()
        scroll.translatesAutoresizingMaskIntoConstraints = false
        scroll.userInterfaceLayoutDirection = .leftToRight
        scroll.drawsBackground = false
        scroll.hasHorizontalScroller = false
        scroll.hasVerticalScroller = true
        scroll.autohidesScrollers = true
        scroll.borderType = .noBorder
        scroll.scrollerStyle = .overlay
        scroll.automaticallyAdjustsContentInsets = false
        let clip = TopAlignedClipView()
        clip.drawsBackground = false
        clip.postsBoundsChangedNotifications = true
        scroll.contentView = clip
        schedulePageCardsScrollView = scroll
        wrapper.addSubview(scroll)

        let stack = NSStackView()
        stack.translatesAutoresizingMaskIntoConstraints = false
        stack.userInterfaceLayoutDirection = .leftToRight
        stack.orientation = .vertical
        stack.spacing = schedulePageCardSpacing
        stack.alignment = .width
        schedulePageCardsStack = stack
        scroll.documentView = stack

        NSLayoutConstraint.activate([
            scroll.leadingAnchor.constraint(equalTo: wrapper.leadingAnchor),
            scroll.trailingAnchor.constraint(equalTo: wrapper.trailingAnchor),
            scroll.topAnchor.constraint(equalTo: wrapper.topAnchor),
            scroll.bottomAnchor.constraint(equalTo: wrapper.bottomAnchor),
            scroll.heightAnchor.constraint(greaterThanOrEqualToConstant: 420),

            stack.leadingAnchor.constraint(equalTo: scroll.contentView.leadingAnchor),
            stack.trailingAnchor.constraint(equalTo: scroll.contentView.trailingAnchor),
            stack.topAnchor.constraint(equalTo: scroll.contentView.topAnchor),
            stack.widthAnchor.constraint(equalTo: scroll.contentView.widthAnchor)
        ])

        scroll.contentView.postsBoundsChangedNotifications = true
        schedulePageScrollObservation = NotificationCenter.default.addObserver(
            forName: NSView.boundsDidChangeNotification,
            object: scroll.contentView,
            queue: .main
        ) { [weak self] _ in
            self?.schedulePageScrolled()
        }

        renderSchedulePageCards()
        return wrapper
    }

    private func scheduleTopAuthRow() -> NSView {
        let row = NSStackView()
        row.translatesAutoresizingMaskIntoConstraints = false
        row.orientation = .horizontal
        row.alignment = .centerY
        row.spacing = 10

        let spacer = NSView()
        spacer.translatesAutoresizingMaskIntoConstraints = false
        row.addArrangedSubview(spacer)
        spacer.setContentHuggingPriority(.defaultLow, for: .horizontal)

        let host = GoogleProfileAuthHostView()
        host.translatesAutoresizingMaskIntoConstraints = false
        let authButton = makeGoogleAuthButton()
        host.authButton = authButton
        scheduleGoogleAuthHostView = host
        scheduleGoogleAuthButton = authButton
        host.addSubview(authButton)
        NSLayoutConstraint.activate([
            authButton.centerXAnchor.constraint(equalTo: host.centerXAnchor),
            authButton.centerYAnchor.constraint(equalTo: host.centerYAnchor)
        ])
        let hostPadW = host.widthAnchor.constraint(equalTo: authButton.widthAnchor, constant: 0)
        let hostPadH = host.heightAnchor.constraint(equalTo: authButton.heightAnchor, constant: 0)
        hostPadW.isActive = true
        hostPadH.isActive = true
        scheduleGoogleAuthHostPadWidthConstraint = hostPadW
        scheduleGoogleAuthHostPadHeightConstraint = hostPadH
        updateGoogleAuthButtonTitle()
        row.addArrangedSubview(host)

        row.widthAnchor.constraint(greaterThanOrEqualToConstant: 780).isActive = true
        return row
    }

    private func makeScheduleFilterDropdown() -> NSPopUpButton {
        let button = HoverPopUpButton(frame: .zero, pullsDown: false)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.autoenablesItems = false
        button.isBordered = false
        button.bezelStyle = .regularSquare
        button.wantsLayer = true
        button.layer?.cornerRadius = 8
        button.layer?.masksToBounds = true
        button.layer?.backgroundColor = palette.inputBackground.cgColor
        button.layer?.borderColor = palette.inputBorder.cgColor
        button.layer?.borderWidth = 1
        button.font = typography.filterText
        button.contentTintColor = palette.textSecondary
        button.target = self
        button.action = #selector(scheduleFilterDropdownChanged(_:))
        button.heightAnchor.constraint(equalToConstant: 34).isActive = true
        button.widthAnchor.constraint(equalToConstant: 156).isActive = true

        button.removeAllItems()
        button.addItems(withTitles: ["All", "Today", "This week"])
        button.selectItem(at: scheduleFilter.rawValue)

        if let menu = button.menu {
            for (index, item) in menu.items.enumerated() {
                item.tag = index
            }
        }

        let baseColor = palette.inputBackground
        let baseBorder = palette.inputBorder
        let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
        let hoverColor = baseColor.blended(withFraction: 0.10, of: hoverBlend) ?? baseColor
        let hoverBorder = baseBorder.blended(withFraction: 0.16, of: hoverBlend) ?? baseBorder
        button.onHoverChanged = { [weak button] hovering in
            button?.layer?.backgroundColor = (hovering ? hoverColor : baseColor).cgColor
            button?.layer?.borderColor = (hovering ? hoverBorder : baseBorder).cgColor
        }
        button.onHoverChanged?(false)

        scheduleFilterDropdown = button
        return button
    }

    private func makeSchedulePillButton(title: String) -> NSButton {
        let button = NSButton(title: title, target: nil, action: nil)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.isBordered = false
        button.bezelStyle = .regularSquare
        button.wantsLayer = true
        button.layer?.cornerRadius = 8
        button.layer?.backgroundColor = palette.inputBackground.cgColor
        button.layer?.borderColor = palette.inputBorder.cgColor
        button.layer?.borderWidth = 1
        button.font = typography.filterText
        button.contentTintColor = palette.textSecondary
        button.setButtonType(.momentaryChange)
        button.heightAnchor.constraint(equalToConstant: 34).isActive = true
        button.widthAnchor.constraint(greaterThanOrEqualToConstant: 132).isActive = true
        return button
    }

    private func makeGoogleAuthButton() -> NSButton {
        let button = HoverButton(title: "", target: self, action: #selector(scheduleConnectButtonPressed(_:)))
        button.translatesAutoresizingMaskIntoConstraints = false
        button.isBordered = false
        button.bezelStyle = .regularSquare
        button.wantsLayer = true
        button.layer?.cornerRadius = 16
        button.layer?.borderWidth = 1
        button.font = NSFont.systemFont(ofSize: 14, weight: .semibold)
        button.imagePosition = .imageLeading
        button.alignment = .center
        button.imageHugsTitle = true
        button.lineBreakMode = .byTruncatingTail
        button.contentTintColor = palette.textPrimary
        button.imageScaling = .scaleNone
        button.layer?.masksToBounds = true
        let heightConstraint = button.heightAnchor.constraint(equalToConstant: 42)
        heightConstraint.isActive = true
        scheduleGoogleAuthButtonHeightConstraint = heightConstraint
        let widthConstraint = button.widthAnchor.constraint(equalToConstant: 248)
        widthConstraint.isActive = true
        scheduleGoogleAuthButtonWidthConstraint = widthConstraint
        button.onHoverChanged = { [weak self] hovering in
            self?.scheduleGoogleAuthHovering = hovering
            self?.scheduleGoogleAuthHostView?.setProfileHoverActive(hovering)
            self?.applyGoogleAuthButtonSurface()
        }
        button.onHoverChanged?(false)
        return button
    }

    private func makeSchedulePageAddButton() -> NSButton {
        let diameter: CGFloat = 30
        let button = HoverButton(title: "", target: self, action: #selector(schedulePageAddMeetingPressed(_:)))
        button.translatesAutoresizingMaskIntoConstraints = false
        button.isBordered = false
        button.bezelStyle = .regularSquare
        button.wantsLayer = true
        button.layer?.cornerRadius = diameter / 2
        button.layer?.masksToBounds = true
        button.layer?.backgroundColor = palette.inputBackground.cgColor
        button.layer?.borderColor = palette.inputBorder.cgColor
        button.layer?.borderWidth = 1
        button.setButtonType(.momentaryChange)
        button.contentTintColor = palette.textSecondary
        button.image = NSImage(systemSymbolName: "plus", accessibilityDescription: "Schedule meeting")
        button.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 14, weight: .semibold)
        button.imagePosition = .imageOnly
        button.imageScaling = .scaleProportionallyDown
        button.focusRingType = .none
        button.heightAnchor.constraint(equalToConstant: diameter).isActive = true
        button.widthAnchor.constraint(equalToConstant: diameter).isActive = true
        let baseColor = palette.inputBackground
        let baseBorder = palette.inputBorder
        let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
        let hoverColor = baseColor.blended(withFraction: 0.10, of: hoverBlend) ?? baseColor
        let hoverBorder = baseBorder.blended(withFraction: 0.16, of: hoverBlend) ?? baseBorder
        button.onHoverChanged = { [weak button] hovering in
            button?.layer?.backgroundColor = (hovering ? hoverColor : baseColor).cgColor
            button?.layer?.borderColor = (hovering ? hoverBorder : baseBorder).cgColor
        }
        button.onHoverChanged?(false)
        return button
    }

    private func makeScheduleRefreshButton(
        action: Selector = #selector(scheduleReloadButtonPressed(_:)),
        accessibilityDescription: String = "Refresh meetings"
    ) -> NSButton {
        let diameter: CGFloat = 30
        let button = HoverButton(title: "", target: self, action: action)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.isBordered = false
        button.bezelStyle = .regularSquare
        button.wantsLayer = true
        button.layer?.cornerRadius = diameter / 2
        button.layer?.masksToBounds = true
        button.layer?.backgroundColor = palette.inputBackground.cgColor
        button.layer?.borderColor = palette.inputBorder.cgColor
        button.layer?.borderWidth = 1
        button.setButtonType(.momentaryChange)
        button.contentTintColor = palette.textSecondary
        button.image = NSImage(systemSymbolName: "arrow.clockwise", accessibilityDescription: accessibilityDescription)
        button.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 14, weight: .semibold)
        button.imagePosition = .imageOnly
        button.imageScaling = .scaleProportionallyDown
        button.focusRingType = .none
        button.heightAnchor.constraint(equalToConstant: diameter).isActive = true
        button.widthAnchor.constraint(equalToConstant: diameter).isActive = true
        let baseColor = palette.inputBackground
        let baseBorder = palette.inputBorder
        let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
        let hoverColor = baseColor.blended(withFraction: 0.10, of: hoverBlend) ?? baseColor
        let hoverBorder = baseBorder.blended(withFraction: 0.16, of: hoverBlend) ?? baseBorder
        button.onHoverChanged = { [weak button] hovering in
            button?.layer?.backgroundColor = (hovering ? hoverColor : baseColor).cgColor
            button?.layer?.borderColor = (hovering ? hoverBorder : baseBorder).cgColor
        }
        button.onHoverChanged?(false)
        return button
    }

    func scheduleCardsRow(meetings: [ScheduledMeeting]) -> NSView {
        let cardWidth: CGFloat = 240
        let cardsPerViewport: CGFloat = 3
        let viewportWidth = (cardWidth * cardsPerViewport) + (12 * (cardsPerViewport - 1))

        let wrapper = NSStackView()
        wrapper.translatesAutoresizingMaskIntoConstraints = false
        wrapper.orientation = .horizontal
        wrapper.alignment = .centerY
        wrapper.spacing = 10
        let leftButton = makeScheduleScrollButton(systemSymbol: "chevron.left", action: #selector(scheduleScrollLeftPressed(_:)))
        scheduleScrollLeftButton = leftButton
        wrapper.addArrangedSubview(leftButton)

        let scroll = NSScrollView()
        scheduleCardsScrollView = scroll
        scroll.translatesAutoresizingMaskIntoConstraints = false
        scroll.drawsBackground = false
        scroll.hasHorizontalScroller = false
        scroll.hasVerticalScroller = false
        scroll.horizontalScrollElasticity = .allowed
        scroll.verticalScrollElasticity = .none
        scroll.autohidesScrollers = false
        scroll.borderType = .noBorder
        scroll.automaticallyAdjustsContentInsets = false
        scroll.heightAnchor.constraint(equalToConstant: 150).isActive = true
        scroll.widthAnchor.constraint(equalToConstant: viewportWidth).isActive = true

        let row = NSStackView()
        row.translatesAutoresizingMaskIntoConstraints = false
        row.orientation = .horizontal
        row.spacing = 12
        row.alignment = .top
        row.distribution = .gravityAreas
        row.setContentHuggingPriority(.defaultHigh, for: .horizontal)
        row.heightAnchor.constraint(equalToConstant: 150).isActive = true
        scheduleCardsStack = row

        scroll.documentView = row
        scroll.contentView.postsBoundsChangedNotifications = true

        // Pin top/leading/trailing only; avoid bottom == clip so the horizontal stack is not stretched vertically inside the clip (same as Schedule cards scroll).
        NSLayoutConstraint.activate([
            row.leadingAnchor.constraint(equalTo: scroll.contentView.leadingAnchor),
            row.trailingAnchor.constraint(greaterThanOrEqualTo: scroll.contentView.trailingAnchor),
            row.topAnchor.constraint(equalTo: scroll.contentView.topAnchor),
            row.heightAnchor.constraint(equalToConstant: 150)
        ])

        renderScheduleCards(into: row, meetings: meetings)
        wrapper.addArrangedSubview(scroll)
        let rightButton = makeScheduleScrollButton(systemSymbol: "chevron.right", action: #selector(scheduleScrollRightPressed(_:)))
        scheduleScrollRightButton = rightButton
        wrapper.addArrangedSubview(rightButton)
        scroll.setContentHuggingPriority(.defaultLow, for: .horizontal)
        scroll.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
        wrapper.widthAnchor.constraint(greaterThanOrEqualToConstant: 780).isActive = true
        return wrapper
    }

    func scheduleCard(meeting: ScheduledMeeting, useFlexibleWidth: Bool = false, contentHeight: CGFloat = 150) -> NSView {
        let cardWidth: CGFloat = 240

        let card = roundedContainer(cornerRadius: 12, color: palette.sectionCard)
        styleSurface(card, borderColor: palette.inputBorder, borderWidth: 1, shadow: true)
        card.translatesAutoresizingMaskIntoConstraints = false
        card.heightAnchor.constraint(equalToConstant: contentHeight).isActive = true
        if useFlexibleWidth {
            card.setContentHuggingPriority(.defaultLow, for: .horizontal)
            card.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
        } else {
            card.widthAnchor.constraint(equalToConstant: cardWidth).isActive = true
            card.setContentHuggingPriority(.required, for: .horizontal)
            card.setContentCompressionResistancePriority(.required, for: .horizontal)
        }

        let icon = roundedContainer(cornerRadius: 8, color: palette.meetingBadge)
        icon.translatesAutoresizingMaskIntoConstraints = false
        icon.widthAnchor.constraint(equalToConstant: 28).isActive = true
        icon.heightAnchor.constraint(equalToConstant: 28).isActive = true
        let iconView = NSImageView()
        iconView.translatesAutoresizingMaskIntoConstraints = false
        iconView.image = NSImage(systemSymbolName: "video.circle.fill", accessibilityDescription: "Meeting")
        iconView.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 18, weight: .semibold)
        iconView.contentTintColor = .white
        icon.addSubview(iconView)
        NSLayoutConstraint.activate([
            iconView.centerXAnchor.constraint(equalTo: icon.centerXAnchor),
            iconView.centerYAnchor.constraint(equalTo: icon.centerYAnchor)
        ])

        let title = textLabel(meeting.title, font: typography.cardTitle, color: palette.textPrimary)
        title.lineBreakMode = .byTruncatingTail
        title.maximumNumberOfLines = 1
        title.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
        let subtitle = textLabel(meeting.subtitle ?? "Google Calendar", font: typography.cardSubtitle, color: palette.textPrimary)
        let time = textLabel(scheduleTimeText(for: meeting), font: typography.cardTime, color: palette.textSecondary)
        let duration = textLabel(scheduleDurationText(for: meeting), font: NSFont.systemFont(ofSize: 11, weight: .medium), color: palette.textMuted)
        let dayChip = roundedContainer(cornerRadius: 7, color: palette.inputBackground)
        dayChip.translatesAutoresizingMaskIntoConstraints = false
        dayChip.layer?.borderWidth = 1
        dayChip.layer?.borderColor = palette.inputBorder.withAlphaComponent(0.8).cgColor
        let dayText = textLabel(scheduleDayText(for: meeting), font: NSFont.systemFont(ofSize: 11, weight: .semibold), color: palette.textSecondary)
        dayText.translatesAutoresizingMaskIntoConstraints = false
        dayChip.addSubview(dayText)
        NSLayoutConstraint.activate([
            dayText.leadingAnchor.constraint(equalTo: dayChip.leadingAnchor, constant: 8),
            dayText.trailingAnchor.constraint(equalTo: dayChip.trailingAnchor, constant: -8),
            dayText.topAnchor.constraint(equalTo: dayChip.topAnchor, constant: 4),
            dayText.bottomAnchor.constraint(equalTo: dayChip.bottomAnchor, constant: -4)
        ])

        card.addSubview(icon)
        card.addSubview(dayChip)
        card.addSubview(title)
        card.addSubview(subtitle)
        card.addSubview(time)
        card.addSubview(duration)

        var titleConstraints: [NSLayoutConstraint] = [
            icon.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 10),
            icon.topAnchor.constraint(equalTo: card.topAnchor, constant: 10),

            dayChip.trailingAnchor.constraint(equalTo: card.trailingAnchor, constant: -10),
            dayChip.centerYAnchor.constraint(equalTo: icon.centerYAnchor),

            title.leadingAnchor.constraint(equalTo: icon.trailingAnchor, constant: 6),
            title.centerYAnchor.constraint(equalTo: icon.centerYAnchor),
            title.trailingAnchor.constraint(lessThanOrEqualTo: dayChip.leadingAnchor, constant: -8)
        ]
        if !useFlexibleWidth {
            titleConstraints.append(title.widthAnchor.constraint(lessThanOrEqualToConstant: 130))
        }
        NSLayoutConstraint.activate(titleConstraints + [
            subtitle.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 10),
            subtitle.topAnchor.constraint(equalTo: icon.bottomAnchor, constant: 10),
            subtitle.trailingAnchor.constraint(lessThanOrEqualTo: card.trailingAnchor, constant: -10),

            time.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 10),
            time.topAnchor.constraint(equalTo: subtitle.bottomAnchor, constant: 5),
            time.trailingAnchor.constraint(lessThanOrEqualTo: card.trailingAnchor, constant: -10),

            duration.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 10),
            duration.topAnchor.constraint(equalTo: time.bottomAnchor, constant: 4),
            duration.trailingAnchor.constraint(lessThanOrEqualTo: card.trailingAnchor, constant: -10)
        ])

        let hit = HoverButton(title: "", target: self, action: #selector(scheduleCardButtonPressed(_:)))
        hit.translatesAutoresizingMaskIntoConstraints = false
        hit.isBordered = false
        hit.bezelStyle = .regularSquare
        hit.identifier = NSUserInterfaceItemIdentifier(meeting.meetURL.absoluteString)
        hit.heightAnchor.constraint(equalToConstant: contentHeight).isActive = true
        if useFlexibleWidth {
            hit.setContentHuggingPriority(.defaultLow, for: .horizontal)
            hit.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
        } else {
            hit.widthAnchor.constraint(equalToConstant: cardWidth).isActive = true
            hit.setContentHuggingPriority(.required, for: .horizontal)
            hit.setContentCompressionResistancePriority(.required, for: .horizontal)
        }
        hit.addSubview(card)
        NSLayoutConstraint.activate([
            card.leadingAnchor.constraint(equalTo: hit.leadingAnchor),
            card.trailingAnchor.constraint(equalTo: hit.trailingAnchor),
            card.topAnchor.constraint(equalTo: hit.topAnchor),
            card.bottomAnchor.constraint(equalTo: hit.bottomAnchor)
        ])
        hit.onHoverChanged = { [weak self] hovering in
            guard let self else { return }
            let base = self.palette.sectionCard
            let hoverBlend = self.darkModeEnabled ? NSColor.white : NSColor.black
            let hover = base.blended(withFraction: 0.10, of: hoverBlend) ?? base
            if self.storeKitCoordinator.hasPremiumAccess {
                card.layer?.backgroundColor = (hovering ? hover : base).cgColor
            } else {
                card.layer?.backgroundColor = base.cgColor
            }
        }
        hit.onHoverChanged?(false)

        if !storeKitCoordinator.hasPremiumAccess {
            let lockOverlay = NSVisualEffectView()
            lockOverlay.translatesAutoresizingMaskIntoConstraints = false
            lockOverlay.material = darkModeEnabled ? .hudWindow : .popover
            lockOverlay.blendingMode = .withinWindow
            lockOverlay.state = .active
            lockOverlay.wantsLayer = true
            lockOverlay.layer?.cornerRadius = 12
            lockOverlay.layer?.masksToBounds = true
            lockOverlay.layer?.backgroundColor = NSColor.black.withAlphaComponent(darkModeEnabled ? 0.28 : 0.12).cgColor

            let lockLabel = textLabel("Get Premium to see events", font: NSFont.systemFont(ofSize: 12, weight: .semibold), color: darkModeEnabled ? .white : .black)
            lockLabel.alignment = .center

            card.addSubview(lockOverlay)
            lockOverlay.addSubview(lockLabel)
            NSLayoutConstraint.activate([
                lockOverlay.leadingAnchor.constraint(equalTo: card.leadingAnchor),
                lockOverlay.trailingAnchor.constraint(equalTo: card.trailingAnchor),
                lockOverlay.topAnchor.constraint(equalTo: card.topAnchor),
                lockOverlay.bottomAnchor.constraint(equalTo: card.bottomAnchor),
                lockLabel.centerXAnchor.constraint(equalTo: lockOverlay.centerXAnchor),
                lockLabel.centerYAnchor.constraint(equalTo: lockOverlay.centerYAnchor),
                lockLabel.leadingAnchor.constraint(greaterThanOrEqualTo: lockOverlay.leadingAnchor, constant: 10),
                lockLabel.trailingAnchor.constraint(lessThanOrEqualTo: lockOverlay.trailingAnchor, constant: -10)
            ])
            hit.toolTip = "Premium required. Click to open paywall."
        }

        return hit
    }

    private func makeScheduleScrollButton(systemSymbol: String, action: Selector) -> NSButton {
        let button = NSButton(title: "", target: self, action: action)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.isBordered = false
        button.bezelStyle = .regularSquare
        button.wantsLayer = true
        button.layer?.cornerRadius = 16
        button.layer?.backgroundColor = palette.inputBackground.cgColor
        button.layer?.borderColor = palette.inputBorder.cgColor
        button.layer?.borderWidth = 1
        button.image = NSImage(systemSymbolName: systemSymbol, accessibilityDescription: "Scroll meetings")
        button.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 13, weight: .semibold)
        button.imagePosition = .imageOnly
        button.imageScaling = .scaleProportionallyDown
        button.contentTintColor = palette.textSecondary
        button.focusRingType = .none
        button.heightAnchor.constraint(equalToConstant: 32).isActive = true
        button.widthAnchor.constraint(equalToConstant: 32).isActive = true
        return button
    }
}

private extension PremiumPlan {
    var displayName: String {
        switch self {
        case .weekly: return "Weekly"
        case .monthly: return "Monthly"
        case .yearly: return "Yearly"
        case .lifetime: return "Lifetime"
        }
    }
}

extension ViewController: NSTextFieldDelegate {
    func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
        if control === browseAddressField, commandSelector == #selector(NSResponder.insertNewline(_:)) {
            browseOpenAddressClicked(nil)
            return true
        }
        return false
    }
}

extension ViewController: AVSpeechSynthesizerDelegate {
    func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) {
        DispatchQueue.main.async { [weak self] in
            guard let self else { return }
            guard self.aiCompanionSpeechSynthesizer === synthesizer else { return }
            guard let buttonId = self.aiCompanionCurrentlySpeakingButtonId else { return }

            self.aiCompanionIsUsingSpeech = false
            self.aiCompanionCurrentlySpeakingButtonId = nil

            if let button = self.aiCompanionCurrentlyPlayingButton, ObjectIdentifier(button) == buttonId {
                button.title = "Play Audio"
            }
            self.aiCompanionAudioStatusLabelByView[buttonId]?.stringValue = "Finished"
        }
    }

    func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didCancel utterance: AVSpeechUtterance) {
        DispatchQueue.main.async { [weak self] in
            guard let self else { return }
            guard self.aiCompanionSpeechSynthesizer === synthesizer else { return }
            guard let buttonId = self.aiCompanionCurrentlySpeakingButtonId else { return }

            self.aiCompanionIsUsingSpeech = false
            self.aiCompanionCurrentlySpeakingButtonId = nil

            if let button = self.aiCompanionCurrentlyPlayingButton, ObjectIdentifier(button) == buttonId {
                button.title = "Play Audio"
            }
            self.aiCompanionAudioStatusLabelByView[buttonId]?.stringValue = "Stopped"
        }
    }
}

extension ViewController: AVAudioPlayerDelegate {
    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
        DispatchQueue.main.async { [weak self] in
            guard let self else { return }
            guard self.aiCompanionLocalAudioPlayer === player else { return }
            self.aiCompanionAudioDidFinish()
        }
    }

    func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer, error: Error?) {
        DispatchQueue.main.async { [weak self] in
            guard let self else { return }
            guard self.aiCompanionLocalAudioPlayer === player else { return }
            if let button = self.aiCompanionCurrentlyPlayingButton {
                let buttonId = ObjectIdentifier(button)
                button.title = "Play Audio"
                self.aiCompanionAudioStatusLabelByView[buttonId]?.stringValue = "Failed: \(error?.localizedDescription ?? "decode error")"
            }
            self.aiCompanionAudioPlayer?.pause()
            self.aiCompanionAudioPlayer = nil
            self.aiCompanionLocalAudioPlayer?.stop()
            self.aiCompanionLocalAudioPlayer = nil
            self.aiCompanionCurrentlyPlayingURL = nil
            self.aiCompanionCurrentlyPlayingButton = nil
            self.aiCompanionTimeControlObserver = nil
        }
    }
}

extension ViewController: NSWindowDelegate {
    func windowWillClose(_ notification: Notification) {
        guard let closingWindow = notification.object as? NSWindow else { return }
        if closingWindow === aiCompanionNotesPanel {
            aiCompanionStopNotesOutsideClickMonitor()
            aiCompanionNotesPanel = nil
            aiCompanionNotesRootView = nil
            aiCompanionNotesHeaderView = nil
            aiCompanionNotesTitleLabel = nil
            aiCompanionNotesSubtitleLabel = nil
            aiCompanionNotesTextView = nil
            aiCompanionNotesCopyButton = nil
            aiCompanionNotesCloseButton = nil
            return
        }
        if closingWindow === paywallWindow {
            paywallWindow = nil
            paywallUpgradeFlowEnabled = false
        }
    }
}

@available(macOS 13.0, *)
private final class MeetingSystemAudioRecorder: NSObject, SCStreamOutput, SCStreamDelegate {
    private let outputURL: URL
    private var stream: SCStream?
    private var writer: AVAssetWriter?
    private var writerInput: AVAssetWriterInput?
    private let outputQueue = DispatchQueue(label: "meeting.system.audio.capture")
    private var didStartSession = false

    init(outputURL: URL) {
        self.outputURL = outputURL
    }

    func start() async throws {
        try? FileManager.default.removeItem(at: outputURL)
        let content = try await SCShareableContent.excludingDesktopWindows(false, onScreenWindowsOnly: true)
        guard let display = content.displays.first else {
            throw NSError(domain: "MeetingSystemAudioRecorder", code: 1, userInfo: [NSLocalizedDescriptionKey: "No display available for system audio capture."])
        }

        let writer = try AVAssetWriter(outputURL: outputURL, fileType: .m4a)
        let inputSettings: [String: Any] = [
            AVFormatIDKey: kAudioFormatMPEG4AAC,
            AVSampleRateKey: 48_000,
            AVNumberOfChannelsKey: 2,
            AVEncoderBitRateKey: 128_000
        ]
        let input = AVAssetWriterInput(mediaType: .audio, outputSettings: inputSettings)
        input.expectsMediaDataInRealTime = true
        guard writer.canAdd(input) else {
            throw NSError(domain: "MeetingSystemAudioRecorder", code: 2, userInfo: [NSLocalizedDescriptionKey: "Cannot add audio writer input."])
        }
        writer.add(input)
        self.writer = writer
        self.writerInput = input
        didStartSession = false

        let filter = SCContentFilter(display: display, excludingApplications: [], exceptingWindows: [])
        let config = SCStreamConfiguration()
        config.width = 2
        config.height = 2
        config.minimumFrameInterval = CMTime(value: 1, timescale: 2)
        config.queueDepth = 1
        config.capturesAudio = true
        config.sampleRate = 48_000
        config.channelCount = 2
        if #available(macOS 13.0, *) {
            config.excludesCurrentProcessAudio = true
        }

        let stream = SCStream(filter: filter, configuration: config, delegate: self)
        self.stream = stream
        try stream.addStreamOutput(self, type: .audio, sampleHandlerQueue: outputQueue)
        try await stream.startCapture()
    }

    func stop() async throws {
        if let stream {
            try? await stream.stopCapture()
            self.stream = nil
        }
        writerInput?.markAsFinished()
        guard let writer else { return }
        await withCheckedContinuation { continuation in
            writer.finishWriting {
                continuation.resume()
            }
        }
        self.writer = nil
        self.writerInput = nil
    }

    func stream(_ stream: SCStream, didStopWithError error: Error) {
        // Capture may stop on permission changes or display changes; caller handles lifecycle.
    }

    func stream(_ stream: SCStream, didOutputSampleBuffer sampleBuffer: CMSampleBuffer, of outputType: SCStreamOutputType) {
        guard outputType == .audio else { return }
        guard CMSampleBufferDataIsReady(sampleBuffer) else { return }
        guard let writer = writer, let input = writerInput else { return }

        if writer.status == .unknown {
            writer.startWriting()
        }
        if writer.status == .writing {
            let pts = CMSampleBufferGetPresentationTimeStamp(sampleBuffer)
            if !didStartSession {
                writer.startSession(atSourceTime: pts)
                didStartSession = true
            }
            if input.isReadyForMoreMediaData {
                input.append(sampleBuffer)
            }
        }
    }
}

/// Default `NSClipView` uses a non-flipped coordinate system, so a document shorter than the visible area is anchored to the **bottom** of the clip, leaving a large gap above (e.g. Schedule empty state). Flipped coordinates match Auto Layout’s top-leading anchors and keep content top-aligned.
private final class TopAlignedClipView: NSClipView {
    override var isFlipped: Bool { true }
}

/// Wraps the Google auth control and draws a circular accent ring with a light pulse while the signed-in avatar is hovered.
private final class GoogleProfileAuthHostView: NSView {
    weak var authButton: NSButton? {
        didSet { needsLayout = true }
    }

    private let ringLayer = CAShapeLayer()
    private var avatarRingMode = false
    private static let ringLineWidth: CGFloat = 2.25

    override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
        wantsLayer = true
        layer?.masksToBounds = false
        ringLayer.fillColor = nil
        ringLayer.strokeColor = NSColor.clear.cgColor
        ringLayer.lineWidth = Self.ringLineWidth
        ringLayer.lineCap = .round
        ringLayer.opacity = 0
        ringLayer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
        layer?.insertSublayer(ringLayer, at: 0)
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) {
        nil
    }

    func setAvatarRingMode(_ enabled: Bool) {
        avatarRingMode = enabled
        if enabled == false {
            ringLayer.removeAllAnimations()
            ringLayer.opacity = 0
            ringLayer.lineWidth = Self.ringLineWidth
        }
        needsLayout = true
    }

    func updateRingAppearance(isDark: Bool, accent: NSColor) {
        let stroke = isDark
            ? accent.blended(withFraction: 0.22, of: NSColor.white) ?? accent
            : accent
        CATransaction.begin()
        CATransaction.setDisableActions(true)
        ringLayer.strokeColor = stroke.withAlphaComponent(0.95).cgColor
        CATransaction.commit()
    }

    func setProfileHoverActive(_ active: Bool) {
        guard avatarRingMode else { return }
        ringLayer.removeAnimation(forKey: "pulse")
        if active {
            layoutRingPathIfNeeded()
            CATransaction.begin()
            CATransaction.setAnimationDuration(0.22)
            ringLayer.opacity = 1
            CATransaction.commit()
            let pulse = CABasicAnimation(keyPath: "lineWidth")
            pulse.fromValue = Self.ringLineWidth * 0.88
            pulse.toValue = Self.ringLineWidth * 1.45
            pulse.duration = 0.72
            pulse.autoreverses = true
            pulse.repeatCount = .infinity
            pulse.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
            ringLayer.add(pulse, forKey: "pulse")
        } else {
            CATransaction.begin()
            CATransaction.setAnimationDuration(0.18)
            ringLayer.opacity = 0
            CATransaction.commit()
            ringLayer.lineWidth = Self.ringLineWidth
        }
    }

    private func layoutRingPathIfNeeded() {
        guard avatarRingMode, let btn = authButton else { return }
        let f = btn.frame
        guard f.width > 1, f.height > 1 else { return }
        let center = CGPoint(x: f.midX, y: f.midY)
        let avatarR = min(f.width, f.height) / 2
        let gap: CGFloat = 3.5
        let ringRadius = avatarR + gap
        let d = ringRadius * 2
        CATransaction.begin()
        CATransaction.setDisableActions(true)
        ringLayer.bounds = CGRect(x: 0, y: 0, width: d, height: d)
        ringLayer.position = center
        ringLayer.path = CGPath(ellipseIn: CGRect(origin: .zero, size: CGSize(width: d, height: d)), transform: nil)
        CATransaction.commit()
    }

    override func layout() {
        super.layout()
        layoutRingPathIfNeeded()
    }
}

/// Ensures `NSClickGestureRecognizer` on the row receives clicks instead of child label/image views swallowing them.
private class RowHitTestView: NSView {
    override func hitTest(_ point: NSPoint) -> NSView? {
        return bounds.contains(point) ? self : nil
    }

    override func acceptsFirstMouse(for event: NSEvent?) -> Bool {
        true
    }
}

private final class HoverTrackingView: RowHitTestView {
    var onHoverChanged: ((Bool) -> Void)?
    var onClick: (() -> Void)?
    var showsHandCursor = true

    private var trackingAreaRef: NSTrackingArea?
    private var isHovering = false {
        didSet {
            guard isHovering != oldValue else { return }
            onHoverChanged?(isHovering)
        }
    }

    override func updateTrackingAreas() {
        super.updateTrackingAreas()
        if let trackingAreaRef {
            removeTrackingArea(trackingAreaRef)
        }
        let options: NSTrackingArea.Options = [
            .activeInKeyWindow,
            .inVisibleRect,
            .mouseEnteredAndExited
        ]
        let area = NSTrackingArea(rect: bounds, options: options, owner: self, userInfo: nil)
        addTrackingArea(area)
        trackingAreaRef = area
    }

    override func mouseEntered(with event: NSEvent) {
        super.mouseEntered(with: event)
        isHovering = true
    }

    override func mouseExited(with event: NSEvent) {
        super.mouseExited(with: event)
        isHovering = false
    }

    override func resetCursorRects() {
        super.resetCursorRects()
        guard showsHandCursor else { return }
        addCursorRect(bounds, cursor: .pointingHand)
    }

    override func mouseUp(with event: NSEvent) {
        super.mouseUp(with: event)
        guard event.type == .leftMouseUp else { return }
        onClick?()
    }
}

/// Hover tracking without overriding hit-testing; keeps controls like text fields interactive.
private final class HoverSurfaceView: NSView {
    var onHoverChanged: ((Bool) -> Void)?

    private var trackingAreaRef: NSTrackingArea?
    private var isHovering = false {
        didSet {
            guard isHovering != oldValue else { return }
            onHoverChanged?(isHovering)
        }
    }

    override func updateTrackingAreas() {
        super.updateTrackingAreas()
        if let trackingAreaRef {
            removeTrackingArea(trackingAreaRef)
        }
        let options: NSTrackingArea.Options = [
            .activeInKeyWindow,
            .inVisibleRect,
            .mouseEnteredAndExited
        ]
        let area = NSTrackingArea(rect: bounds, options: options, owner: self, userInfo: nil)
        addTrackingArea(area)
        trackingAreaRef = area
    }

    override func mouseEntered(with event: NSEvent) {
        super.mouseEntered(with: event)
        isHovering = true
    }

    override func mouseExited(with event: NSEvent) {
        super.mouseExited(with: event)
        isHovering = false
    }
}

private final class HoverButton: NSButton {
    var onHoverChanged: ((Bool) -> Void)?
    var showsHandCursor = true

    private var trackingAreaRef: NSTrackingArea?
    private var isHovering = false {
        didSet {
            guard isHovering != oldValue else { return }
            onHoverChanged?(isHovering)
        }
    }

    override func updateTrackingAreas() {
        super.updateTrackingAreas()
        if let trackingAreaRef {
            removeTrackingArea(trackingAreaRef)
        }
        let options: NSTrackingArea.Options = [
            .activeInKeyWindow,
            .inVisibleRect,
            .mouseEnteredAndExited
        ]
        let tracking = NSTrackingArea(rect: bounds, options: options, owner: self, userInfo: nil)
        addTrackingArea(tracking)
        trackingAreaRef = tracking
    }

    override func mouseEntered(with event: NSEvent) {
        super.mouseEntered(with: event)
        if showsHandCursor {
            NSCursor.pointingHand.set()
        }
        isHovering = true
    }

    override func mouseExited(with event: NSEvent) {
        super.mouseExited(with: event)
        isHovering = false
    }
}

private final class HoverPopUpButton: NSPopUpButton {
    var onHoverChanged: ((Bool) -> Void)?

    private var trackingAreaRef: NSTrackingArea?
    private var isHovering = false {
        didSet {
            guard isHovering != oldValue else { return }
            onHoverChanged?(isHovering)
        }
    }

    override func updateTrackingAreas() {
        super.updateTrackingAreas()
        if let trackingAreaRef {
            removeTrackingArea(trackingAreaRef)
        }
        let options: NSTrackingArea.Options = [
            .activeInKeyWindow,
            .inVisibleRect,
            .mouseEnteredAndExited
        ]
        let tracking = NSTrackingArea(rect: bounds, options: options, owner: self, userInfo: nil)
        addTrackingArea(tracking)
        trackingAreaRef = tracking
    }

    override func mouseEntered(with event: NSEvent) {
        super.mouseEntered(with: event)
        isHovering = true
    }

    override func mouseExited(with event: NSEvent) {
        super.mouseExited(with: event)
        isHovering = false
    }
}

private func circularNSImage(_ image: NSImage, diameter: CGFloat) -> NSImage {
    let size = NSSize(width: diameter, height: diameter)
    let result = NSImage(size: size)
    result.lockFocus()
    if let ctx = NSGraphicsContext.current {
        ctx.imageInterpolation = .high
    }
    let rect = NSRect(origin: .zero, size: size)
    let path = NSBezierPath(ovalIn: rect)
    path.addClip()
    let src = image.size.width > 0 && image.size.height > 0
        ? NSRect(origin: .zero, size: image.size)
        : NSRect(origin: .zero, size: size)
    image.draw(in: rect, from: src, operation: .copy, fraction: 1.0)
    result.unlockFocus()
    result.isTemplate = false
    return result
}

private final class GoogleAccountMenuViewController: NSViewController {
    private let palette: Palette
    private let darkModeEnabled: Bool
    private let displayName: String
    private let email: String
    private let avatar: NSImage?
    private let onSignOut: () -> Void

    init(
        palette: Palette,
        darkModeEnabled: Bool,
        displayName: String,
        email: String,
        avatar: NSImage?,
        onSignOut: @escaping () -> Void
    ) {
        self.palette = palette
        self.darkModeEnabled = darkModeEnabled
        self.displayName = displayName
        self.email = email
        self.avatar = avatar
        self.onSignOut = onSignOut
        super.init(nibName: nil, bundle: nil)
        view = makeContentView()
        view.appearance = NSAppearance(named: darkModeEnabled ? .darkAqua : .aqua)
        preferredContentSize = NSSize(width: 300, height: 158)
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) {
        nil
    }

    private func makeContentView() -> NSView {
        let root = NSView()
        root.translatesAutoresizingMaskIntoConstraints = false

        let card = NSView()
        card.translatesAutoresizingMaskIntoConstraints = false
        card.wantsLayer = true
        card.layer?.cornerRadius = 14
        card.layer?.backgroundColor = palette.sectionCard.cgColor
        card.layer?.borderColor = palette.inputBorder.cgColor
        card.layer?.borderWidth = 1
        card.layer?.shadowColor = NSColor.black.cgColor
        card.layer?.shadowOpacity = darkModeEnabled ? 0.5 : 0.2
        card.layer?.shadowOffset = CGSize(width: 0, height: 6)
        card.layer?.shadowRadius = 18
        card.layer?.masksToBounds = false

        root.addSubview(card)
        NSLayoutConstraint.activate([
            card.leadingAnchor.constraint(equalTo: root.leadingAnchor, constant: 8),
            card.trailingAnchor.constraint(equalTo: root.trailingAnchor, constant: -8),
            card.topAnchor.constraint(equalTo: root.topAnchor, constant: 8),
            card.bottomAnchor.constraint(equalTo: root.bottomAnchor, constant: -8),
            root.widthAnchor.constraint(equalToConstant: 300)
        ])

        let inner = NSStackView()
        inner.translatesAutoresizingMaskIntoConstraints = false
        inner.orientation = .vertical
        inner.spacing = 0
        inner.alignment = .leading
        card.addSubview(inner)

        NSLayoutConstraint.activate([
            inner.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 18),
            inner.trailingAnchor.constraint(equalTo: card.trailingAnchor, constant: -18),
            inner.topAnchor.constraint(equalTo: card.topAnchor, constant: 18),
            inner.bottomAnchor.constraint(equalTo: card.bottomAnchor, constant: -10)
        ])

        let headerRow = NSView()
        headerRow.translatesAutoresizingMaskIntoConstraints = false

        let avatarBox = NSView()
        avatarBox.translatesAutoresizingMaskIntoConstraints = false
        avatarBox.wantsLayer = true
        avatarBox.layer?.cornerRadius = 24
        avatarBox.layer?.masksToBounds = true
        avatarBox.layer?.borderColor = palette.inputBorder.cgColor
        avatarBox.layer?.borderWidth = 1

        let avatarView = NSImageView()
        avatarView.translatesAutoresizingMaskIntoConstraints = false
        avatarView.imageScaling = .scaleAxesIndependently
        avatarView.image = resolvedAvatarImage()

        avatarBox.addSubview(avatarView)
        NSLayoutConstraint.activate([
            avatarBox.widthAnchor.constraint(equalToConstant: 48),
            avatarBox.heightAnchor.constraint(equalToConstant: 48),
            avatarView.leadingAnchor.constraint(equalTo: avatarBox.leadingAnchor),
            avatarView.trailingAnchor.constraint(equalTo: avatarBox.trailingAnchor),
            avatarView.topAnchor.constraint(equalTo: avatarBox.topAnchor),
            avatarView.bottomAnchor.constraint(equalTo: avatarBox.bottomAnchor)
        ])

        let textColumn = NSStackView()
        textColumn.translatesAutoresizingMaskIntoConstraints = false
        textColumn.orientation = .vertical
        textColumn.spacing = 3
        textColumn.alignment = .leading

        let nameField = NSTextField(labelWithString: displayName)
        nameField.translatesAutoresizingMaskIntoConstraints = false
        nameField.font = NSFont.systemFont(ofSize: 15, weight: .semibold)
        nameField.textColor = palette.textPrimary
        nameField.lineBreakMode = .byTruncatingTail
        nameField.maximumNumberOfLines = 1
        nameField.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)

        let emailField = NSTextField(labelWithString: email)
        emailField.translatesAutoresizingMaskIntoConstraints = false
        emailField.font = NSFont.systemFont(ofSize: 12, weight: .regular)
        emailField.textColor = palette.textTertiary
        emailField.lineBreakMode = .byTruncatingTail
        emailField.maximumNumberOfLines = 1
        emailField.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)

        textColumn.addArrangedSubview(nameField)
        textColumn.addArrangedSubview(emailField)

        headerRow.addSubview(avatarBox)
        headerRow.addSubview(textColumn)

        NSLayoutConstraint.activate([
            avatarBox.leadingAnchor.constraint(equalTo: headerRow.leadingAnchor),
            avatarBox.topAnchor.constraint(equalTo: headerRow.topAnchor),
            avatarBox.bottomAnchor.constraint(lessThanOrEqualTo: headerRow.bottomAnchor),

            textColumn.leadingAnchor.constraint(equalTo: avatarBox.trailingAnchor, constant: 14),
            textColumn.trailingAnchor.constraint(equalTo: headerRow.trailingAnchor),
            textColumn.centerYAnchor.constraint(equalTo: avatarBox.centerYAnchor),
            textColumn.topAnchor.constraint(greaterThanOrEqualTo: headerRow.topAnchor),
            textColumn.bottomAnchor.constraint(lessThanOrEqualTo: headerRow.bottomAnchor)
        ])

        inner.addArrangedSubview(headerRow)
        headerRow.widthAnchor.constraint(equalTo: inner.widthAnchor).isActive = true

        inner.setCustomSpacing(14, after: headerRow)

        let separator = NSView()
        separator.translatesAutoresizingMaskIntoConstraints = false
        separator.wantsLayer = true
        separator.layer?.backgroundColor = palette.separator.cgColor
        separator.heightAnchor.constraint(equalToConstant: 1).isActive = true
        inner.addArrangedSubview(separator)
        separator.widthAnchor.constraint(equalTo: inner.widthAnchor).isActive = true

        inner.setCustomSpacing(6, after: separator)

        let signOutRow = HoverTrackingView()
        signOutRow.translatesAutoresizingMaskIntoConstraints = false
        signOutRow.heightAnchor.constraint(equalToConstant: 44).isActive = true
        signOutRow.wantsLayer = true
        signOutRow.layer?.cornerRadius = 10

        let signOutIcon = NSImageView()
        signOutIcon.translatesAutoresizingMaskIntoConstraints = false
        signOutIcon.imageScaling = .scaleProportionallyDown
        if let sym = NSImage(systemSymbolName: "rectangle.portrait.and.arrow.right", accessibilityDescription: nil) {
            signOutIcon.image = sym
            signOutIcon.contentTintColor = palette.textSecondary
            signOutIcon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 14, weight: .medium)
        }

        let signOutLabel = NSTextField(labelWithString: "Log out")
        signOutLabel.translatesAutoresizingMaskIntoConstraints = false
        signOutLabel.font = NSFont.systemFont(ofSize: 14, weight: .medium)
        signOutLabel.textColor = palette.textPrimary

        signOutRow.addSubview(signOutIcon)
        signOutRow.addSubview(signOutLabel)

        NSLayoutConstraint.activate([
            signOutIcon.leadingAnchor.constraint(equalTo: signOutRow.leadingAnchor, constant: 10),
            signOutIcon.centerYAnchor.constraint(equalTo: signOutRow.centerYAnchor),
            signOutIcon.widthAnchor.constraint(equalToConstant: 20),
            signOutIcon.heightAnchor.constraint(equalToConstant: 20),

            signOutLabel.leadingAnchor.constraint(equalTo: signOutIcon.trailingAnchor, constant: 10),
            signOutLabel.centerYAnchor.constraint(equalTo: signOutRow.centerYAnchor),
            signOutLabel.trailingAnchor.constraint(lessThanOrEqualTo: signOutRow.trailingAnchor, constant: -10)
        ])

        let signOutClick = NSClickGestureRecognizer(target: self, action: #selector(signOutClicked))
        signOutRow.addGestureRecognizer(signOutClick)

        signOutRow.onHoverChanged = { [weak self] hovering in
            guard let self else { return }
            signOutRow.layer?.backgroundColor = (hovering ? self.palette.inputBackground : NSColor.clear).cgColor
        }
        signOutRow.onHoverChanged?(false)

        inner.addArrangedSubview(signOutRow)
        signOutRow.widthAnchor.constraint(equalTo: inner.widthAnchor).isActive = true

        return root
    }

    private func resolvedAvatarImage() -> NSImage {
        if let a = avatar {
            return circularNSImage(a, diameter: 48)
        }
        return initialLetterAvatar()
    }

    private func initialLetterAvatar() -> NSImage {
        let d: CGFloat = 48
        let letter = displayName.trimmingCharacters(in: .whitespacesAndNewlines).first.map { String($0).uppercased() } ?? "?"
        let img = NSImage(size: NSSize(width: d, height: d))
        img.lockFocus()
        palette.primaryBlue.setFill()
        NSBezierPath(ovalIn: NSRect(x: 0, y: 0, width: d, height: d)).fill()
        let attrs: [NSAttributedString.Key: Any] = [
            .font: NSFont.systemFont(ofSize: 20, weight: .semibold),
            .foregroundColor: NSColor.white
        ]
        let sz = (letter as NSString).size(withAttributes: attrs)
        let origin = NSPoint(x: (d - sz.width) / 2, y: (d - sz.height) / 2)
        (letter as NSString).draw(at: origin, withAttributes: attrs)
        img.unlockFocus()
        img.isTemplate = false
        return img
    }

    @objc private func signOutClicked() {
        onSignOut()
    }
}

private final class SettingsMenuViewController: NSViewController {
    private let palette: Palette
    private let typography: Typography
    private let speechLocaleOptions: [SpeechLocaleOption]
    private let selectedPrimaryLanguageIdentifier: String?
    private let selectedSecondaryLanguageIdentifier: String?
    private let onToggleDarkMode: (Bool) -> Void
    private let onUpdatePreferredSpeechLanguages: (String, String?) -> Void
    private let onAction: (SettingsAction, NSView?, NSPoint?) -> Void

    private var darkToggle: NSSwitch?
    private var primaryLanguagePopup: NSPopUpButton?
    private var secondaryLanguagePopup: NSPopUpButton?

    init(
        palette: Palette,
        typography: Typography,
        darkModeEnabled: Bool,
        showRateUsInSettings: Bool,
        showUpgradeInSettings: Bool,
        speechLocaleOptions: [SpeechLocaleOption],
        selectedPrimaryLanguageIdentifier: String?,
        selectedSecondaryLanguageIdentifier: String?,
        onToggleDarkMode: @escaping (Bool) -> Void,
        onUpdatePreferredSpeechLanguages: @escaping (String, String?) -> Void,
        onAction: @escaping (SettingsAction, NSView?, NSPoint?) -> Void
    ) {
        self.palette = palette
        self.typography = typography
        self.speechLocaleOptions = speechLocaleOptions
        self.selectedPrimaryLanguageIdentifier = selectedPrimaryLanguageIdentifier
        self.selectedSecondaryLanguageIdentifier = selectedSecondaryLanguageIdentifier
        self.onToggleDarkMode = onToggleDarkMode
        self.onUpdatePreferredSpeechLanguages = onUpdatePreferredSpeechLanguages
        self.onAction = onAction
        super.init(nibName: nil, bundle: nil)
        self.view = makeView(
            darkModeEnabled: darkModeEnabled,
            showRateUsInSettings: showRateUsInSettings,
            showUpgradeInSettings: showUpgradeInSettings
        )
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) {
        nil
    }

    func setDarkModeEnabled(_ enabled: Bool) {
        darkToggle?.state = enabled ? .on : .off
    }

    private func makeView(
        darkModeEnabled: Bool,
        showRateUsInSettings: Bool,
        showUpgradeInSettings: Bool
    ) -> NSView {
        let root = NSView()
        root.translatesAutoresizingMaskIntoConstraints = false

        let card = roundedCard()
        root.addSubview(card)
        NSLayoutConstraint.activate([
            card.leadingAnchor.constraint(equalTo: root.leadingAnchor),
            card.trailingAnchor.constraint(equalTo: root.trailingAnchor),
            card.topAnchor.constraint(equalTo: root.topAnchor),
            card.bottomAnchor.constraint(equalTo: root.bottomAnchor),
            root.widthAnchor.constraint(equalToConstant: 320)
        ])

        let stack = NSStackView()
        stack.translatesAutoresizingMaskIntoConstraints = false
        stack.orientation = .vertical
        stack.spacing = 6
        stack.alignment = .leading
        card.addSubview(stack)

        NSLayoutConstraint.activate([
            stack.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 14),
            stack.trailingAnchor.constraint(equalTo: card.trailingAnchor, constant: -14),
            stack.topAnchor.constraint(equalTo: card.topAnchor, constant: 14),
            stack.bottomAnchor.constraint(lessThanOrEqualTo: card.bottomAnchor, constant: -14)
        ])

        stack.addArrangedSubview(settingsDarkModeRow(enabled: darkModeEnabled))
        stack.addArrangedSubview(settingsSpeechLanguageRow(
            title: "AI Language 1",
            isPrimary: true
        ))
        stack.addArrangedSubview(settingsSpeechLanguageRow(
            title: "AI Language 2",
            isPrimary: false
        ))
        if showRateUsInSettings {
            stack.addArrangedSubview(settingsActionRow(icon: "★", title: "Rate Us", action: .rateUs))
        }
        stack.addArrangedSubview(settingsActionRow(icon: "🔒", title: "Privacy Policy", action: .privacyPolicy))
        stack.addArrangedSubview(settingsActionRow(icon: "💬", title: "Support", action: .support))
        stack.addArrangedSubview(settingsActionRow(icon: "📄", title: "Terms of Services", action: .termsOfServices))
        stack.addArrangedSubview(settingsActionRow(icon: "⤴︎", title: "Share App", action: .shareApp))
        if showUpgradeInSettings {
            stack.addArrangedSubview(settingsActionRow(icon: "⬆︎", title: "Upgrade", action: .upgrade))
        }

        for v in stack.arrangedSubviews {
            v.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
        }

        return root
    }

    private func roundedCard() -> NSView {
        let view = NSView()
        view.translatesAutoresizingMaskIntoConstraints = false
        view.wantsLayer = true
        view.layer?.cornerRadius = 12
        view.layer?.backgroundColor = palette.sectionCard.cgColor
        view.layer?.borderColor = palette.inputBorder.cgColor
        view.layer?.borderWidth = 1
        view.layer?.shadowColor = NSColor.black.cgColor
        view.layer?.shadowOpacity = 0.28
        view.layer?.shadowOffset = CGSize(width: 0, height: -1)
        view.layer?.shadowRadius = 10
        return view
    }

    private func settingsDarkModeRow(enabled: Bool) -> NSView {
        let row = NSView()
        row.translatesAutoresizingMaskIntoConstraints = false
        row.heightAnchor.constraint(equalToConstant: 44).isActive = true
        row.wantsLayer = true
        row.layer?.cornerRadius = 10

        let icon = NSTextField(labelWithString: "◐")
        icon.translatesAutoresizingMaskIntoConstraints = false
        icon.font = NSFont.systemFont(ofSize: 18, weight: .medium)
        icon.textColor = palette.textPrimary

        let title = NSTextField(labelWithString: "Dark Mode")
        title.translatesAutoresizingMaskIntoConstraints = false
        title.font = NSFont.systemFont(ofSize: 16, weight: .semibold)
        title.textColor = palette.textPrimary

        let toggle = NSSwitch()
        toggle.translatesAutoresizingMaskIntoConstraints = false
        toggle.state = enabled ? .on : .off
        toggle.target = self
        toggle.action = #selector(darkModeToggled(_:))
        darkToggle = toggle

        row.addSubview(icon)
        row.addSubview(title)
        row.addSubview(toggle)
        row.layer?.backgroundColor = NSColor.clear.cgColor

        NSLayoutConstraint.activate([
            icon.leadingAnchor.constraint(equalTo: row.leadingAnchor, constant: 4),
            icon.centerYAnchor.constraint(equalTo: row.centerYAnchor),

            title.leadingAnchor.constraint(equalTo: icon.trailingAnchor, constant: 10),
            title.centerYAnchor.constraint(equalTo: row.centerYAnchor),

            toggle.trailingAnchor.constraint(equalTo: row.trailingAnchor, constant: -2),
            toggle.centerYAnchor.constraint(equalTo: row.centerYAnchor)
        ])

        return row
    }

    private func settingsActionRow(icon: String, title: String, action: SettingsAction) -> NSView {
        let row = HoverButton(title: "", target: self, action: #selector(settingsActionButtonPressed(_:)))
        row.tag = action.rawValue
        row.isBordered = false
        row.translatesAutoresizingMaskIntoConstraints = false
        row.heightAnchor.constraint(equalToConstant: 42).isActive = true
        row.wantsLayer = true
        row.layer?.cornerRadius = 10
        row.layer?.backgroundColor = NSColor.clear.cgColor

        let iconLabel = NSTextField(labelWithString: icon)
        iconLabel.translatesAutoresizingMaskIntoConstraints = false
        iconLabel.font = NSFont.systemFont(ofSize: 18, weight: .medium)
        iconLabel.textColor = palette.textPrimary

        let titleLabel = NSTextField(labelWithString: title)
        titleLabel.translatesAutoresizingMaskIntoConstraints = false
        titleLabel.font = NSFont.systemFont(ofSize: 16, weight: .semibold)
        titleLabel.textColor = palette.textPrimary

        row.addSubview(iconLabel)
        row.addSubview(titleLabel)

        NSLayoutConstraint.activate([
            iconLabel.leadingAnchor.constraint(equalTo: row.leadingAnchor, constant: 4),
            iconLabel.centerYAnchor.constraint(equalTo: row.centerYAnchor),
            titleLabel.leadingAnchor.constraint(equalTo: iconLabel.trailingAnchor, constant: 10),
            titleLabel.centerYAnchor.constraint(equalTo: row.centerYAnchor)
        ])

        row.onHoverChanged = { hovering in
            row.layer?.backgroundColor = (hovering ? self.palette.inputBackground : NSColor.clear).cgColor
        }
        row.onHoverChanged?(false)

        return row
    }

    private func settingsSpeechLanguageRow(title: String, isPrimary: Bool) -> NSView {
        let row = NSView()
        row.translatesAutoresizingMaskIntoConstraints = false
        row.heightAnchor.constraint(equalToConstant: 62).isActive = true
        row.wantsLayer = true
        row.layer?.cornerRadius = 10
        row.layer?.backgroundColor = NSColor.clear.cgColor

        let titleLabel = NSTextField(labelWithString: title)
        titleLabel.translatesAutoresizingMaskIntoConstraints = false
        titleLabel.font = NSFont.systemFont(ofSize: 13, weight: .semibold)
        titleLabel.textColor = palette.textPrimary

        let popup = NSPopUpButton(frame: .zero, pullsDown: false)
        popup.translatesAutoresizingMaskIntoConstraints = false
        popup.target = self
        popup.action = #selector(speechLanguageChanged(_:))

        if isPrimary {
            for option in speechLocaleOptions {
                popup.addItem(withTitle: option.displayName)
                popup.lastItem?.representedObject = option.identifier
            }
            let preferred = selectedPrimaryLanguageIdentifier ?? speechLocaleOptions.first?.identifier
            if let preferred {
                selectLocale(identifier: preferred, in: popup)
            }
            primaryLanguagePopup = popup
        } else {
            popup.addItem(withTitle: "None")
            popup.lastItem?.representedObject = ""
            for option in speechLocaleOptions {
                popup.addItem(withTitle: option.displayName)
                popup.lastItem?.representedObject = option.identifier
            }
            if let secondary = selectedSecondaryLanguageIdentifier,
               secondary.isEmpty == false {
                selectLocale(identifier: secondary, in: popup)
            } else {
                popup.selectItem(at: 0)
            }
            secondaryLanguagePopup = popup
        }

        row.addSubview(titleLabel)
        row.addSubview(popup)
        NSLayoutConstraint.activate([
            titleLabel.leadingAnchor.constraint(equalTo: row.leadingAnchor, constant: 4),
            titleLabel.topAnchor.constraint(equalTo: row.topAnchor, constant: 6),
            titleLabel.trailingAnchor.constraint(equalTo: row.trailingAnchor, constant: -4),

            popup.leadingAnchor.constraint(equalTo: row.leadingAnchor, constant: 4),
            popup.trailingAnchor.constraint(equalTo: row.trailingAnchor, constant: -2),
            popup.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 6),
            popup.heightAnchor.constraint(equalToConstant: 28)
        ])
        return row
    }

    private func selectLocale(identifier: String, in popup: NSPopUpButton) {
        for item in popup.itemArray {
            if let represented = item.representedObject as? String, represented == identifier {
                popup.select(item)
                return
            }
        }
    }

    @objc private func speechLanguageChanged(_ sender: NSPopUpButton) {
        guard let primary = primaryLanguagePopup?.selectedItem?.representedObject as? String,
              primary.isEmpty == false else { return }

        var normalizedSecondary: String? = secondaryLanguagePopup?.selectedItem?.representedObject as? String
        if normalizedSecondary?.isEmpty == true {
            normalizedSecondary = nil
        }
        if let secondaryValue = normalizedSecondary,
           secondaryValue.replacingOccurrences(of: "_", with: "-").lowercased() == primary.replacingOccurrences(of: "_", with: "-").lowercased() {
            normalizedSecondary = nil
            secondaryLanguagePopup?.selectItem(at: 0)
        }
        onUpdatePreferredSpeechLanguages(primary, normalizedSecondary)
    }

    @objc private func darkModeToggled(_ sender: NSSwitch) {
        onToggleDarkMode(sender.state == .on)
    }

    @objc private func settingsActionButtonPressed(_ sender: NSButton) {
        guard let action = SettingsAction(rawValue: sender.tag) else { return }
        let clickPoint: NSPoint?
        if let event = NSApp.currentEvent {
            let pointInWindow = event.locationInWindow
            clickPoint = sender.convert(pointInWindow, from: nil)
        } else {
            clickPoint = nil
        }
        onAction(action, sender, clickPoint)
    }

}

private extension ViewController {
    private func hasGoogleSessionAvailable() -> Bool {
        guard let tokens = googleOAuth.loadTokens() else { return false }
        if tokens.expiresAt.timeIntervalSinceNow > 60 {
            return true
        }
        return (tokens.refreshToken?.isEmpty == false)
    }

    private func requireGoogleLoginForCalendarScheduling() -> Bool {
        guard hasGoogleSessionAvailable() else {
            showSimpleAlert(
                title: "Connect Google",
                message: "Sign in with Google first to schedule a meeting from Calendar."
            )
            return false
        }
        return true
    }

    func roundedContainer(cornerRadius: CGFloat, color: NSColor) -> NSView {
        let view = NSView()
        view.wantsLayer = true
        view.layer?.backgroundColor = color.cgColor
        view.layer?.cornerRadius = cornerRadius
        return view
    }

    func styleSurface(_ view: NSView, borderColor: NSColor, borderWidth: CGFloat, shadow: Bool) {
        view.layer?.borderColor = borderColor.cgColor
        view.layer?.borderWidth = borderWidth
        if shadow {
            view.layer?.shadowColor = NSColor.black.cgColor
            view.layer?.shadowOpacity = 0.18
            view.layer?.shadowOffset = CGSize(width: 0, height: -1)
            view.layer?.shadowRadius = 5
        }
    }

    func textLabel(_ text: String, font: NSFont, color: NSColor) -> NSTextField {
        let label = NSTextField(labelWithString: text)
        label.translatesAutoresizingMaskIntoConstraints = false
        label.textColor = color
        label.font = font
        return label
    }

    func iconLabel(_ text: String, size: CGFloat) -> NSTextField {
        let label = NSTextField(labelWithString: text)
        label.translatesAutoresizingMaskIntoConstraints = false
        label.font = NSFont.systemFont(ofSize: size)
        return label
    }

    func sidebarSectionTitle(_ text: String) -> NSTextField {
        let sectionColor = darkModeEnabled ? palette.textMuted : NSColor(calibratedWhite: 0.14, alpha: 1.0)
        let field = textLabel(text, font: typography.sidebarSection, color: sectionColor)
        field.alignment = .left
        return field
    }

    func sidebarItem(_ text: String, icon: String, page: SidebarPage, logoImageName: String? = nil, systemSymbolName: String? = nil, logoIconWidth: CGFloat = 18, logoHeightMultiplier: CGFloat = 1, logoTemplate: Bool = true, showsDisclosure: Bool = false) -> NSView {
        let item = HoverButton(title: "", target: self, action: #selector(sidebarButtonClicked(_:)))
        item.tag = page.rawValue
        item.isBordered = false
        item.wantsLayer = true
        item.layer?.cornerRadius = 10
        item.layer?.backgroundColor = NSColor.clear.cgColor
        item.translatesAutoresizingMaskIntoConstraints = false
        item.heightAnchor.constraint(equalToConstant: 36).isActive = true
        item.layer?.borderWidth = 0
        sidebarPageByView[ObjectIdentifier(item)] = page

        let leadingView: NSView
        if let name = logoImageName, let logo = NSImage(named: name) {
            logo.isTemplate = true
            let imageView = NSImageView(image: logo)
            imageView.translatesAutoresizingMaskIntoConstraints = false
            imageView.imageScaling = .scaleProportionallyDown
            imageView.imageAlignment = .alignCenter
            imageView.isEditable = false
            leadingView = imageView
        } else if let symbolName = systemSymbolName, let symbol = NSImage(systemSymbolName: symbolName, accessibilityDescription: text) {
            symbol.isTemplate = true
            let imageView = NSImageView(image: symbol)
            imageView.translatesAutoresizingMaskIntoConstraints = false
            imageView.imageScaling = .scaleProportionallyDown
            imageView.imageAlignment = .alignCenter
            imageView.isEditable = false
            leadingView = imageView
        } else {
            leadingView = textLabel(icon, font: typography.sidebarIcon, color: palette.textSecondary)
        }

        let baseSidebarTextColor = darkModeEnabled ? palette.textSecondary : NSColor(calibratedWhite: 0.08, alpha: 1.0)
        let titleLabel = textLabel(text, font: typography.sidebarItem, color: baseSidebarTextColor)
        titleLabel.alignment = .left

        item.addSubview(leadingView)
        item.addSubview(titleLabel)

        var constraints: [NSLayoutConstraint] = [
            leadingView.leadingAnchor.constraint(equalTo: item.leadingAnchor, constant: 12),
            leadingView.centerYAnchor.constraint(equalTo: item.centerYAnchor),
            titleLabel.leadingAnchor.constraint(equalTo: leadingView.trailingAnchor, constant: 8),
            titleLabel.centerYAnchor.constraint(equalTo: item.centerYAnchor)
        ]

        if showsDisclosure {
            let chevron = textLabel("›", font: NSFont.systemFont(ofSize: 22, weight: .semibold), color: baseSidebarTextColor)
            chevron.translatesAutoresizingMaskIntoConstraints = false
            chevron.alignment = .right
            item.addSubview(chevron)
            constraints.append(contentsOf: [
                chevron.trailingAnchor.constraint(equalTo: item.trailingAnchor, constant: -10),
                chevron.centerYAnchor.constraint(equalTo: item.centerYAnchor),
                titleLabel.trailingAnchor.constraint(lessThanOrEqualTo: chevron.leadingAnchor, constant: -8)
            ])
        } else {
            constraints.append(titleLabel.trailingAnchor.constraint(lessThanOrEqualTo: item.trailingAnchor, constant: -10))
        }

        if logoImageName != nil || systemSymbolName != nil {
            let h = logoIconWidth * logoHeightMultiplier
            constraints.append(contentsOf: [
                leadingView.widthAnchor.constraint(equalToConstant: logoIconWidth),
                leadingView.heightAnchor.constraint(equalToConstant: h)
            ])
        }
        NSLayoutConstraint.activate(constraints)

        applySidebarRowStyle(item, page: page, logoTemplate: logoTemplate)
        item.onHoverChanged = { [weak self, weak item] hovering in
            guard let self, let item else { return }
            self.applySidebarRowStyle(item, page: page, logoTemplate: logoTemplate, hovering: hovering)
        }

        return item
    }

    func applySidebarRowStyle(_ item: NSView, page: SidebarPage, logoTemplate: Bool, hovering: Bool = false) {
        let selected = (page == selectedSidebarPage)
        let hoverColor = darkModeEnabled ? NSColor(calibratedWhite: 1, alpha: 0.07) : NSColor(calibratedWhite: 0, alpha: 0.08)
        item.layer?.backgroundColor = (selected ? palette.primaryBlue : (hovering ? hoverColor : NSColor.clear)).cgColor
        let baseSidebarTextColor = darkModeEnabled ? palette.textSecondary : NSColor(calibratedWhite: 0.08, alpha: 1.0)
        let tint = selected ? NSColor.white : baseSidebarTextColor
        let sidebarIconTint = darkModeEnabled ? tint : baseSidebarTextColor
        guard item.subviews.count >= 2 else { return }
        let leading = item.subviews[0]
        let title = item.subviews.first { $0 is NSTextField } as? NSTextField
        title?.textColor = tint
        // Optional disclosure chevron (if present) is the last text field.
        if let chevron = item.subviews.last as? NSTextField, chevron !== title {
            chevron.textColor = sidebarIconTint
        }
        if let imageView = leading as? NSImageView {
            if logoTemplate {
                imageView.contentTintColor = sidebarIconTint
            }
        } else if let iconField = leading as? NSTextField {
            iconField.textColor = sidebarIconTint
        }
    }

    func actionButton(title: String, color: NSColor, textColor: NSColor, width: CGFloat) -> NSView {
        let button = HoverTrackingView()
        button.wantsLayer = true
        button.layer?.cornerRadius = 9
        button.layer?.backgroundColor = color.cgColor
        button.translatesAutoresizingMaskIntoConstraints = false
        button.widthAnchor.constraint(equalToConstant: width).isActive = true
        button.heightAnchor.constraint(equalToConstant: 36).isActive = true
        styleSurface(button, borderColor: title == "Cancel" ? palette.inputBorder : palette.primaryBlueBorder, borderWidth: 1, shadow: false)
        if title == "Cancel" {
            button.layer?.backgroundColor = palette.cancelButton.cgColor
        }

        let label = textLabel(title, font: typography.buttonText, color: textColor)
        button.addSubview(label)
        NSLayoutConstraint.activate([
            label.centerXAnchor.constraint(equalTo: button.centerXAnchor),
            label.centerYAnchor.constraint(equalTo: button.centerYAnchor)
        ])

        let baseColor = (title == "Cancel") ? palette.cancelButton : color
        let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
        let hoverColor = baseColor.blended(withFraction: 0.12, of: hoverBlend) ?? baseColor
        button.onHoverChanged = { hovering in
            button.layer?.backgroundColor = (hovering ? hoverColor : baseColor).cgColor
        }
        button.onHoverChanged?(false)

        return button
    }

    func iconRoundButton(systemSymbol: String, size: CGFloat, iconPointSize: CGFloat = 16, onClick: (() -> Void)? = nil) -> NSView {
        let button = HoverTrackingView()
        button.wantsLayer = true
        button.layer?.cornerRadius = size / 2
        button.layer?.backgroundColor = palette.inputBackground.cgColor
        button.translatesAutoresizingMaskIntoConstraints = false
        button.widthAnchor.constraint(equalToConstant: size).isActive = true
        button.heightAnchor.constraint(equalToConstant: size).isActive = true
        styleSurface(button, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)

        let symbolConfig = NSImage.SymbolConfiguration(pointSize: iconPointSize, weight: .semibold)
        let iconView = NSImageView()
        iconView.translatesAutoresizingMaskIntoConstraints = false
        iconView.image = NSImage(systemSymbolName: systemSymbol, accessibilityDescription: "Refresh")
        iconView.symbolConfiguration = symbolConfig
        iconView.contentTintColor = palette.textSecondary
        button.addSubview(iconView)
        NSLayoutConstraint.activate([
            iconView.centerXAnchor.constraint(equalTo: button.centerXAnchor),
            iconView.centerYAnchor.constraint(equalTo: button.centerYAnchor)
        ])

        let baseColor = palette.inputBackground
        let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
        let hoverColor = baseColor.blended(withFraction: 0.10, of: hoverBlend) ?? baseColor
        button.onHoverChanged = { hovering in
            button.layer?.backgroundColor = (hovering ? hoverColor : baseColor).cgColor
        }
        button.onHoverChanged?(false)
        button.onClick = onClick

        return button
    }
}

private let calendarDayKeyFormatter: DateFormatter = {
    let f = DateFormatter()
    f.calendar = Calendar(identifier: .gregorian)
    f.locale = Locale(identifier: "en_US_POSIX")
    f.timeZone = TimeZone.current
    f.dateFormat = "yyyy-MM-dd"
    return f
}()

// MARK: - Calendar page actions + rendering

private extension ViewController {
    private func makeCalendarHeaderPillButton(title: String, action: Selector) -> NSButton {
        let button = makeSchedulePillButton(title: title)
        button.target = self
        button.action = action
        button.heightAnchor.constraint(equalToConstant: 30).isActive = true
        return button
    }

    private func calendarStartOfMonth(for date: Date) -> Date {
        let calendar = Calendar.current
        let comps = calendar.dateComponents([.year, .month], from: date)
        return calendar.date(from: comps) ?? calendar.startOfDay(for: date)
    }

    private func calendarMonthTitleText(for monthAnchor: Date) -> String {
        let f = DateFormatter()
        f.locale = Locale.current
        f.timeZone = TimeZone.current
        f.dateFormat = "MMMM yyyy"
        return f.string(from: monthAnchor)
    }

    private func calendarWeekdaySymbolsStartingAtFirstWeekday() -> [String] {
        // Align weekday header to Calendar.current.firstWeekday
        let calendar = Calendar.current
        var symbols = DateFormatter().veryShortWeekdaySymbols ?? ["S", "M", "T", "W", "T", "F", "S"]
        // veryShortWeekdaySymbols starts with Sunday in most locales; rotate to firstWeekday.
        let first = max(1, min(7, calendar.firstWeekday)) // 1..7
        let shift = (first - 1) % 7
        if shift == 0 { return symbols }
        let head = Array(symbols[shift...])
        let tail = Array(symbols[..<shift])
        symbols = head + tail
        return symbols
    }

    @objc func calendarPrevMonthPressed(_ sender: NSButton) {
        let calendar = Calendar.current
        calendarPageMonthAnchor = calendar.date(byAdding: .month, value: -1, to: calendarPageMonthAnchor).map(calendarStartOfMonth(for:)) ?? calendarPageMonthAnchor
        calendarPageMonthLabel?.stringValue = calendarMonthTitleText(for: calendarPageMonthAnchor)
        renderCalendarMonthGrid()
    }

    @objc func calendarNextMonthPressed(_ sender: NSButton) {
        let calendar = Calendar.current
        calendarPageMonthAnchor = calendar.date(byAdding: .month, value: 1, to: calendarPageMonthAnchor).map(calendarStartOfMonth(for:)) ?? calendarPageMonthAnchor
        calendarPageMonthLabel?.stringValue = calendarMonthTitleText(for: calendarPageMonthAnchor)
        renderCalendarMonthGrid()
    }

    @objc func calendarRefreshPressed(_ sender: NSButton) {
        Task { [weak self] in
            await self?.loadSchedule()
        }
    }

    @objc func calendarDayCellPressed(_ sender: NSButton) {
        guard requireGoogleLoginForCalendarScheduling() else { return }
        guard let raw = sender.identifier?.rawValue,
              let date = calendarDayKeyFormatter.date(from: raw) else { return }
        calendarPageSelectedDate = Calendar.current.startOfDay(for: date)
        renderCalendarMonthGrid()
        renderCalendarSelectedDay()
        if let refreshedButton = calendarButton(forDateKey: raw) {
            showCalendarDayActionPopover(relativeTo: refreshedButton)
        }
    }

    private func showCalendarDayActionPopover(relativeTo anchor: NSView) {
        guard anchor.window != nil else { return }
        calendarPageActionPopover?.performClose(nil)
        let popover = NSPopover()
        popover.behavior = .transient
        popover.animates = true
        popover.appearance = NSAppearance(named: darkModeEnabled ? .darkAqua : .aqua)
        popover.contentViewController = CalendarDayActionMenuViewController(
            palette: palette,
            onSchedule: { [weak self] in
                self?.calendarPageActionPopover?.performClose(nil)
                self?.calendarPageActionPopover = nil
                self?.presentCreateMeetingPopover(relativeTo: anchor)
            }
        )
        calendarPageActionPopover = popover
        popover.show(relativeTo: anchor.bounds, of: anchor, preferredEdge: .maxY)
    }

    private func presentCreateMeetingPopover(relativeTo anchor: NSView) {
        guard anchor.window != nil else { return }
        calendarPageCreatePopover?.performClose(nil)
        let popover = NSPopover()
        popover.behavior = .transient
        popover.animates = true
        popover.appearance = NSAppearance(named: darkModeEnabled ? .darkAqua : .aqua)
        let selectedDate = Calendar.current.startOfDay(for: calendarPageSelectedDate)
        let vc = CreateMeetingPopoverViewController(
            palette: palette,
            typography: typography,
            selectedDate: selectedDate,
            onCancel: { [weak self] in
                self?.calendarPageCreatePopover?.performClose(nil)
                self?.calendarPageCreatePopover = nil
            },
            onSave: { [weak self] draft in
                guard let self else { return }
                self.calendarPageCreatePopover?.performClose(nil)
                self.calendarPageCreatePopover = nil
                self.calendarCreateMeeting(title: draft.title, notes: draft.notes, start: draft.startDate, end: draft.endDate)
            }
        )
        popover.contentViewController = vc
        calendarPageCreatePopover = popover
        popover.show(relativeTo: anchor.bounds, of: anchor, preferredEdge: .maxY)
    }

    private func calendarCreateMeeting(title: String, notes: String?, start: Date, end: Date) {
        Task { [weak self] in
            guard let self else { return }
            do {
                try await self.ensureGoogleClientIdConfigured(presentingWindow: self.view.window)
                let token = try await self.googleOAuth.validAccessToken(presentingWindow: self.view.window)
                _ = try await self.calendarClient.createEvent(
                    accessToken: token,
                    title: title,
                    description: notes,
                    start: start,
                    end: end,
                    timeZone: .current
                )
                await self.loadSchedule()
                await MainActor.run {
                    let calendar = Calendar.current
                    self.calendarPageSelectedDate = calendar.startOfDay(for: start)
                    self.calendarPageMonthAnchor = self.calendarStartOfMonth(for: start)
                    self.calendarPageMonthLabel?.stringValue = self.calendarMonthTitleText(for: self.calendarPageMonthAnchor)
                    self.renderCalendarMonthGrid()
                    self.renderCalendarSelectedDay()
                    self.showTopToast(message: "Meeting added successfully.", isError: false)
                }
            } catch {
                await MainActor.run {
                    self.showTopToast(message: "An issue occurred. Please try again.", isError: true)
                }
            }
        }
    }

    private func renderCalendarMonthGrid() {
        guard let gridStack = calendarPageGridStack else { return }
        gridStack.arrangedSubviews.forEach { v in
            gridStack.removeArrangedSubview(v)
            v.removeFromSuperview()
        }

        let calendar = Calendar.current
        let monthStart = calendarStartOfMonth(for: calendarPageMonthAnchor)
        guard let dayRange = calendar.range(of: .day, in: .month, for: monthStart),
              let monthEnd = calendar.date(byAdding: DateComponents(month: 1, day: 0), to: monthStart) else { return }

        let firstWeekday = calendar.component(.weekday, from: monthStart) // 1..7
        let leadingEmpty = (firstWeekday - calendar.firstWeekday + 7) % 7
        let totalDays = dayRange.count
        let totalCells = leadingEmpty + totalDays
        let rowCount = Int(ceil(Double(totalCells) / 7.0))
        let rowHeight: CGFloat = 56
        let rowSpacing: CGFloat = 12
        let verticalPadding: CGFloat = 32
        calendarPageGridHeightConstraint?.constant = verticalPadding + (CGFloat(rowCount) * rowHeight) + (CGFloat(max(0, rowCount - 1)) * rowSpacing)

        let meetingCounts = calendarMeetingCountsByDay(from: scheduleCachedMeetings, monthStart: monthStart, monthEnd: monthEnd)

        var day = 1
        for _ in 0..<rowCount {
            let row = NSStackView()
            row.translatesAutoresizingMaskIntoConstraints = false
            row.userInterfaceLayoutDirection = .leftToRight
            row.orientation = .horizontal
            row.alignment = .top
            row.distribution = .fillEqually
            row.spacing = rowSpacing
            row.heightAnchor.constraint(equalToConstant: rowHeight).isActive = true

            for col in 0..<7 {
                let cellIndex = (gridStack.arrangedSubviews.count * 7) + col
                if cellIndex < leadingEmpty || day > totalDays {
                    row.addArrangedSubview(calendarEmptyDayCell())
                    continue
                }
                guard let date = calendar.date(byAdding: .day, value: day - 1, to: monthStart) else {
                    row.addArrangedSubview(calendarEmptyDayCell())
                    continue
                }
                let isSelected = calendar.isDate(date, inSameDayAs: calendarPageSelectedDate)
                let key = calendarDayKeyFormatter.string(from: calendar.startOfDay(for: date))
                let count = meetingCounts[key] ?? 0
                row.addArrangedSubview(calendarDayCell(dayNumber: day, dateKey: key, meetingCount: count, isSelected: isSelected))
                day += 1
            }
            gridStack.addArrangedSubview(row)
            row.widthAnchor.constraint(equalTo: gridStack.widthAnchor).isActive = true
        }
    }

    private func calendarButton(forDateKey key: String) -> NSButton? {
        guard let gridStack = calendarPageGridStack else { return nil }
        for rowView in gridStack.arrangedSubviews {
            guard let row = rowView as? NSStackView else { continue }
            for cell in row.arrangedSubviews {
                if let button = cell as? NSButton, button.identifier?.rawValue == key {
                    return button
                }
            }
        }
        return nil
    }

    private func renderCalendarSelectedDay() {
        let calendar = Calendar.current
        let selectedDay = calendar.startOfDay(for: calendarPageSelectedDate)
        let nextDay = calendar.date(byAdding: .day, value: 1, to: selectedDay) ?? selectedDay.addingTimeInterval(86400)

        let meetings = scheduleCachedMeetings
            .filter { $0.startDate >= selectedDay && $0.startDate < nextDay }
            .sorted(by: { $0.startDate < $1.startDate })

        let f = DateFormatter()
        f.locale = Locale.current
        f.timeZone = TimeZone.current
        f.dateFormat = "EEE, d MMM"

        if meetings.isEmpty {
            calendarPageDaySummaryLabel?.stringValue = hasGoogleSessionAvailable() == false
                ? "Connect Google to see meetings"
                : "No meetings on \(f.string(from: selectedDay))"
        } else if meetings.count == 1 {
            calendarPageDaySummaryLabel?.stringValue = "1 meeting on \(f.string(from: selectedDay))"
        } else {
            calendarPageDaySummaryLabel?.stringValue = "\(meetings.count) meetings on \(f.string(from: selectedDay))"
        }
    }

    private func calendarMeetingCountsByDay(from meetings: [ScheduledMeeting], monthStart: Date, monthEnd: Date) -> [String: Int] {
        let calendar = Calendar.current
        var counts: [String: Int] = [:]
        for meeting in meetings {
            guard meeting.startDate >= monthStart && meeting.startDate < monthEnd else { continue }
            let key = calendarDayKeyFormatter.string(from: calendar.startOfDay(for: meeting.startDate))
            counts[key, default: 0] += 1
        }
        return counts
    }

    private func calendarEmptyDayCell() -> NSView {
        let v = NSView()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.heightAnchor.constraint(equalToConstant: 56).isActive = true
        return v
    }

    private func calendarDayCell(dayNumber: Int, dateKey: String, meetingCount: Int, isSelected: Bool) -> NSButton {
        let button = HoverButton(title: "", target: self, action: #selector(calendarDayCellPressed(_:)))
        button.translatesAutoresizingMaskIntoConstraints = false
        button.isBordered = false
        button.bezelStyle = .regularSquare
        button.wantsLayer = true
        button.layer?.cornerRadius = 12
        button.layer?.masksToBounds = true
        button.identifier = NSUserInterfaceItemIdentifier(dateKey)
        button.heightAnchor.constraint(equalToConstant: 56).isActive = true
        button.setContentHuggingPriority(.required, for: .vertical)
        button.setContentCompressionResistancePriority(.required, for: .vertical)
        button.alignment = .left
        button.imagePosition = .noImage

        let base = palette.inputBackground
        let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
        let hover = base.blended(withFraction: 0.10, of: hoverBlend) ?? base
        let selectedBackground = darkModeEnabled
            ? NSColor(calibratedRed: 30.0 / 255.0, green: 34.0 / 255.0, blue: 42.0 / 255.0, alpha: 1)
            : NSColor(calibratedRed: 255.0 / 255.0, green: 246.0 / 255.0, blue: 236.0 / 255.0, alpha: 1)
        let borderIdle = palette.inputBorder
        let borderSelected = palette.primaryBlueBorder

        func applyAppearance(hovering: Bool) {
            button.layer?.backgroundColor = (isSelected ? selectedBackground : (hovering ? hover : base)).cgColor
            button.layer?.borderWidth = isSelected ? 1.5 : 1
            button.layer?.borderColor = (isSelected ? borderSelected : borderIdle).cgColor
        }
        applyAppearance(hovering: false)
        button.onHoverChanged = { hovering in
            applyAppearance(hovering: hovering)
        }

        button.attributedTitle = NSAttributedString(
            string: "   \(dayNumber)",
            attributes: [
                .font: NSFont.systemFont(ofSize: 14, weight: .bold),
                .foregroundColor: palette.textPrimary
            ]
        )

        if meetingCount > 0 {
            let dot = roundedContainer(cornerRadius: 4, color: palette.meetingBadge)
            dot.translatesAutoresizingMaskIntoConstraints = false
            dot.layer?.borderWidth = 0
            button.addSubview(dot)
            NSLayoutConstraint.activate([
                dot.trailingAnchor.constraint(equalTo: button.trailingAnchor, constant: -10),
                dot.centerYAnchor.constraint(equalTo: button.centerYAnchor),
                dot.widthAnchor.constraint(equalToConstant: 8),
                dot.heightAnchor.constraint(equalToConstant: 8)
            ])
        }

        return button
    }
}

private final class CalendarDayActionMenuViewController: NSViewController {
    private let palette: Palette
    private let onSchedule: () -> Void

    init(palette: Palette, onSchedule: @escaping () -> Void) {
        self.palette = palette
        self.onSchedule = onSchedule
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder: NSCoder) { nil }

    override func loadView() {
        let root = NSView()
        root.translatesAutoresizingMaskIntoConstraints = false

        let stack = NSStackView()
        stack.translatesAutoresizingMaskIntoConstraints = false
        stack.orientation = .vertical
        stack.alignment = .leading
        stack.spacing = 10

        let title = NSTextField(labelWithString: "Actions")
        title.font = NSFont.systemFont(ofSize: 12, weight: .semibold)
        title.textColor = palette.textMuted

        let schedule = NSButton(title: "Schedule meeting", target: self, action: #selector(schedulePressed(_:)))
        schedule.bezelStyle = .rounded
        schedule.font = NSFont.systemFont(ofSize: 13, weight: .medium)

        stack.addArrangedSubview(title)
        stack.addArrangedSubview(schedule)
        root.addSubview(stack)

        NSLayoutConstraint.activate([
            root.widthAnchor.constraint(equalToConstant: 220),
            root.heightAnchor.constraint(greaterThanOrEqualToConstant: 86),
            stack.leadingAnchor.constraint(equalTo: root.leadingAnchor, constant: 14),
            stack.trailingAnchor.constraint(equalTo: root.trailingAnchor, constant: -14),
            stack.topAnchor.constraint(equalTo: root.topAnchor, constant: 12),
            stack.bottomAnchor.constraint(equalTo: root.bottomAnchor, constant: -12)
        ])

        view = root
    }

    @objc private func schedulePressed(_ sender: NSButton) {
        onSchedule()
    }
}

private final class CreateMeetingPopoverViewController: NSViewController, NSTextViewDelegate {
    struct Draft {
        let title: String
        let notes: String?
        let startDate: Date
        let endDate: Date
    }

    private let palette: Palette
    private let typography: Typography
    private let selectedDate: Date
    private let onCancel: () -> Void
    private let onSave: (Draft) -> Void

    private var titleField: NSTextField?
    private var timePicker: NSDatePicker?
    private var durationField: NSTextField?
    private var notesView: NSTextView?
    private var notesScrollView: NSScrollView?
    private var errorLabel: NSTextField?
    private var notesBorderIdle = NSColor.clear
    private var notesBorderHover = NSColor.clear
    private var notesBorderFocused = NSColor.clear
    private var notesIsHovered = false
    private var notesIsFocused = false

    init(palette: Palette,
         typography: Typography,
         selectedDate: Date,
         onCancel: @escaping () -> Void,
         onSave: @escaping (Draft) -> Void) {
        self.palette = palette
        self.typography = typography
        self.selectedDate = selectedDate
        self.onCancel = onCancel
        self.onSave = onSave
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder: NSCoder) { nil }

    override func loadView() {
        let root = NSView()
        root.translatesAutoresizingMaskIntoConstraints = false
        root.userInterfaceLayoutDirection = .leftToRight
        root.wantsLayer = true
        root.layer?.cornerRadius = 14
        root.layer?.masksToBounds = true
        root.layer?.backgroundColor = palette.sectionCard.cgColor
        root.layer?.borderWidth = 1
        root.layer?.borderColor = palette.inputBorder.withAlphaComponent(0.9).cgColor

        let stack = NSStackView()
        stack.translatesAutoresizingMaskIntoConstraints = false
        stack.orientation = .vertical
        stack.alignment = .leading
        stack.spacing = 14
        stack.userInterfaceLayoutDirection = .leftToRight

        let inputSurface = palette.inputBackground.blended(withFraction: 0.18, of: palette.sectionCard) ?? palette.inputBackground
        let fieldBorder = palette.textSecondary.withAlphaComponent(0.4)
        notesBorderIdle = fieldBorder
        notesBorderHover = palette.textSecondary.withAlphaComponent(0.72)
        notesBorderFocused = palette.primaryBlueBorder

        let header = NSTextField(labelWithString: "Schedule meeting")
        header.font = NSFont.systemFont(ofSize: 16, weight: .semibold)
        header.textColor = palette.textPrimary
        header.alignment = .left
        header.userInterfaceLayoutDirection = .leftToRight
        header.baseWritingDirection = .leftToRight

        let titleLabel = NSTextField(labelWithString: "Title")
        titleLabel.font = typography.fieldLabel
        titleLabel.textColor = palette.textSecondary
        titleLabel.alignment = .left
        titleLabel.userInterfaceLayoutDirection = .leftToRight
        titleLabel.baseWritingDirection = .leftToRight

        let titleShell = NSView()
        titleShell.translatesAutoresizingMaskIntoConstraints = false
        titleShell.wantsLayer = true
        titleShell.layer?.cornerRadius = 8
        titleShell.layer?.backgroundColor = inputSurface.cgColor
        titleShell.layer?.borderColor = fieldBorder.cgColor
        titleShell.layer?.borderWidth = 1.2
        titleShell.heightAnchor.constraint(equalToConstant: 40).isActive = true

        let titleField = NSTextField(string: "")
        titleField.translatesAutoresizingMaskIntoConstraints = false
        titleField.isBordered = false
        titleField.drawsBackground = false
        titleField.focusRingType = .none
        titleField.font = NSFont.systemFont(ofSize: 14, weight: .regular)
        titleField.textColor = palette.textPrimary
        titleField.placeholderString = "Team sync"
        titleShell.addSubview(titleField)
        NSLayoutConstraint.activate([
            titleField.leadingAnchor.constraint(equalTo: titleShell.leadingAnchor, constant: 10),
            titleField.trailingAnchor.constraint(equalTo: titleShell.trailingAnchor, constant: -10),
            titleField.centerYAnchor.constraint(equalTo: titleShell.centerYAnchor)
        ])
        self.titleField = titleField

        let timeRow = NSStackView()
        timeRow.translatesAutoresizingMaskIntoConstraints = false
        timeRow.orientation = .horizontal
        timeRow.alignment = .centerY
        timeRow.spacing = 10
        timeRow.distribution = .fill

        let startLabel = NSTextField(labelWithString: "Start")
        startLabel.font = typography.fieldLabel
        startLabel.textColor = palette.textSecondary
        startLabel.alignment = .left
        startLabel.userInterfaceLayoutDirection = .leftToRight
        startLabel.baseWritingDirection = .leftToRight

        let pickerShell = NSView()
        pickerShell.translatesAutoresizingMaskIntoConstraints = false
        pickerShell.wantsLayer = true
        pickerShell.layer?.cornerRadius = 8
        pickerShell.layer?.backgroundColor = inputSurface.cgColor
        pickerShell.layer?.borderColor = fieldBorder.cgColor
        pickerShell.layer?.borderWidth = 1.2
        pickerShell.heightAnchor.constraint(equalToConstant: 34).isActive = true

        let timePicker = NSDatePicker()
        timePicker.translatesAutoresizingMaskIntoConstraints = false
        timePicker.isBordered = false
        timePicker.drawsBackground = false
        timePicker.focusRingType = .none
        timePicker.datePickerStyle = .textFieldAndStepper
        timePicker.datePickerElements = [.hourMinute]
        timePicker.font = typography.filterText
        timePicker.textColor = palette.textSecondary
        timePicker.dateValue = Date()
        pickerShell.addSubview(timePicker)
        NSLayoutConstraint.activate([
            timePicker.leadingAnchor.constraint(equalTo: pickerShell.leadingAnchor, constant: 8),
            timePicker.trailingAnchor.constraint(equalTo: pickerShell.trailingAnchor, constant: -8),
            timePicker.centerYAnchor.constraint(equalTo: pickerShell.centerYAnchor)
        ])
        self.timePicker = timePicker

        let durationLabel = NSTextField(labelWithString: "Duration (min)")
        durationLabel.font = typography.fieldLabel
        durationLabel.textColor = palette.textSecondary
        durationLabel.alignment = .left
        durationLabel.userInterfaceLayoutDirection = .leftToRight
        durationLabel.baseWritingDirection = .leftToRight

        let durationShell = NSView()
        durationShell.translatesAutoresizingMaskIntoConstraints = false
        durationShell.wantsLayer = true
        durationShell.layer?.cornerRadius = 8
        durationShell.layer?.backgroundColor = inputSurface.cgColor
        durationShell.layer?.borderColor = fieldBorder.cgColor
        durationShell.layer?.borderWidth = 1.2
        durationShell.heightAnchor.constraint(equalToConstant: 34).isActive = true

        let durationField = NSTextField(string: "30")
        durationField.translatesAutoresizingMaskIntoConstraints = false
        durationField.isBordered = false
        durationField.drawsBackground = false
        durationField.focusRingType = .none
        durationField.font = typography.filterText
        durationField.textColor = palette.textSecondary
        durationField.formatter = NumberFormatter()
        durationShell.addSubview(durationField)
        NSLayoutConstraint.activate([
            durationField.leadingAnchor.constraint(equalTo: durationShell.leadingAnchor, constant: 8),
            durationField.trailingAnchor.constraint(equalTo: durationShell.trailingAnchor, constant: -8),
            durationField.centerYAnchor.constraint(equalTo: durationShell.centerYAnchor)
        ])
        self.durationField = durationField

        let startGroup = NSStackView(views: [startLabel, pickerShell])
        startGroup.translatesAutoresizingMaskIntoConstraints = false
        startGroup.orientation = .vertical
        startGroup.alignment = .leading
        startGroup.spacing = 6

        let durationGroup = NSStackView(views: [durationLabel, durationShell])
        durationGroup.translatesAutoresizingMaskIntoConstraints = false
        durationGroup.orientation = .vertical
        durationGroup.alignment = .leading
        durationGroup.spacing = 6

        timeRow.addArrangedSubview(startGroup)
        timeRow.addArrangedSubview(durationGroup)
        startGroup.widthAnchor.constraint(equalTo: durationGroup.widthAnchor).isActive = true

        let notesLabel = NSTextField(labelWithString: "Notes")
        notesLabel.font = typography.fieldLabel
        notesLabel.textColor = palette.textSecondary
        notesLabel.alignment = .left
        notesLabel.userInterfaceLayoutDirection = .leftToRight
        notesLabel.baseWritingDirection = .leftToRight

        let notesScroll = HoverFocusScrollView()
        notesScroll.translatesAutoresizingMaskIntoConstraints = false
        notesScroll.drawsBackground = true
        notesScroll.backgroundColor = inputSurface
        notesScroll.hasVerticalScroller = true
        notesScroll.hasHorizontalScroller = false
        notesScroll.borderType = .noBorder
        notesScroll.wantsLayer = true
        notesScroll.layer?.cornerRadius = 8
        notesScroll.layer?.masksToBounds = true
        notesScroll.layer?.borderWidth = 1.2
        notesScroll.layer?.borderColor = notesBorderIdle.cgColor
        notesScroll.heightAnchor.constraint(equalToConstant: 100).isActive = true
        notesScroll.onHoverChanged = { [weak self] hovering in
            guard let self else { return }
            self.notesIsHovered = hovering
            self.updateNotesBorderAppearance()
        }
        notesScroll.onMouseDown = { [weak self] in
            guard let self, let notesView = self.notesView as? ImmediateFocusTextView else { return }
            self.view.window?.makeFirstResponder(notesView)
            notesView.ensureCaretVisibleImmediately()
            self.notesIsFocused = true
            self.updateNotesBorderAppearance()
        }

        let notesView = ImmediateFocusTextView(frame: .zero)
        notesView.drawsBackground = false
        notesView.font = NSFont.systemFont(ofSize: 13, weight: .regular)
        notesView.textColor = palette.textPrimary
        notesView.insertionPointColor = palette.textPrimary
        notesView.isEditable = true
        notesView.isSelectable = true
        notesView.isRichText = false
        notesView.importsGraphics = false
        notesView.isHorizontallyResizable = false
        notesView.isVerticallyResizable = true
        notesView.autoresizingMask = [.width]
        notesView.textContainerInset = NSSize(width: 6, height: 6)
        notesView.textContainer?.widthTracksTextView = true
        notesView.textContainer?.containerSize = NSSize(
            width: notesScroll.contentSize.width,
            height: CGFloat.greatestFiniteMagnitude
        )
        notesView.delegate = self
        notesScroll.documentView = notesView
        self.notesView = notesView
        self.notesScrollView = notesScroll

        let error = NSTextField(labelWithString: "")
        error.translatesAutoresizingMaskIntoConstraints = false
        error.textColor = NSColor.systemRed
        error.font = NSFont.systemFont(ofSize: 12, weight: .semibold)
        error.isHidden = true
        self.errorLabel = error

        let actions = NSStackView()
        actions.translatesAutoresizingMaskIntoConstraints = false
        actions.orientation = .horizontal
        actions.alignment = .centerY
        actions.spacing = 10

        let cancel = NSButton(title: "Cancel", target: self, action: #selector(cancelPressed(_:)))
        cancel.bezelStyle = .rounded

        let save = NSButton(title: "Save", target: self, action: #selector(savePressed(_:)))
        save.bezelStyle = .rounded
        save.keyEquivalent = "\r"

        let actionsSpacer = NSView()
        actionsSpacer.translatesAutoresizingMaskIntoConstraints = false
        actionsSpacer.setContentHuggingPriority(.defaultLow, for: .horizontal)

        actions.addArrangedSubview(cancel)
        actions.addArrangedSubview(actionsSpacer)
        actions.addArrangedSubview(save)

        stack.addArrangedSubview(header)
        stack.addArrangedSubview(titleLabel)
        stack.addArrangedSubview(titleShell)
        stack.addArrangedSubview(timeRow)
        stack.addArrangedSubview(notesLabel)
        stack.addArrangedSubview(notesScroll)
        stack.addArrangedSubview(error)
        stack.addArrangedSubview(actions)

        root.addSubview(stack)
        NSLayoutConstraint.activate([
            root.widthAnchor.constraint(equalToConstant: 372),
            stack.leadingAnchor.constraint(equalTo: root.leadingAnchor, constant: 16),
            stack.trailingAnchor.constraint(equalTo: root.trailingAnchor, constant: -16),
            stack.topAnchor.constraint(equalTo: root.topAnchor, constant: 16),
            stack.bottomAnchor.constraint(equalTo: root.bottomAnchor, constant: -16),
            titleShell.widthAnchor.constraint(equalTo: stack.widthAnchor),
            timeRow.widthAnchor.constraint(equalTo: stack.widthAnchor),
            notesScroll.widthAnchor.constraint(equalTo: stack.widthAnchor),
            error.widthAnchor.constraint(equalTo: stack.widthAnchor),
            actions.widthAnchor.constraint(equalTo: stack.widthAnchor)
        ])

        view = root
    }

    @objc private func cancelPressed(_ sender: NSButton) {
        onCancel()
    }

    @objc private func savePressed(_ sender: NSButton) {
        setError(nil)

        let title = (titleField?.stringValue ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
        if title.isEmpty {
            setError("Please enter a title.")
            return
        }

        let durationText = (durationField?.stringValue ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
        let durationMinutes = Int(durationText) ?? 0
        if durationMinutes <= 0 {
            setError("Duration must be a positive number of minutes.")
            return
        }

        let time = timePicker?.dateValue ?? Date()
        let calendar = Calendar.current
        let dateParts = calendar.dateComponents([.year, .month, .day], from: selectedDate)
        let timeParts = calendar.dateComponents([.hour, .minute], from: time)
        var merged = DateComponents()
        merged.year = dateParts.year
        merged.month = dateParts.month
        merged.day = dateParts.day
        merged.hour = timeParts.hour
        merged.minute = timeParts.minute
        guard let start = calendar.date(from: merged) else {
            setError("Invalid start time.")
            return
        }
        let end = start.addingTimeInterval(TimeInterval(durationMinutes * 60))
        let notes = notesView?.string.trimmingCharacters(in: .whitespacesAndNewlines)
        let cleanedNotes = (notes?.isEmpty == false) ? notes : nil

        onSave(Draft(title: title, notes: cleanedNotes, startDate: start, endDate: end))
    }

    private func updateNotesBorderAppearance() {
        let color: NSColor
        let width: CGFloat
        if notesIsFocused {
            color = notesBorderFocused
            width = 1.6
        } else if notesIsHovered {
            color = notesBorderHover
            width = 1.4
        } else {
            color = notesBorderIdle
            width = 1.2
        }
        notesScrollView?.layer?.borderColor = color.cgColor
        notesScrollView?.layer?.borderWidth = width
    }

    private func setError(_ message: String?) {
        guard let errorLabel else { return }
        errorLabel.stringValue = message ?? ""
        errorLabel.isHidden = message == nil
    }

    func textDidBeginEditing(_ notification: Notification) {
        guard let current = notification.object as? NSTextView, current === notesView else { return }
        notesIsFocused = true
        updateNotesBorderAppearance()
    }

    func textDidEndEditing(_ notification: Notification) {
        guard let current = notification.object as? NSTextView, current === notesView else { return }
        notesIsFocused = false
        updateNotesBorderAppearance()
    }
}

private final class HoverFocusScrollView: NSScrollView {
    var onHoverChanged: ((Bool) -> Void)?
    var onMouseDown: (() -> Void)?
    private var hoverTrackingArea: NSTrackingArea?

    override func updateTrackingAreas() {
        super.updateTrackingAreas()
        if let hoverTrackingArea {
            removeTrackingArea(hoverTrackingArea)
        }
        let area = NSTrackingArea(
            rect: bounds,
            options: [.activeInActiveApp, .inVisibleRect, .mouseEnteredAndExited],
            owner: self,
            userInfo: nil
        )
        addTrackingArea(area)
        hoverTrackingArea = area
    }

    override func mouseEntered(with event: NSEvent) {
        super.mouseEntered(with: event)
        onHoverChanged?(true)
    }

    override func mouseExited(with event: NSEvent) {
        super.mouseExited(with: event)
        onHoverChanged?(false)
    }

    override func acceptsFirstMouse(for event: NSEvent?) -> Bool {
        true
    }

    override func mouseDown(with event: NSEvent) {
        onMouseDown?()
        if let window, !window.isKeyWindow {
            window.makeKeyAndOrderFront(nil)
            return
        }
        // Forward the click straight to the text view so caret placement/blink starts immediately.
        if let textView = documentView as? NSTextView {
            window?.makeFirstResponder(textView)
            textView.mouseDown(with: event)
            return
        }
        super.mouseDown(with: event)
    }
}

private final class ImmediateFocusTextView: NSTextView {
    override var acceptsFirstResponder: Bool { true }

    override func acceptsFirstMouse(for event: NSEvent?) -> Bool {
        true
    }

    @discardableResult
    override func becomeFirstResponder() -> Bool {
        let accepted = super.becomeFirstResponder()
        if accepted {
            ensureCaretVisibleImmediately()
        }
        return accepted
    }

    override func mouseDown(with event: NSEvent) {
        window?.makeFirstResponder(self)
        super.mouseDown(with: event)
        ensureCaretVisibleImmediately()
    }

    func ensureCaretVisibleImmediately() {
        var range = selectedRange()
        if range.location == NSNotFound {
            range = NSRange(location: string.utf16.count, length: 0)
        }
        setSelectedRange(range)
        scrollRangeToVisible(range)
        needsDisplay = true
        displayIfNeeded()
    }
}

// MARK: - Schedule actions (OAuth entry)

private extension ViewController {
    @objc func scheduleReloadButtonPressed(_ sender: NSButton) {
        scheduleReloadClicked()
    }

    @objc func scheduleScrollLeftPressed(_ sender: NSButton) {
        scrollScheduleCards(direction: -1)
    }

    @objc func scheduleScrollRightPressed(_ sender: NSButton) {
        scrollScheduleCards(direction: 1)
    }

    @objc func scheduleCardButtonPressed(_ sender: NSButton) {
        guard storeKitCoordinator.hasPremiumAccess else {
            showPaywall()
            return
        }
        guard let raw = sender.identifier?.rawValue,
              let url = URL(string: raw) else { return }
        let meeting = scheduleCachedMeetings.first(where: { $0.meetURL.absoluteString == raw })
        openMeetingURL(url, meeting: meeting)
    }

    @objc func scheduleConnectButtonPressed(_ sender: NSButton) {
        scheduleConnectClicked()
    }

    @objc func schedulePageLoadMorePressed(_ sender: NSButton) {
        appendSchedulePageBatchIfNeeded()
    }

    private func scheduleInitialHeadingText() -> String {
        hasGoogleSessionAvailable() ? "Loading…" : "Connect Google to see meetings"
    }

    private func schedulePageInitialHeadingText() -> String {
        hasGoogleSessionAvailable() ? "Loading schedule…" : "Connect Google to see meetings"
    }

    @objc func scheduleFilterDropdownChanged(_ sender: NSPopUpButton) {
        guard let selectedItem = sender.selectedItem,
              let filter = ScheduleFilter(rawValue: selectedItem.tag) else { return }
        applyScheduleFilter(filter)
    }

    private func applyScheduleFilter(_ filter: ScheduleFilter) {
        scheduleFilter = filter
        scheduleFilterDropdown?.selectItem(at: filter.rawValue)
        Task { [weak self] in
            await self?.loadSchedule()
        }
    }

    @objc func schedulePageFilterDropdownChanged(_ sender: NSPopUpButton) {
        guard let selectedItem = sender.selectedItem,
              let filter = SchedulePageFilter(rawValue: selectedItem.tag) else { return }
        schedulePageFilter = filter
        refreshSchedulePageDateFilterUI()
        applySchedulePageFiltersAndRender()
    }

    @objc func schedulePageDatePickerChanged(_ sender: NSDatePicker) {
        schedulePageFromDate = schedulePageFromDatePicker?.dateValue ?? schedulePageFromDate
        schedulePageToDate = schedulePageToDatePicker?.dateValue ?? schedulePageToDate
    }

    @objc func schedulePageApplyDateRangePressed(_ sender: NSButton) {
        if let selectedItem = schedulePageFilterDropdown?.selectedItem,
           let selectedFilter = SchedulePageFilter(rawValue: selectedItem.tag) {
            schedulePageFilter = selectedFilter
        }
        refreshSchedulePageDateFilterUI()
        applySchedulePageFiltersAndRender()
    }

    @objc func schedulePageResetFiltersPressed(_ sender: NSButton) {
        schedulePageFilter = .all
        schedulePageFilterDropdown?.selectItem(at: SchedulePageFilter.all.rawValue)
        let today = Calendar.current.startOfDay(for: Date())
        schedulePageFromDate = today
        schedulePageToDate = today
        schedulePageFromDatePicker?.dateValue = today
        schedulePageToDatePicker?.dateValue = today
        refreshSchedulePageDateFilterUI()
        applySchedulePageFiltersAndRender()
    }

    @objc private func aiCompanionRecordingsFilterChanged(_ sender: NSPopUpButton) {
        guard let selectedItem = sender.selectedItem,
              let filter = AiCompanionRecordingsFilter(rawValue: selectedItem.tag) else { return }
        aiCompanionRecordingsFilter = filter
        if filter != .customRange {
            setAiCompanionRecordingsRangeError(nil)
        }
        refreshAiCompanionRecordingsFilterChrome()
        redrawAiCompanionPageIfNeeded()
    }

    @objc private func aiCompanionFilterDatePickerChanged(_ sender: NSDatePicker) {
        aiCompanionFilterFromDate = aiCompanionFilterFromDatePicker?.dateValue ?? aiCompanionFilterFromDate
        aiCompanionFilterToDate = aiCompanionFilterToDatePicker?.dateValue ?? aiCompanionFilterToDate
    }

    @objc private func aiCompanionRecordingsApplyPressed(_ sender: NSButton) {
        aiCompanionFilterFromDate = aiCompanionFilterFromDatePicker?.dateValue ?? aiCompanionFilterFromDate
        aiCompanionFilterToDate = aiCompanionFilterToDatePicker?.dateValue ?? aiCompanionFilterToDate
        if let selectedItem = aiCompanionRecordingsFilterDropdown?.selectedItem,
           let filter = AiCompanionRecordingsFilter(rawValue: selectedItem.tag) {
            aiCompanionRecordingsFilter = filter
        }
        if aiCompanionRecordingsFilter == .customRange && !aiCompanionHasValidCustomFilterRange() {
            setAiCompanionRecordingsRangeError("Start date must be on or before end date.")
        } else {
            setAiCompanionRecordingsRangeError(nil)
        }
        refreshAiCompanionRecordingsFilterChrome()
        redrawAiCompanionPageIfNeeded()
    }

    @objc private func aiCompanionRecordingsResetPressed(_ sender: NSButton) {
        aiCompanionRecordingsFilter = .today
        aiCompanionRecordingsFilterDropdown?.selectItem(at: AiCompanionRecordingsFilter.today.rawValue)
        let today = Calendar.current.startOfDay(for: Date())
        aiCompanionFilterFromDate = today
        aiCompanionFilterToDate = today
        aiCompanionFilterFromDatePicker?.dateValue = today
        aiCompanionFilterToDatePicker?.dateValue = today
        setAiCompanionRecordingsRangeError(nil)
        refreshAiCompanionRecordingsFilterChrome()
        redrawAiCompanionPageIfNeeded()
    }

    @objc private func aiCompanionRecordingsRefreshPressed(_ sender: NSButton) {
        loadAiCompanionLocalRecordings()
        redrawAiCompanionPageIfNeeded()
    }

    @objc func schedulePageAddMeetingPressed(_ sender: NSButton) {
        guard requireGoogleLoginForCalendarScheduling() else { return }

        let accessory = NSView(frame: NSRect(x: 0, y: 0, width: 230, height: 28))

        let datePicker = NSDatePicker(frame: accessory.bounds)
        datePicker.autoresizingMask = [.width, .height]
        datePicker.datePickerMode = .single
        datePicker.datePickerStyle = .textFieldAndStepper
        datePicker.datePickerElements = [.yearMonthDay]
        datePicker.dateValue = Calendar.current.startOfDay(for: Date())
        accessory.addSubview(datePicker)

        let alert = NSAlert()
        alert.messageText = "Select date"
        alert.informativeText = "Choose a date to schedule your meeting."
        alert.alertStyle = .informational
        alert.accessoryView = accessory
        alert.addButton(withTitle: "Continue")
        alert.addButton(withTitle: "Cancel")

        guard alert.runModal() == .alertFirstButtonReturn else { return }

        calendarPageSelectedDate = Calendar.current.startOfDay(for: datePicker.dateValue)
        presentCreateMeetingPopover(relativeTo: sender)
    }

    private func scheduleTimeText(for meeting: ScheduledMeeting) -> String {
        if meeting.isAllDay { return "All day" }
        let f = DateFormatter()
        f.locale = Locale.current
        f.timeZone = TimeZone.current
        f.dateStyle = .none
        f.timeStyle = .short
        return "\(f.string(from: meeting.startDate)) - \(f.string(from: meeting.endDate))"
    }

    private func scheduleDayText(for meeting: ScheduledMeeting) -> String {
        let f = DateFormatter()
        f.locale = Locale.current
        f.timeZone = TimeZone.current
        f.dateFormat = "EEE, d MMM"
        return f.string(from: meeting.startDate)
    }

    private func scheduleDurationText(for meeting: ScheduledMeeting) -> String {
        if meeting.isAllDay { return "Duration: all day" }
        let duration = max(0, meeting.endDate.timeIntervalSince(meeting.startDate))
        let totalMinutes = Int(duration / 60)
        let hours = totalMinutes / 60
        let minutes = totalMinutes % 60
        if hours > 0, minutes > 0 { return "Duration: \(hours)h \(minutes)m" }
        if hours > 0 { return "Duration: \(hours)h" }
        return "Duration: \(minutes)m"
    }

    private func scheduleHeadingText(for meetings: [ScheduledMeeting]) -> String {
        guard let first = meetings.first else {
            return hasGoogleSessionAvailable() ? "No upcoming meetings" : "Connect Google to see meetings"
        }

        let day = Calendar.current.startOfDay(for: first.startDate)
        let f = DateFormatter()
        f.locale = Locale.current
        f.timeZone = TimeZone.current
        f.dateFormat = "EEEE, d MMM"
        return f.string(from: day)
    }

    private func openMeetingURL(_ url: URL, meeting: ScheduledMeeting? = nil) {
        let title = meeting?.title ?? "Scheduled Meeting"
        let shouldOpenMeeting = beginMeetingRecordingIfConsented(meetingTitle: title, meetingURL: url)
        guard shouldOpenMeeting else { return }
        openInDefaultBrowser(url: url)
    }

    private func renderScheduleCards(into stack: NSStackView, meetings: [ScheduledMeeting]) {
        displayedScheduleMeetings = meetings
        let shouldShowScrollControls = meetings.count > 3
        scheduleScrollLeftButton?.isHidden = !shouldShowScrollControls
        scheduleScrollRightButton?.isHidden = !shouldShowScrollControls
        scheduleCardsScrollView?.contentView.setBoundsOrigin(.zero)
        if let scroll = scheduleCardsScrollView {
            scroll.reflectScrolledClipView(scroll.contentView)
        }

        stack.arrangedSubviews.forEach { v in
            stack.removeArrangedSubview(v)
            v.removeFromSuperview()
        }

        if meetings.isEmpty {
            let empty = roundedContainer(cornerRadius: 10, color: palette.sectionCard)
            empty.translatesAutoresizingMaskIntoConstraints = false
            empty.widthAnchor.constraint(equalToConstant: 240).isActive = true
            empty.heightAnchor.constraint(equalToConstant: 150).isActive = true
            styleSurface(empty, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)

            let label = textLabel(hasGoogleSessionAvailable() ? "No meetings" : "Connect to load schedule", font: typography.cardSubtitle, color: palette.textSecondary)
            label.translatesAutoresizingMaskIntoConstraints = false
            empty.addSubview(label)
            NSLayoutConstraint.activate([
                label.centerXAnchor.constraint(equalTo: empty.centerXAnchor),
                label.centerYAnchor.constraint(equalTo: empty.centerYAnchor)
            ])
            stack.addArrangedSubview(empty)
            return
        }

        for meeting in meetings {
            stack.addArrangedSubview(scheduleCard(meeting: meeting))
        }
    }

    private func filteredMeetings(_ meetings: [ScheduledMeeting]) -> [ScheduledMeeting] {
        let now = Date()
        switch scheduleFilter {
        case .all:
            return meetings.filter { $0.endDate >= now }
        case .today:
            let start = Calendar.current.startOfDay(for: now)
            let end = Calendar.current.date(byAdding: .day, value: 1, to: start) ?? start.addingTimeInterval(86400)
            return meetings.filter { $0.startDate >= start && $0.startDate < end }
        case .week:
            let end = Calendar.current.date(byAdding: .day, value: 7, to: now) ?? now.addingTimeInterval(7 * 86400)
            return meetings.filter { $0.startDate >= now && $0.startDate <= end }
        }
    }

    private func filteredMeetingsForSchedulePage(_ meetings: [ScheduledMeeting]) -> [ScheduledMeeting] {
        let calendar = Calendar.current
        let now = Date()
        switch schedulePageFilter {
        case .all:
            return meetings.filter { $0.endDate >= now }
        case .today:
            let start = calendar.startOfDay(for: now)
            let end = calendar.date(byAdding: .day, value: 1, to: start) ?? start.addingTimeInterval(86400)
            return meetings.filter { $0.startDate >= start && $0.startDate < end }
        case .week:
            let end = calendar.date(byAdding: .day, value: 7, to: now) ?? now.addingTimeInterval(7 * 86400)
            return meetings.filter { $0.startDate >= now && $0.startDate <= end }
        case .month:
            let end = calendar.date(byAdding: .month, value: 1, to: now) ?? now.addingTimeInterval(30 * 86400)
            return meetings.filter { $0.startDate >= now && $0.startDate <= end }
        case .customRange:
            let start = calendar.startOfDay(for: schedulePageFromDate)
            let inclusiveEndDay = calendar.startOfDay(for: schedulePageToDate)
            guard let end = calendar.date(byAdding: .day, value: 1, to: inclusiveEndDay) else {
                return meetings
            }
            return meetings.filter { $0.startDate >= start && $0.startDate < end }
        }
    }

    private func refreshSchedulePageDateFilterUI() {
        let isCustom = schedulePageFilter == .customRange
        schedulePageFromDatePicker?.isEnabled = isCustom
        schedulePageToDatePicker?.isEnabled = isCustom
        let dim: CGFloat = isCustom ? 1.0 : 0.65
        schedulePageFromDatePicker?.alphaValue = 1
        schedulePageToDatePicker?.alphaValue = 1
        schedulePageFromDatePicker?.superview?.alphaValue = dim
        schedulePageToDatePicker?.superview?.alphaValue = dim
    }

    private func schedulePageHasValidCustomRange() -> Bool {
        let start = Calendar.current.startOfDay(for: schedulePageFromDate)
        let end = Calendar.current.startOfDay(for: schedulePageToDate)
        return start <= end
    }

    private func setSchedulePageRangeError(_ message: String?) {
        guard let label = schedulePageRangeErrorLabel else { return }
        label.stringValue = message ?? ""
        label.isHidden = message == nil
    }

    private func applySchedulePageFiltersAndRender() {
        schedulePageFromDate = schedulePageFromDatePicker?.dateValue ?? schedulePageFromDate
        schedulePageToDate = schedulePageToDatePicker?.dateValue ?? schedulePageToDate
        if schedulePageFilter == .customRange && !schedulePageHasValidCustomRange() {
            setSchedulePageRangeError("Start date must be on or before end date.")
            schedulePageFilteredMeetings = []
            schedulePageVisibleCount = 0
            renderSchedulePageCards()
            schedulePageDateHeadingLabel?.stringValue = "Invalid custom date range"
            return
        }

        setSchedulePageRangeError(nil)
        schedulePageFilteredMeetings = filteredMeetingsForSchedulePage(scheduleCachedMeetings)
        schedulePageVisibleCount = min(schedulePageBatchSize, schedulePageFilteredMeetings.count)
        renderSchedulePageCards()
        schedulePageDateHeadingLabel?.stringValue = scheduleHeadingText(for: schedulePageFilteredMeetings)
    }

    private func appendSchedulePageBatchIfNeeded() {
        guard schedulePageVisibleCount < schedulePageFilteredMeetings.count else { return }
        let nextCount = min(schedulePageVisibleCount + schedulePageBatchSize, schedulePageFilteredMeetings.count)
        guard nextCount > schedulePageVisibleCount else { return }
        schedulePageVisibleCount = nextCount
        renderSchedulePageCards()
        // If we're still near the bottom after adding a batch (large viewport),
        // immediately evaluate again so pagination keeps advancing in chunks of 6.
        DispatchQueue.main.async { [weak self] in
            self?.schedulePageScrolled()
        }
    }

    private func schedulePageScrolled() {
        guard let scroll = schedulePageCardsScrollView else { return }
        let contentBounds = scroll.contentView.bounds
        let contentHeight = scroll.documentView?.bounds.height ?? 0
        guard contentHeight > 0 else { return }
        let remaining = contentHeight - (contentBounds.origin.y + contentBounds.height)
        if remaining <= 200 {
            appendSchedulePageBatchIfNeeded()
        }
    }

    private func renderSchedulePageCards() {
        guard let stack = schedulePageCardsStack else { return }
        stack.arrangedSubviews.forEach { v in
            stack.removeArrangedSubview(v)
            v.removeFromSuperview()
        }

        let visibleMeetings = Array(schedulePageFilteredMeetings.prefix(schedulePageVisibleCount))
        if visibleMeetings.isEmpty {
            let empty = roundedContainer(cornerRadius: 10, color: palette.sectionCard)
            empty.translatesAutoresizingMaskIntoConstraints = false
            empty.heightAnchor.constraint(equalToConstant: 140).isActive = true
            styleSurface(empty, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
            let label = textLabel(hasGoogleSessionAvailable() ? "No meetings for selected filters" : "Connect to load schedule", font: typography.cardSubtitle, color: palette.textSecondary)
            label.translatesAutoresizingMaskIntoConstraints = false
            empty.addSubview(label)
            NSLayoutConstraint.activate([
                label.centerXAnchor.constraint(equalTo: empty.centerXAnchor),
                label.centerYAnchor.constraint(equalTo: empty.centerYAnchor)
            ])
            stack.addArrangedSubview(empty)
            empty.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
            return
        }

        var index = 0
        while index < visibleMeetings.count {
            let row = NSStackView()
            row.translatesAutoresizingMaskIntoConstraints = false
            row.userInterfaceLayoutDirection = .leftToRight
            row.orientation = .horizontal
            row.alignment = .top
            row.spacing = schedulePageCardSpacing
            row.distribution = .fillEqually
            let rowEnd = min(index + schedulePageCardsPerRow, visibleMeetings.count)
            for meeting in visibleMeetings[index..<rowEnd] {
                row.addArrangedSubview(scheduleCard(meeting: meeting, useFlexibleWidth: true, contentHeight: schedulePageCardHeight))
            }
            stack.addArrangedSubview(row)
            row.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
            index = rowEnd
        }

        if schedulePageVisibleCount < schedulePageFilteredMeetings.count {
            let pagination = NSStackView()
            pagination.translatesAutoresizingMaskIntoConstraints = false
            pagination.orientation = .horizontal
            pagination.alignment = .centerY
            pagination.spacing = 10

            let moreLabel = textLabel(
                "Showing \(schedulePageVisibleCount) of \(schedulePageFilteredMeetings.count)",
                font: NSFont.systemFont(ofSize: 12, weight: .medium),
                color: palette.textMuted
            )
            pagination.addArrangedSubview(moreLabel)

            let spacer = NSView()
            spacer.translatesAutoresizingMaskIntoConstraints = false
            spacer.setContentHuggingPriority(.defaultLow, for: .horizontal)
            pagination.addArrangedSubview(spacer)

            stack.addArrangedSubview(pagination)
            pagination.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
        }
    }

    private func scrollScheduleCards(direction: Int) {
        guard let scroll = scheduleCardsScrollView else { return }
        let contentBounds = scroll.contentView.bounds
        let step = max(220, contentBounds.width * 0.7)
        let proposedX = contentBounds.origin.x + (CGFloat(direction) * step)
        let maxX = max(0, scroll.documentView?.bounds.width ?? 0 - contentBounds.width)
        let nextX = min(max(0, proposedX), maxX)
        scroll.contentView.animator().setBoundsOrigin(NSPoint(x: nextX, y: 0))
        scroll.reflectScrolledClipView(scroll.contentView)
    }

    private func loadSchedule() async {
        do {
            if hasGoogleSessionAvailable() == false {
                await MainActor.run {
                    updateGoogleAuthButtonTitle()
                    applyGoogleProfile(nil)
                    scheduleDateHeadingLabel?.stringValue = "Connect Google to see meetings"
                    schedulePageDateHeadingLabel?.stringValue = "Connect Google to see meetings"
                    if let stack = scheduleCardsStack {
                        renderScheduleCards(into: stack, meetings: [])
                    }
                    scheduleCachedMeetings = []
                    pageCache[.aiCompanion] = nil
                    publishWidgetMeetingsSnapshot(from: [])
                    DesktopWidgetWindowManager.shared.refreshForAuthStateChange()
                    MeetingReminderManager.shared.cancelAllReminders()
                    applySchedulePageFiltersAndRender()
                    if calendarPageGridStack != nil {
                        calendarPageMonthLabel?.stringValue = calendarMonthTitleText(for: calendarPageMonthAnchor)
                        renderCalendarMonthGrid()
                        renderCalendarSelectedDay()
                    }
                }
                return
            }

            let token = try await googleOAuth.validAccessToken(presentingWindow: view.window)
            let profile = try? await googleOAuth.fetchUserProfile(accessToken: token)
            let meetings = try await calendarClient.fetchUpcomingMeetings(accessToken: token)
            let filtered = filteredMeetings(meetings)

            await MainActor.run {
                updateGoogleAuthButtonTitle()
                applyGoogleProfile(profile.map { self.makeGoogleProfileDisplay(from: $0) })
                scheduleDateHeadingLabel?.stringValue = scheduleHeadingText(for: filtered)
                if let stack = scheduleCardsStack {
                    renderScheduleCards(into: stack, meetings: filtered)
                }
                scheduleCachedMeetings = meetings
                pageCache[.aiCompanion] = nil
                publishWidgetMeetingsSnapshot(from: filtered)
                DesktopWidgetWindowManager.shared.refreshForAuthStateChange()
                if storeKitCoordinator.hasPremiumAccess {
                    MeetingReminderManager.shared.scheduleReminders(for: meetings)
                }
                applySchedulePageFiltersAndRender()
                if calendarPageGridStack != nil {
                    calendarPageMonthLabel?.stringValue = calendarMonthTitleText(for: calendarPageMonthAnchor)
                    renderCalendarMonthGrid()
                    renderCalendarSelectedDay()
                }
            }
        } catch {
            await MainActor.run {
                updateGoogleAuthButtonTitle()
                if hasGoogleSessionAvailable() == false {
                    applyGoogleProfile(nil)
                }
                scheduleDateHeadingLabel?.stringValue = "Couldn’t load schedule"
                schedulePageDateHeadingLabel?.stringValue = "Couldn’t load schedule"
                if let stack = scheduleCardsStack {
                    renderScheduleCards(into: stack, meetings: [])
                }
                scheduleCachedMeetings = []
                pageCache[.aiCompanion] = nil
                publishWidgetMeetingsSnapshot(from: [])
                DesktopWidgetWindowManager.shared.refreshForAuthStateChange()
                MeetingReminderManager.shared.cancelAllReminders()
                applySchedulePageFiltersAndRender()
                if calendarPageGridStack != nil {
                    calendarPageMonthLabel?.stringValue = calendarMonthTitleText(for: calendarPageMonthAnchor)
                    renderCalendarMonthGrid()
                    renderCalendarSelectedDay()
                }
                showSimpleError("Couldn’t load schedule.", error: error)
            }
        }
    }

    private func publishWidgetMeetingsSnapshot(from meetings: [ScheduledMeeting]) {
        let formatter = DateFormatter()
        formatter.dateFormat = "EEE, h:mm a"
        formatter.locale = Locale.current
        let payload = meetings.prefix(widgetSnapshotLimit).map { meeting in
            let endText = DateFormatter.localizedString(from: meeting.endDate, dateStyle: .none, timeStyle: .short)
            return WidgetMeetingSnapshot(
                id: meeting.id,
                title: meeting.title,
                timeText: "\(formatter.string(from: meeting.startDate)) - \(endText)",
                joinLink: meeting.meetURL.absoluteString
            )
        }
        if let data = try? JSONEncoder().encode(payload) {
            UserDefaults.standard.set(data, forKey: WidgetMeetingStore.key)
        } else {
            UserDefaults.standard.removeObject(forKey: WidgetMeetingStore.key)
        }
        NotificationCenter.default.post(name: .meetingsSnapshotUpdated, object: nil)
    }

    func showScheduleHelp() {
        let alert = NSAlert()
        alert.messageText = "Google schedule"
        alert.informativeText = "To show scheduled meetings, connect your Google account. You’ll need a Google OAuth client ID (Desktop) and a redirect URI matching the app’s callback scheme."
        alert.addButton(withTitle: "OK")
        alert.runModal()
    }

    func scheduleReloadClicked() {
        Task { [weak self] in
            guard let self else { return }
            do {
                try await self.ensureGoogleClientIdConfigured(presentingWindow: self.view.window)
                _ = try await self.googleOAuth.validAccessToken(presentingWindow: self.view.window)
                await MainActor.run {
                    self.scheduleDateHeadingLabel?.stringValue = "Refreshing…"
                    self.pageCache[.joinMeetings] = nil
                    self.pageCache[.photo] = nil
                    self.pageCache[.widgets] = nil
                    self.pageCache[.aiCompanion] = nil
                    self.showSidebarPage(self.selectedSidebarPage)
                }
                await self.loadSchedule()
            } catch {
                await MainActor.run {
                    self.showSimpleError("Couldn’t refresh schedule.", error: error)
                }
            }
        }
    }

    func scheduleConnectClicked() {
        Task { [weak self] in
            guard let self else { return }
            do {
                if self.hasGoogleSessionAvailable() {
                    await MainActor.run { self.showGoogleAccountMenu() }
                    return
                }

                try await self.ensureGoogleClientIdConfigured(presentingWindow: self.view.window)
                let token = try await self.googleOAuth.validAccessToken(presentingWindow: self.view.window)
                let profile = try? await self.googleOAuth.fetchUserProfile(accessToken: token)
                await MainActor.run {
                    self.updateGoogleAuthButtonTitle()
                    self.applyGoogleProfile(profile.map { self.makeGoogleProfileDisplay(from: $0) })
                    self.pageCache[.joinMeetings] = nil
                    self.pageCache[.photo] = nil
                    self.pageCache[.video] = nil
                    self.pageCache[.widgets] = nil
                    self.pageCache[.settings] = nil
                    self.pageCache[.aiCompanion] = nil
                    self.showSidebarPage(self.selectedSidebarPage)
                }
                // Ensure desktop widgets refresh immediately with the newly available meetings.
                await self.loadSchedule()
            } catch {
                self.showSimpleError("Couldn’t connect Google account.", error: error)
            }
        }
    }

    private func showGoogleAccountMenu() {
        guard let button = scheduleGoogleAuthButton else { return }
        if googleAccountPopover?.isShown == true {
            googleAccountPopover?.performClose(nil)
            googleAccountPopover = nil
            return
        }

        let popover = NSPopover()
        popover.behavior = .transient
        popover.animates = true
        popover.appearance = NSAppearance(named: darkModeEnabled ? .darkAqua : .aqua)

        let name = scheduleCurrentProfile?.name ?? "Google account"
        let email = scheduleCurrentProfile?.email ?? "Signed in"
        let avatar = scheduleProfileMenuAvatar

        popover.contentViewController = GoogleAccountMenuViewController(
            palette: palette,
            darkModeEnabled: darkModeEnabled,
            displayName: name,
            email: email,
            avatar: avatar,
            onSignOut: { [weak self] in
                self?.googleAccountPopover?.performClose(nil)
                self?.googleAccountPopover = nil
                self?.performGoogleSignOut()
            }
        )

        googleAccountPopover = popover
        popover.show(relativeTo: button.bounds, of: button, preferredEdge: .minY)
    }

    private func performGoogleSignOut() {
        do {
            MeetingReminderManager.shared.cancelAllReminders()
            try googleOAuth.signOut()
            applyGoogleProfile(nil)
            publishWidgetMeetingsSnapshot(from: [])
            DesktopWidgetWindowManager.shared.refreshForAuthStateChange()
            updateGoogleAuthButtonTitle()
            pageCache[.joinMeetings] = nil
            pageCache[.photo] = nil
            pageCache[.video] = nil
            pageCache[.widgets] = nil
            pageCache[.settings] = nil
            pageCache[.aiCompanion] = nil
            showSidebarPage(selectedSidebarPage)
            Task { [weak self] in
                await self?.loadSchedule()
            }
        } catch {
            showSimpleError("Couldn’t logout Google account.", error: error)
        }
    }

    private func updateGoogleAuthButtonTitle() {
        let signedIn = hasGoogleSessionAvailable()
        guard let button = scheduleGoogleAuthButton else { return }

        let profileName = scheduleCurrentProfile?.name ?? "Google account"
        let ringHostInset: CGFloat = signedIn ? 14 : 0
        scheduleGoogleAuthHostPadWidthConstraint?.constant = ringHostInset
        scheduleGoogleAuthHostPadHeightConstraint?.constant = ringHostInset
        scheduleGoogleAuthHostView?.setAvatarRingMode(signedIn)
        scheduleGoogleAuthHostView?.updateRingAppearance(isDark: darkModeEnabled, accent: palette.primaryBlue)
        if signedIn == false {
            scheduleGoogleAuthHostView?.setProfileHoverActive(false)
        }

        if signedIn {
            button.setAccessibilityLabel("\(profileName), Google account")
            button.attributedTitle = NSAttributedString(string: "")
            button.imagePosition = .imageOnly
            button.imageScaling = .scaleProportionallyDown
            button.symbolConfiguration = nil
            scheduleGoogleAuthButtonHeightConstraint?.constant = scheduleGoogleSignedInAvatarSize
            scheduleGoogleAuthButtonWidthConstraint?.constant = scheduleGoogleSignedInAvatarSize
            button.layer?.cornerRadius = scheduleGoogleSignedInAvatarSize / 2

            let symbol = NSImage(systemSymbolName: "person.crop.circle.fill", accessibilityDescription: "Profile")
            if let symbol {
                let sized = resizedImage(symbol, to: NSSize(width: scheduleGoogleSignedInAvatarSize, height: scheduleGoogleSignedInAvatarSize))
                button.image = sized
                button.contentTintColor = palette.textSecondary
            } else {
                button.image = nil
                button.contentTintColor = nil
            }
            scheduleProfileMenuAvatar = button.image
        } else {
            button.setAccessibilityLabel("Sign in with Google")
            let title = "Sign in with Google"
            let titleFont = NSFont.systemFont(ofSize: 14, weight: .medium)
            let titleColor = darkModeEnabled ? NSColor(calibratedWhite: 0.96, alpha: 1) : NSColor(calibratedRed: 0.13, green: 0.14, blue: 0.16, alpha: 1)
            button.attributedTitle = NSAttributedString(string: title, attributes: [
                .font: titleFont,
                .foregroundColor: titleColor
            ])
            let textWidth = (title as NSString).size(withAttributes: [.font: titleFont]).width
            let idealWidth = ceil(textWidth + 80)
            scheduleGoogleAuthButtonWidthConstraint?.constant = min(320, max(188, idealWidth))
            scheduleGoogleAuthButtonHeightConstraint?.constant = 42
            button.layer?.cornerRadius = 21

            button.imagePosition = .imageLeading
            button.imageScaling = .scaleNone
            if let g = NSImage(named: "GoogleGLogo") {
                button.image = paddedTrailingImage(g, iconSize: NSSize(width: 22, height: 22), trailingPadding: 8)
            } else {
                button.image = nil
            }
            button.contentTintColor = nil
        }

        applyGoogleAuthButtonSurface()
    }

    private func makeGoogleProfileDisplay(from profile: GoogleUserProfile) -> GoogleProfileDisplay {
        let cleanedName = profile.name?.trimmingCharacters(in: .whitespacesAndNewlines)
        let cleanedEmail = profile.email?.trimmingCharacters(in: .whitespacesAndNewlines)
        return GoogleProfileDisplay(
            name: (cleanedName?.isEmpty == false ? cleanedName : nil) ?? "Google User",
            email: (cleanedEmail?.isEmpty == false ? cleanedEmail : nil) ?? "Signed in",
            pictureURL: profile.picture.flatMap(URL.init(string:))
        )
    }

    private func applyGoogleProfile(_ profile: GoogleProfileDisplay?) {
        scheduleProfileImageTask?.cancel()
        scheduleProfileImageTask = nil
        if profile == nil {
            scheduleProfileMenuAvatar = nil
        }
        scheduleCurrentProfile = profile

        updateGoogleAuthButtonTitle()
        pageCache[.aiCompanion] = nil
        redrawAiCompanionPageIfNeeded()

        guard let profile, let pictureURL = profile.pictureURL else { return }
        let avatarDiameter = scheduleGoogleSignedInAvatarSize
        scheduleProfileImageTask = Task { [weak self] in
            do {
                let (data, _) = try await URLSession.shared.data(from: pictureURL)
                if Task.isCancelled { return }
                guard let image = NSImage(data: data) else { return }
                await MainActor.run { [weak self] in
                    guard let self else { return }
                    let rounded = self.circularProfileImage(image, diameter: avatarDiameter)
                    self.scheduleProfileMenuAvatar = circularNSImage(rounded, diameter: 48)
                    self.scheduleGoogleAuthButton?.image = rounded
                    self.scheduleGoogleAuthButton?.contentTintColor = nil
                }
            } catch {
                // Keep placeholder avatar if image fetch fails.
            }
        }
    }

    private func resizedImage(_ image: NSImage, to size: NSSize) -> NSImage {
        let result = NSImage(size: size)
        result.lockFocus()
        image.draw(in: NSRect(origin: .zero, size: size),
                   from: NSRect(origin: .zero, size: image.size),
                   operation: .copy,
                   fraction: 1.0)
        result.unlockFocus()
        result.isTemplate = false
        return result
    }

    /// Clips a photo to a circle for the signed-in avatar (Google userinfo `picture` URLs are usually square).
    private func circularProfileImage(_ image: NSImage, diameter: CGFloat) -> NSImage {
        circularNSImage(image, diameter: diameter)
    }

    private func paddedTrailingImage(_ image: NSImage, iconSize: NSSize, trailingPadding: CGFloat) -> NSImage {
        let base = resizedImage(image, to: iconSize)
        let canvas = NSSize(width: iconSize.width + trailingPadding, height: iconSize.height)
        let result = NSImage(size: canvas)
        result.lockFocus()
        base.draw(in: NSRect(x: 0, y: 0, width: iconSize.width, height: iconSize.height),
                  from: NSRect(origin: .zero, size: base.size),
                  operation: .copy,
                  fraction: 1.0)
        result.unlockFocus()
        result.isTemplate = false
        return result
    }

    private func applyGoogleAuthButtonSurface() {
        guard let button = scheduleGoogleAuthButton else { return }
        let signedIn = hasGoogleSessionAvailable()
        let isDark = darkModeEnabled
        if signedIn {
            button.layer?.backgroundColor = NSColor.clear.cgColor
            button.layer?.borderWidth = 0
            scheduleGoogleAuthHostView?.updateRingAppearance(isDark: isDark, accent: palette.primaryBlue)
            return
        }
        let baseBackground = isDark
            ? NSColor(calibratedRed: 8.0 / 255.0, green: 14.0 / 255.0, blue: 24.0 / 255.0, alpha: 1)
            : NSColor.white
        let hoverBlend = isDark ? NSColor.white : NSColor.black
        let hoverBackground = baseBackground.blended(withFraction: 0.07, of: hoverBlend) ?? baseBackground
        let baseBorder = isDark
            ? NSColor(calibratedWhite: 0.50, alpha: 1)
            : NSColor(calibratedWhite: 0.72, alpha: 1)
        let hoverBorder = isDark
            ? NSColor(calibratedWhite: 0.62, alpha: 1)
            : NSColor(calibratedWhite: 0.56, alpha: 1)
        button.layer?.borderWidth = 1
        button.layer?.backgroundColor = (scheduleGoogleAuthHovering ? hoverBackground : baseBackground).cgColor
        button.layer?.borderColor = (scheduleGoogleAuthHovering ? hoverBorder : baseBorder).cgColor
    }

    @MainActor
    func ensureGoogleClientIdConfigured(presentingWindow: NSWindow?) async throws {
        _ = presentingWindow
        guard googleOAuth.configuredClientId() != nil else { throw GoogleOAuthError.missingClientId }
        guard googleOAuth.configuredClientSecret() != nil else { throw GoogleOAuthError.missingClientSecret }
    }

    func showSimpleError(_ title: String, error: Error) {
        DispatchQueue.main.async {
            let alert = NSAlert()
            alert.alertStyle = .warning
            alert.messageText = title
            alert.informativeText = error.localizedDescription
            alert.addButton(withTitle: "OK")
            alert.runModal()
        }
    }
}

private struct Palette {
    let pageBackground: NSColor
    let sidebarBackground: NSColor
    let sectionCard: NSColor
    let tabBarBackground: NSColor
    let tabIdleBackground: NSColor
    let inputBackground: NSColor
    let inputBorder: NSColor
    let primaryBlue: NSColor
    let primaryBlueBorder: NSColor
    let cancelButton: NSColor
    let meetingBadge: NSColor
    let separator: NSColor
    let textPrimary: NSColor
    let textSecondary: NSColor
    let textTertiary: NSColor
    let textMuted: NSColor

    init(isDarkMode: Bool) {
        if isDarkMode {
            pageBackground = NSColor(calibratedRed: 10.0 / 255.0, green: 11.0 / 255.0, blue: 12.0 / 255.0, alpha: 1)
            sidebarBackground = NSColor(calibratedRed: 16.0 / 255.0, green: 17.0 / 255.0, blue: 19.0 / 255.0, alpha: 1)
            sectionCard = NSColor(calibratedRed: 22.0 / 255.0, green: 23.0 / 255.0, blue: 26.0 / 255.0, alpha: 1)
            tabBarBackground = NSColor(calibratedRed: 22.0 / 255.0, green: 23.0 / 255.0, blue: 26.0 / 255.0, alpha: 1)
            tabIdleBackground = NSColor(calibratedRed: 22.0 / 255.0, green: 23.0 / 255.0, blue: 26.0 / 255.0, alpha: 1)
            inputBackground = NSColor(calibratedRed: 20.0 / 255.0, green: 21.0 / 255.0, blue: 24.0 / 255.0, alpha: 1)
            inputBorder = NSColor(calibratedRed: 38.0 / 255.0, green: 40.0 / 255.0, blue: 44.0 / 255.0, alpha: 1)
            primaryBlue = NSColor(calibratedRed: 27.0 / 255.0, green: 115.0 / 255.0, blue: 232.0 / 255.0, alpha: 1)
            primaryBlueBorder = NSColor(calibratedRed: 42.0 / 255.0, green: 118.0 / 255.0, blue: 220.0 / 255.0, alpha: 1)
            cancelButton = NSColor(calibratedRed: 20.0 / 255.0, green: 21.0 / 255.0, blue: 24.0 / 255.0, alpha: 1)
            meetingBadge = NSColor(calibratedRed: 0.88, green: 0.66, blue: 0.14, alpha: 1)
            separator = NSColor(calibratedRed: 26.0 / 255.0, green: 27.0 / 255.0, blue: 30.0 / 255.0, alpha: 1)
            textPrimary = NSColor(calibratedWhite: 0.98, alpha: 1)
            textSecondary = NSColor(calibratedWhite: 0.78, alpha: 1)
            textTertiary = NSColor(calibratedWhite: 0.66, alpha: 1)
            textMuted = NSColor(calibratedWhite: 0.44, alpha: 1)
        } else {
            pageBackground = NSColor(calibratedRed: 244.0 / 255.0, green: 246.0 / 255.0, blue: 249.0 / 255.0, alpha: 1)
            sidebarBackground = NSColor(calibratedRed: 232.0 / 255.0, green: 236.0 / 255.0, blue: 242.0 / 255.0, alpha: 1)
            sectionCard = NSColor.white
            tabBarBackground = NSColor.white
            tabIdleBackground = NSColor.white
            inputBackground = NSColor(calibratedRed: 247.0 / 255.0, green: 249.0 / 255.0, blue: 252.0 / 255.0, alpha: 1)
            inputBorder = NSColor(calibratedRed: 211.0 / 255.0, green: 218.0 / 255.0, blue: 228.0 / 255.0, alpha: 1)
            primaryBlue = NSColor(calibratedRed: 27.0 / 255.0, green: 115.0 / 255.0, blue: 232.0 / 255.0, alpha: 1)
            primaryBlueBorder = NSColor(calibratedRed: 42.0 / 255.0, green: 118.0 / 255.0, blue: 220.0 / 255.0, alpha: 1)
            cancelButton = NSColor(calibratedRed: 240.0 / 255.0, green: 243.0 / 255.0, blue: 248.0 / 255.0, alpha: 1)
            meetingBadge = NSColor(calibratedRed: 0.88, green: 0.66, blue: 0.14, alpha: 1)
            separator = NSColor(calibratedRed: 212.0 / 255.0, green: 219.0 / 255.0, blue: 229.0 / 255.0, alpha: 1)
            textPrimary = NSColor(calibratedRed: 32.0 / 255.0, green: 38.0 / 255.0, blue: 47.0 / 255.0, alpha: 1)
            textSecondary = NSColor(calibratedRed: 82.0 / 255.0, green: 92.0 / 255.0, blue: 107.0 / 255.0, alpha: 1)
            textTertiary = NSColor(calibratedRed: 110.0 / 255.0, green: 120.0 / 255.0, blue: 136.0 / 255.0, alpha: 1)
            textMuted = NSColor(calibratedRed: 134.0 / 255.0, green: 145.0 / 255.0, blue: 162.0 / 255.0, alpha: 1)
        }
    }
}

private struct Typography {
    let sidebarBrand = NSFont.systemFont(ofSize: 26, weight: .bold)
    let sidebarSection = NSFont.systemFont(ofSize: 11, weight: .medium)
    let sidebarIcon = NSFont.systemFont(ofSize: 12, weight: .medium)
    let sidebarItem = NSFont.systemFont(ofSize: 16, weight: .medium)

    let pageTitle = NSFont.systemFont(ofSize: 27, weight: .semibold)
    let joinWithURLTitle = NSFont.systemFont(ofSize: 17, weight: .semibold)
    let sectionTitleBold = NSFont.systemFont(ofSize: 25, weight: .bold)
    let dateHeading = NSFont.systemFont(ofSize: 18, weight: .medium)

    let tabIcon = NSFont.systemFont(ofSize: 13, weight: .regular)
    let tabTitle = NSFont.systemFont(ofSize: 31 / 2, weight: .semibold)

    let fieldLabel = NSFont.systemFont(ofSize: 15, weight: .medium)
    let inputPlaceholder = NSFont.systemFont(ofSize: 14, weight: .regular)
    let buttonText = NSFont.systemFont(ofSize: 16, weight: .medium)
    let filterText = NSFont.systemFont(ofSize: 15, weight: .regular)
    let filterArrow = NSFont.systemFont(ofSize: 12, weight: .regular)
    let iconButton = NSFont.systemFont(ofSize: 14, weight: .medium)

    let cardIcon = NSFont.systemFont(ofSize: 8, weight: .bold)
    let cardTitle = NSFont.systemFont(ofSize: 15, weight: .semibold)
    let cardSubtitle = NSFont.systemFont(ofSize: 13, weight: .bold)
    let cardTime = NSFont.systemFont(ofSize: 12, weight: .regular)
}

// MARK: - In-app browser (macOS WKWebView + chrome)
// Note: This target is AppKit/macOS. iOS would use WKWebView or SFSafariViewController; Android would use WebView or Custom Tabs.

private enum InAppBrowserURLPolicy: Equatable {
    case allowAll
    case whitelist(hostSuffixes: [String])
}

private func inAppBrowserURLAllowed(_ url: URL, policy: InAppBrowserURLPolicy) -> Bool {
    let scheme = (url.scheme ?? "").lowercased()
    if scheme == "about" { return true }
    guard scheme == "http" || scheme == "https" else { return false }
    guard let host = url.host?.lowercased() else { return false }
    switch policy {
    case .allowAll:
        return true
    case .whitelist(let suffixes):
        for suffix in suffixes {
            let s = suffix.lowercased()
            if host == s || host.hasSuffix("." + s) { return true }
        }
        return false
    }
}

private enum InAppBrowserWebKitSupport {
    static func makeWebViewConfiguration() -> WKWebViewConfiguration {
        let config = WKWebViewConfiguration()
        config.websiteDataStore = .default()
        config.preferences.javaScriptCanOpenWindowsAutomatically = true
        if #available(macOS 12.3, *) {
            config.preferences.isElementFullscreenEnabled = true
        }
        config.mediaTypesRequiringUserActionForPlayback = []
        if #available(macOS 11.0, *) {
            config.defaultWebpagePreferences.allowsContentJavaScript = true
        }
        config.applicationNameForUserAgent = "MeetingsApp/1.0"
        return config
    }
}

private final class InAppBrowserWindowController: NSWindowController {
    private static let defaultContentSize = NSSize(width: 1100, height: 760)
    private static let minimumContentSize = NSSize(width: 800, height: 520)

    private let browserViewController = InAppBrowserContainerViewController()

    init() {
        let browserWindow = NSWindow(
            contentRect: NSRect(origin: .zero, size: Self.defaultContentSize),
            styleMask: [.titled, .closable, .miniaturizable, .resizable],
            backing: .buffered,
            defer: false
        )
        browserWindow.title = "Browser"
        browserWindow.isRestorable = false
        browserWindow.setFrameAutosaveName("")
        browserWindow.minSize = browserWindow.frameRect(forContentRect: NSRect(origin: .zero, size: Self.minimumContentSize)).size
        browserWindow.center()
        browserWindow.contentViewController = browserViewController
        super.init(window: browserWindow)
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) {
        nil
    }

    /// Resets size and position each time the browser is shown so a previously tiny window is never reused.
    func applyDefaultFrameCenteredOnVisibleScreen() {
        guard let w = window, let screen = w.screen ?? NSScreen.main else { return }
        let windowFrame = w.frameRect(forContentRect: NSRect(origin: .zero, size: Self.defaultContentSize))
        let vf = screen.visibleFrame
        var frame = windowFrame
        frame.origin.x = vf.midX - frame.width / 2
        frame.origin.y = vf.midY - frame.height / 2
        if frame.maxX > vf.maxX { frame.origin.x = vf.maxX - frame.width }
        if frame.minX < vf.minX { frame.origin.x = vf.minX }
        if frame.maxY > vf.maxY { frame.origin.y = vf.maxY - frame.height }
        if frame.minY < vf.minY { frame.origin.y = vf.minY }
        w.setFrame(frame, display: true)
    }

    func load(url: URL, policy: InAppBrowserURLPolicy) {
        browserViewController.setNavigationPolicy(policy)
        browserViewController.load(url: url)
    }
}

private final class InAppBrowserContainerViewController: NSViewController, WKNavigationDelegate, WKUIDelegate, NSTextFieldDelegate {
    private var webView: WKWebView!
    private var webContainerView: NSView!
    private weak var urlField: NSTextField?
    private var backButton: NSButton!
    private var forwardButton: NSButton!
    private var reloadStopButton: NSButton!
    private var goButton: NSButton!
    private var progressBar: NSProgressIndicator!

    private var lastLoadedURL: URL?
    private var navigationPolicy: InAppBrowserURLPolicy = .allowAll
    private var processTerminateRetryCount = 0
    /// Includes fresh WKWebView instances so each retry gets a new WebContent process after a crash.
    private let maxProcessTerminateRetries = 3
    private var kvoTokens: [NSKeyValueObservation] = []

    deinit {
        kvoTokens.removeAll()
    }

    func setNavigationPolicy(_ policy: InAppBrowserURLPolicy) {
        navigationPolicy = policy
    }

    override func loadView() {
        let root = NSView()
        root.translatesAutoresizingMaskIntoConstraints = false

        let wv = makeWebView()
        webView = wv

        let webHost = NSView()
        webHost.translatesAutoresizingMaskIntoConstraints = false
        webHost.wantsLayer = true
        webHost.addSubview(wv)
        NSLayoutConstraint.activate([
            wv.leadingAnchor.constraint(equalTo: webHost.leadingAnchor),
            wv.trailingAnchor.constraint(equalTo: webHost.trailingAnchor),
            wv.topAnchor.constraint(equalTo: webHost.topAnchor),
            wv.bottomAnchor.constraint(equalTo: webHost.bottomAnchor)
        ])
        webContainerView = webHost

        let toolbar = NSStackView()
        toolbar.translatesAutoresizingMaskIntoConstraints = false
        toolbar.orientation = .horizontal
        toolbar.spacing = 8
        toolbar.alignment = .centerY
        toolbar.edgeInsets = NSEdgeInsets(top: 6, left: 10, bottom: 6, right: 10)

        backButton = makeToolbarButton(title: "◀", symbolName: "chevron.backward", accessibilityDescription: "Back")
        backButton.target = self
        backButton.action = #selector(goBack)
        forwardButton = makeToolbarButton(title: "▶", symbolName: "chevron.forward", accessibilityDescription: "Forward")
        forwardButton.target = self
        forwardButton.action = #selector(goForward)
        reloadStopButton = makeToolbarButton(title: "Reload", symbolName: "arrow.clockwise", accessibilityDescription: "Reload")
        reloadStopButton.target = self
        reloadStopButton.action = #selector(reloadOrStop)

        let field = NSTextField(string: "")
        field.translatesAutoresizingMaskIntoConstraints = false
        field.font = NSFont.systemFont(ofSize: 13, weight: .regular)
        field.placeholderString = "Address"
        field.cell?.sendsActionOnEndEditing = false
        field.delegate = self
        urlField = field

        goButton = NSButton(title: "Go", target: self, action: #selector(addressFieldSubmitted))
        goButton.translatesAutoresizingMaskIntoConstraints = false
        goButton.bezelStyle = .rounded

        toolbar.addArrangedSubview(backButton)
        toolbar.addArrangedSubview(forwardButton)
        toolbar.addArrangedSubview(reloadStopButton)
        toolbar.addArrangedSubview(field)
        toolbar.addArrangedSubview(goButton)
        field.widthAnchor.constraint(greaterThanOrEqualToConstant: 240).isActive = true

        let bar = NSProgressIndicator()
        bar.translatesAutoresizingMaskIntoConstraints = false
        bar.style = .bar
        bar.isIndeterminate = false
        bar.minValue = 0
        bar.maxValue = 1
        bar.doubleValue = 0
        bar.isHidden = true
        progressBar = bar

        let separator = NSBox()
        separator.translatesAutoresizingMaskIntoConstraints = false
        separator.boxType = .separator

        webView.navigationDelegate = self
        webView.uiDelegate = self

        root.addSubview(toolbar)
        root.addSubview(bar)
        root.addSubview(separator)
        root.addSubview(webHost)

        NSLayoutConstraint.activate([
            toolbar.leadingAnchor.constraint(equalTo: root.leadingAnchor),
            toolbar.trailingAnchor.constraint(equalTo: root.trailingAnchor),
            toolbar.topAnchor.constraint(equalTo: root.topAnchor),

            bar.leadingAnchor.constraint(equalTo: root.leadingAnchor),
            bar.trailingAnchor.constraint(equalTo: root.trailingAnchor),
            bar.topAnchor.constraint(equalTo: toolbar.bottomAnchor),
            bar.heightAnchor.constraint(equalToConstant: 3),

            separator.leadingAnchor.constraint(equalTo: root.leadingAnchor),
            separator.trailingAnchor.constraint(equalTo: root.trailingAnchor),
            separator.topAnchor.constraint(equalTo: bar.bottomAnchor),

            webHost.leadingAnchor.constraint(equalTo: root.leadingAnchor),
            webHost.trailingAnchor.constraint(equalTo: root.trailingAnchor),
            webHost.topAnchor.constraint(equalTo: separator.bottomAnchor),
            webHost.bottomAnchor.constraint(equalTo: root.bottomAnchor)
        ])

        view = root
        installWebViewObservers()
        syncToolbarFromWebView()
    }

    private func makeWebView() -> WKWebView {
        let wv = WKWebView(frame: .zero, configuration: InAppBrowserWebKitSupport.makeWebViewConfiguration())
        wv.translatesAutoresizingMaskIntoConstraints = false
        return wv
    }

    private func teardownWebViewObservers() {
        kvoTokens.removeAll()
    }

    /// New `WKWebView` = new WebContent process (helps after GPU/JS crashes on heavy sites like Meet).
    private func replaceWebViewAndLoad(url: URL) {
        teardownWebViewObservers()
        webView.navigationDelegate = nil
        webView.uiDelegate = nil
        webView.removeFromSuperview()

        let wv = makeWebView()
        webView = wv
        webContainerView.addSubview(wv)
        NSLayoutConstraint.activate([
            wv.leadingAnchor.constraint(equalTo: webContainerView.leadingAnchor),
            wv.trailingAnchor.constraint(equalTo: webContainerView.trailingAnchor),
            wv.topAnchor.constraint(equalTo: webContainerView.topAnchor),
            wv.bottomAnchor.constraint(equalTo: webContainerView.bottomAnchor)
        ])
        webView.navigationDelegate = self
        webView.uiDelegate = self
        installWebViewObservers()
        syncToolbarFromWebView()
        webView.load(URLRequest(url: url, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData))
    }

    private func makeToolbarButton(title: String, symbolName: String, accessibilityDescription: String) -> NSButton {
        let b = NSButton()
        b.translatesAutoresizingMaskIntoConstraints = false
        b.bezelStyle = .texturedRounded
        b.setAccessibilityLabel(accessibilityDescription)
        if #available(macOS 11.0, *), let img = NSImage(systemSymbolName: symbolName, accessibilityDescription: accessibilityDescription) {
            b.image = img
            b.imagePosition = .imageOnly
        } else {
            b.title = title
        }
        b.widthAnchor.constraint(greaterThanOrEqualToConstant: 32).isActive = true
        return b
    }

    private func installWebViewObservers() {
        kvoTokens.append(webView.observe(\.canGoBack, options: [.new]) { [weak self] _, _ in
            self?.syncToolbarFromWebView()
        })
        kvoTokens.append(webView.observe(\.canGoForward, options: [.new]) { [weak self] _, _ in
            self?.syncToolbarFromWebView()
        })
        kvoTokens.append(webView.observe(\.isLoading, options: [.new]) { [weak self] _, _ in
            self?.syncToolbarFromWebView()
        })
        kvoTokens.append(webView.observe(\.estimatedProgress, options: [.new]) { [weak self] _, _ in
            self?.syncProgressFromWebView()
        })
        kvoTokens.append(webView.observe(\.title, options: [.new]) { [weak self] _, _ in
            self?.syncWindowTitle()
        })
        kvoTokens.append(webView.observe(\.url, options: [.new]) { [weak self] _, _ in
            self?.syncAddressFieldFromWebView()
        })
    }

    private func syncToolbarFromWebView() {
        backButton?.isEnabled = webView.canGoBack
        forwardButton?.isEnabled = webView.canGoForward
        if webView.isLoading {
            if #available(macOS 11.0, *), let img = NSImage(systemSymbolName: "xmark", accessibilityDescription: "Stop") {
                reloadStopButton.image = img
                reloadStopButton.imagePosition = .imageOnly
                reloadStopButton.title = ""
            } else {
                reloadStopButton.title = "Stop"
            }
        } else {
            if #available(macOS 11.0, *), let img = NSImage(systemSymbolName: "arrow.clockwise", accessibilityDescription: "Reload") {
                reloadStopButton.image = img
                reloadStopButton.imagePosition = .imageOnly
                reloadStopButton.title = ""
            } else {
                reloadStopButton.title = "Reload"
            }
        }
        syncProgressFromWebView()
    }

    private func syncProgressFromWebView() {
        guard let progressBar else { return }
        if webView.isLoading {
            progressBar.isHidden = false
            progressBar.doubleValue = webView.estimatedProgress
        } else {
            progressBar.isHidden = true
            progressBar.doubleValue = 0
        }
    }

    private func syncAddressFieldFromWebView() {
        guard let urlField, urlField.currentEditor() == nil, let url = webView.url else { return }
        urlField.stringValue = url.absoluteString
    }

    private func syncWindowTitle() {
        let t = webView.title?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
        let host = webView.url?.host ?? ""
        view.window?.title = t.isEmpty ? (host.isEmpty ? "Browser" : host) : t
    }

    func load(url: URL) {
        lastLoadedURL = url
        processTerminateRetryCount = 0
        urlField?.stringValue = url.absoluteString
        webView.load(URLRequest(url: url))
        syncWindowTitle()
    }

    @objc private func goBack() {
        webView.goBack()
    }

    @objc private func goForward() {
        webView.goForward()
    }

    @objc private func reloadOrStop() {
        if webView.isLoading {
            webView.stopLoading()
        } else {
            webView.reload()
        }
    }

    @objc private func addressFieldSubmitted() {
        let raw = urlField?.stringValue.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
        guard raw.isEmpty == false else { return }
        var normalized = raw
        if normalized.lowercased().hasPrefix("http://") == false && normalized.lowercased().hasPrefix("https://") == false {
            normalized = "https://\(normalized)"
        }
        guard let url = URL(string: normalized),
              let scheme = url.scheme?.lowercased(),
              scheme == "http" || scheme == "https",
              url.host != nil
        else {
            let alert = NSAlert()
            alert.messageText = "Invalid address"
            alert.informativeText = "Enter a valid web address, for example https://example.com"
            alert.addButton(withTitle: "OK")
            alert.runModal()
            return
        }
        guard inAppBrowserURLAllowed(url, policy: navigationPolicy) else {
            presentBlockedHostAlert()
            return
        }
        load(url: url)
    }

    private func presentBlockedHostAlert() {
        let alert = NSAlert()
        alert.messageText = "Address not allowed"
        alert.informativeText = "This URL is not permitted with the current in-app browser policy (whitelist)."
        alert.addButton(withTitle: "OK")
        alert.runModal()
    }

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        processTerminateRetryCount = 0
        syncAddressFieldFromWebView()
        syncWindowTitle()
    }

    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        let nsError = error as NSError
        if nsError.code == NSURLErrorCancelled {
            return
        }
        let alert = NSAlert()
        alert.messageText = "Unable to load page"
        alert.informativeText = "Could not load this page in the in-app browser.\n\n\(error.localizedDescription)"
        alert.addButton(withTitle: "Try Again")
        alert.addButton(withTitle: "OK")
        if alert.runModal() == .alertFirstButtonReturn, let url = lastLoadedURL {
            processTerminateRetryCount = 0
            webView.load(URLRequest(url: url))
        }
    }

    func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
        guard let url = lastLoadedURL else { return }

        if processTerminateRetryCount < maxProcessTerminateRetries {
            processTerminateRetryCount += 1
            replaceWebViewAndLoad(url: url)
            return
        }

        let alert = NSAlert()
        alert.messageText = "Page stopped loading"
        alert.informativeText =
            "The in-app browser closed this page unexpectedly. You can try loading it again in this same window."
        alert.addButton(withTitle: "Try Again")
        alert.addButton(withTitle: "OK")
        if alert.runModal() == .alertFirstButtonReturn {
            processTerminateRetryCount = 0
            replaceWebViewAndLoad(url: url)
        }
    }

    func webView(
        _ webView: WKWebView,
        decidePolicyFor navigationAction: WKNavigationAction,
        decisionHandler: @escaping (WKNavigationActionPolicy) -> Void
    ) {
        guard let url = navigationAction.request.url else {
            decisionHandler(.allow)
            return
        }
        let scheme = (url.scheme ?? "").lowercased()
        if scheme == "mailto" || scheme == "tel" {
            decisionHandler(.cancel)
            return
        }
        if inAppBrowserURLAllowed(url, policy: navigationPolicy) == false {
            if navigationAction.targetFrame?.isMainFrame != false {
                DispatchQueue.main.async { [weak self] in
                    self?.presentBlockedHostAlert()
                }
            }
            decisionHandler(.cancel)
            return
        }
        decisionHandler(.allow)
    }

    func webView(
        _ webView: WKWebView,
        createWebViewWith configuration: WKWebViewConfiguration,
        for navigationAction: WKNavigationAction,
        windowFeatures: WKWindowFeatures
    ) -> WKWebView? {
        if navigationAction.targetFrame == nil, let requestURL = navigationAction.request.url {
            if inAppBrowserURLAllowed(requestURL, policy: navigationPolicy) {
                webView.load(URLRequest(url: requestURL))
            } else {
                presentBlockedHostAlert()
            }
        }
        return nil
    }

    func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
        if control === urlField, commandSelector == #selector(NSResponder.insertNewline(_:)) {
            addressFieldSubmitted()
            return true
        }
        return false
    }
}

