import SwiftUI
import SwiftData

struct ChildMenuView: View {
    @Environment(\.modelContext) private var modelContext
    @Binding var path: NavigationPath
    @Binding var isPresented: Bool

    private var store: CourseStore { CourseStore(modelContext: modelContext) }

    private var footprint: String {
        let bytes = CourseLibrary.storageByteCount()
        return ByteCountFormatter.string(fromByteCount: bytes, countStyle: .file)
    }

    var body: some View {
        NavigationStack {
            List {
                Section("课程") {
                    Button {
                        isPresented = false
                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
                            path.append(ChildRoute.download)
                        }
                    } label: {
                        Label("添加课程", systemImage: "square.and.arrow.down")
                    }
                }
                Section("AI") {
                    Button {
                        isPresented = false
                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
                            path.append(ChildRoute.aiPair)
                        }
                    } label: {
                        Label("AI 配置 / 配对", systemImage: "sparkles")
                    }
                    if AiConfigStore.isPaired {
                        LabeledContent("AI 配置", value: AiConfigStore.loadConfig() == nil ? "已配对·待同步" : "已缓存")
                    } else {
                        LabeledContent("AI 配置", value: "未配对")
                    }
                }
                Section("存储") {
                    LabeledContent("本地课程占用", value: footprint)
                    if let url = store.settings().lastPublishBaseURL, !url.isEmpty {
                        LabeledContent("上次电脑地址", value: url)
                    } else {
                        LabeledContent("上次电脑地址", value: "未保存")
                    }
                }
                Section("关于") {
                    LabeledContent("应用", value: "Stellia")
                    LabeledContent("角色", value: "儿童学习端")
                    Text("课程在电脑 StudyDeck 组织，通过局域网下载到本机学习。进度仅保存在 iPad。")
                        .font(.footnote)
                        .foregroundStyle(.secondary)
                }
            }
            .navigationTitle("菜单")
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button("关闭") { isPresented = false }
                }
            }
        }
    }
}
