//
//  kordophone2App.swift
//  kordophone2
//
//  Created by James Magahern on 8/24/25.
//

import SwiftUI

@main
struct KordophoneApp: App
{    
    var body: some Scene {
        WindowGroup {
            SplitView()
        }
        .commands {
            TextEditingCommands()
        }

        WindowGroup(id: .transcriptWindow, for: Display.Conversation.self) { selectedConversation in
            TranscriptWindowView(conversation: selectedConversation)
        }

        Settings {
            PreferencesView()
        }
    }
    
    private func reportError(_ e: Error) {
        // Just printing for now.
        print("Error: \(e.localizedDescription)")
    }
}

struct TranscriptWindowView: View
{
    @State private var transcriptViewModel = TranscriptView.ViewModel()
    @State private var entryViewModel = MessageEntryView.ViewModel()
    private let displayedConversation: Binding<Display.Conversation?>

    public init(conversation: Binding<Display.Conversation?>) {
        self.displayedConversation = conversation
        transcriptViewModel.displayedConversation = conversation.wrappedValue
        observeDisplayedConversationChanges()
    }

    private func observeDisplayedConversationChanges() {
        withObservationTracking {
            _ = displayedConversation.wrappedValue
        } onChange: {
            Task { @MainActor in
                guard let displayedConversation = self.displayedConversation.wrappedValue else { return }
                transcriptViewModel.displayedConversation = displayedConversation

                observeDisplayedConversationChanges()
            }
        }
    }

    var body: some View {
        VStack {
            ConversationView(transcriptModel: $transcriptViewModel, entryModel: $entryViewModel)
                .navigationTitle(displayedConversation.wrappedValue?.displayName ?? "Kordophone")
                .selectedConversation(displayedConversation.wrappedValue)
        }
    }
}

extension String
{
    static let transcriptWindow = "TranscriptWindow"
}
