import SwiftUI
import SwiftData
import UserNotifications

struct TodayView: View {
    @Environment(\.nahbarTheme) var theme
    @Environment(\.modelContext) private var modelContext
    @EnvironmentObject private var profileStore: UserProfileStore
    @Query private var people: [Person]
    // V5: Nachwirkungen sind jetzt Treffen-Momente mit Status "warte_nachwirkung"
    @Query(filter: #Predicate<Moment> {
        $0.statusRaw == "warte_nachwirkung" && $0.typeRaw == "Treffen"
    }, sort: \Moment.createdAt, order: .reverse)
    private var pendingAftermaths: [Moment]
    @State private var selectedMomentForAftermath: Moment? = nil
    @State private var showPersonPicker = false
    @State private var personForNewMoment: Person? = nil
    @State private var showTodoPersonPicker = false
    @State private var personForNewTodo: Person? = nil
    @State private var todoForEdit: Todo? = nil
    @State private var fadingOutTodos: [Todo] = []
    @AppStorage("upcomingDaysAhead") private var daysAhead: Int = 7

    private var needsAttention: [Person] {
        people
            .filter { $0.needsAttention }
            .sorted { ($0.lastMomentDate ?? $0.createdAt) < ($1.lastMomentDate ?? $1.createdAt) }
    }

    private var birthdayPeople: [Person] {
        people.filter { $0.hasBirthdayWithin(days: daysAhead) }
    }

    // V5: Geplante Treffen (Datum in der Zukunft, noch nicht bewertet)
    @Query(filter: #Predicate<Moment> {
        $0.typeRaw == "Treffen" && $0.statusRaw == nil
    }, sort: \Moment.createdAt)
    private var allUnratedMeetings: [Moment]

    private var plannedMeetings: [Moment] {
        let now = Date()
        let horizon = Calendar.current.date(byAdding: .day, value: daysAhead, to: now) ?? now
        return allUnratedMeetings.filter { $0.createdAt > now && $0.createdAt <= horizon }
    }

    // Alle planbaren Momente (Treffen, Gespräch, Vorhaben) mit gesetzter Erinnerung
    @Query(filter: #Predicate<Moment> {
        $0.typeRaw != "Gedanke" && !$0.isCompleted && $0.reminderDate != nil
    }, sort: \Moment.reminderDate)
    private var allWithReminder: [Moment]

    private var upcomingReminders: [Moment] {
        let now = Date()
        let horizon = Calendar.current.date(byAdding: .day, value: daysAhead, to: now) ?? now
        // Momente, die bereits über das Kalenderzeiger in plannedMeetings erscheinen, ausblenden
        let plannedIDs = Set(plannedMeetings.map { $0.id })
        return allWithReminder.filter { m in
            guard let r = m.reminderDate else { return false }
            return r >= now && r <= horizon && !plannedIDs.contains(m.id)
        }
    }

    // V5: Vorhaben ohne Erinnerung (offene Schritte)
    @Query(filter: #Predicate<Moment> {
        $0.typeRaw == "Vorhaben" && !$0.isCompleted && $0.reminderDate == nil
    }, sort: \Moment.createdAt)
    private var openIntentions: [Moment]

    // V7: Fällige Todos (alle offenen, nach Fälligkeitsdatum sortiert)
    @Query(filter: #Predicate<Todo> {
        !$0.isCompleted
    }, sort: \Todo.dueDate)
    private var allOpenTodos: [Todo]

    private var dueTodos: [Todo] {
        let horizon = Calendar.current.date(byAdding: .day, value: daysAhead, to: Date.now) ?? Date.now
        return allOpenTodos.filter { $0.dueDate <= horizon }
    }

    private var isEmpty: Bool {
        needsAttention.isEmpty && birthdayPeople.isEmpty && openIntentions.isEmpty
            && upcomingReminders.isEmpty && pendingAftermaths.isEmpty && plannedMeetings.isEmpty
            && dueTodos.isEmpty && fadingOutTodos.isEmpty
    }

    /// Kombiniert offene Todos mit gerade abgehakten (die noch ausblenden).
    private var visibleTodos: [Todo] {
        let fadingIDs = Set(fadingOutTodos.map(\.id))
        return dueTodos.filter { !fadingIDs.contains($0.id) } + fadingOutTodos
    }

    private var activePeople: [Person] {
        people.filter { !$0.isArchived }.sorted { $0.name < $1.name }
    }

    private var birthdaySectionTitle: LocalizedStringKey {
        switch daysAhead {
        case 3:  return "In 3 Tagen"
        case 7:  return "Diese Woche"
        case 14: return "Nächste 2 Wochen"
        case 30: return "Nächster Monat"
        default: return "Nächste \(daysAhead) Tage"
        }
    }

    private var greeting: String {
        let hour = Calendar.current.component(.hour, from: Date())
        let base: String
        if hour < 12 { base = String(localized: "Guten Morgen") }
        else if hour < 18 { base = String(localized: "Guten Tag") }
        else { base = String(localized: "Guten Abend") }

        let firstName = profileStore.name.split(separator: " ").first.map(String.init) ?? ""
        if firstName.isEmpty { return "\(base)." }
        return "\(base), \(firstName)."
    }

    private var formattedToday: String {
        Date.now.formatted(.dateTime.weekday(.wide).month(.wide).day())
    }

    var body: some View {
        NavigationStack {
            ScrollView {
                VStack(alignment: .leading, spacing: 32) {
                    // Header
                    VStack(alignment: .leading, spacing: 4) {
                        Text(greeting)
                            .font(.system(size: 32, weight: .light, design: theme.displayDesign))
                            .foregroundStyle(theme.contentPrimary)
                        Text(formattedToday)
                            .font(.system(size: 15, design: theme.displayDesign))
                            .foregroundStyle(theme.contentTertiary)
                    }
                    .padding(.horizontal, 20)
                    .padding(.top, 12)

                    if isEmpty {
                        emptyState
                    } else {
                        VStack(spacing: 24) {
                            if !plannedMeetings.isEmpty {
                                TodaySection(title: "Geplante Treffen", icon: "calendar.badge.clock") {
                                    ForEach(plannedMeetings) { moment in
                                        if let person = moment.person {
                                            NavigationLink(destination: PersonDetailView(person: person)) {
                                                TodayRow(person: person, hint: plannedMeetingHint(for: moment))
                                            }
                                            .buttonStyle(.plain)
                                        }
                                        if moment.id != plannedMeetings.last?.id {
                                            RowDivider()
                                        }
                                    }
                                }
                            }

                            if !upcomingReminders.isEmpty {
                                TodaySection(title: "Anstehende Unternehmungen", icon: "calendar") {
                                    ForEach(upcomingReminders) { moment in
                                        if let person = moment.person {
                                            NavigationLink(destination: PersonDetailView(person: person)) {
                                                TodayRow(person: person, hint: reminderHint(for: moment))
                                            }
                                            .buttonStyle(.plain)
                                        }
                                        if moment.id != upcomingReminders.last?.id {
                                            RowDivider()
                                        }
                                    }
                                }
                            }

                            if !openIntentions.isEmpty {
                                TodaySection(title: "Offene Unternehmungen", icon: "arrow.right.circle") {
                                    ForEach(openIntentions) { moment in
                                        if let person = moment.person {
                                            NavigationLink(destination: PersonDetailView(person: person)) {
                                                TodayRow(person: person, hint: moment.text)
                                            }
                                            .buttonStyle(.plain)
                                        }
                                        if moment.id != openIntentions.last?.id {
                                            RowDivider()
                                        }
                                    }
                                }
                            }

                            if !birthdayPeople.isEmpty {
                                TodaySection(title: "Anstehende Geburtstage", icon: "gift") {
                                    ForEach(birthdayPeople) { person in
                                        VStack(spacing: 0) {
                                            NavigationLink(destination: PersonDetailView(person: person)) {
                                                TodayRow(person: person, hint: birthdayHint(for: person))
                                            }
                                            .buttonStyle(.plain)
                                            GiftSuggestionRow(person: person)
                                        }
                                        if person.id != birthdayPeople.last?.id {
                                            RowDivider()
                                        }
                                    }
                                }
                            }

                            if !visibleTodos.isEmpty {
                                TodaySection(title: "Fällige Todos", icon: "checkmark.circle") {
                                    ForEach(visibleTodos) { todo in
                                        TodoTodayRow(
                                            todo: todo,
                                            onComplete: { completeTodo(todo) },
                                            onEdit: { todoForEdit = todo }
                                        )
                                        if todo.id != visibleTodos.last?.id {
                                            RowDivider()
                                        }
                                    }
                                }
                            }

                            if !pendingAftermaths.isEmpty {
                                TodaySection(title: "Nachwirkung fällig", icon: "moon.stars.fill") {
                                    ForEach(pendingAftermaths) { moment in
                                        Button {
                                            selectedMomentForAftermath = moment
                                        } label: {
                                            HStack(spacing: 12) {
                                                if let p = moment.person {
                                                    PersonAvatar(person: p, size: 36)
                                                }
                                                VStack(alignment: .leading, spacing: 2) {
                                                    Text(moment.person?.name ?? "Unbekannt")
                                                        .font(.system(size: 15, weight: .medium))
                                                        .foregroundStyle(theme.contentPrimary)
                                                    Text("Treffen \(moment.createdAt.formatted(date: .abbreviated, time: .omitted))")
                                                        .font(.system(size: 13))
                                                        .foregroundStyle(theme.contentTertiary)
                                                }
                                                Spacer()
                                                Image(systemName: "chevron.right")
                                                    .font(.system(size: 12, weight: .medium))
                                                    .foregroundStyle(theme.contentTertiary)
                                            }
                                            .padding(.horizontal, 16)
                                            .padding(.vertical, 12)
                                        }
                                        .buttonStyle(.plain)
                                        if moment.id != pendingAftermaths.last?.id {
                                            RowDivider()
                                        }
                                    }
                                }
                            }

                            if !needsAttention.isEmpty {
                                TodaySection(title: "Schon eine Weile her", icon: "clock") {
                                    ForEach(needsAttention.prefix(5)) { person in
                                        NavigationLink(destination: PersonDetailView(person: person)) {
                                            TodayRow(person: person, hint: lastSeenHint(for: person))
                                        }
                                        .buttonStyle(.plain)
                                        if person.id != Array(needsAttention.prefix(5)).last?.id {
                                            RowDivider()
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                .padding(.bottom, 40)
            }
            .background(theme.backgroundPrimary.ignoresSafeArea())
            .navigationBarHidden(true)
            .sheet(item: $selectedMomentForAftermath) { moment in
                AftermathRatingFlowView(moment: moment)
            }
            .sheet(item: $todoForEdit) { todo in
                EditTodoView(todo: todo)
            }
            .sheet(isPresented: $showPersonPicker) {
                TodayPersonPickerSheet(people: activePeople) { person in
                    personForNewMoment = person
                }
            }
            .sheet(item: $personForNewMoment) { person in
                AddMomentView(person: person)
            }
            .sheet(isPresented: $showTodoPersonPicker) {
                TodayPersonPickerSheet(people: activePeople) { person in
                    personForNewTodo = person
                }
            }
            .sheet(item: $personForNewTodo) { person in
                AddTodoView(person: person)
            }
        }
    }

    // MARK: - Empty State

    private var emptyState: some View {
        VStack(spacing: 24) {
            Spacer().frame(height: 32)

            VStack(spacing: 6) {
                Text("Ein ruhiger Tag.")
                    .font(.system(size: 20, weight: .light, design: theme.displayDesign))
                    .foregroundStyle(theme.contentPrimary)
                Text("Lass uns mit der Beziehungspflege starten.")
                    .font(.system(size: 15))
                    .foregroundStyle(theme.contentTertiary)
            }

            VStack(spacing: 12) {
                Button {
                    showPersonPicker = true
                } label: {
                    HStack(spacing: 14) {
                        Image(systemName: "plus.circle.fill")
                            .font(.system(size: 22))
                        VStack(alignment: .leading, spacing: 2) {
                            Text("Moment erfassen")
                                .font(.system(size: 15, weight: .semibold, design: theme.displayDesign))
                            Text("Treffen, Gespräch oder Erlebnis")
                                .font(.system(size: 12))
                                .opacity(0.8)
                        }
                        Spacer()
                        Image(systemName: "chevron.right")
                            .font(.system(size: 12, weight: .medium))
                            .opacity(0.6)
                    }
                    .foregroundStyle(theme.backgroundPrimary)
                    .padding(.horizontal, 20)
                    .padding(.vertical, 16)
                    .background(theme.accent)
                    .clipShape(RoundedRectangle(cornerRadius: theme.radiusCard))
                }
                .buttonStyle(.plain)

                Button {
                    showTodoPersonPicker = true
                } label: {
                    HStack(spacing: 14) {
                        Image(systemName: "checkmark.circle")
                            .font(.system(size: 22))
                        VStack(alignment: .leading, spacing: 2) {
                            Text("Todo hinzufügen")
                                .font(.system(size: 15, weight: .semibold, design: theme.displayDesign))
                            Text("Aufgabe für eine Person anlegen")
                                .font(.system(size: 12))
                                .opacity(0.7)
                        }
                        Spacer()
                        Image(systemName: "chevron.right")
                            .font(.system(size: 12, weight: .medium))
                            .opacity(0.5)
                    }
                    .foregroundStyle(theme.accent)
                    .padding(.horizontal, 20)
                    .padding(.vertical, 16)
                    .background(theme.accent.opacity(0.1))
                    .clipShape(RoundedRectangle(cornerRadius: theme.radiusCard))
                    .overlay(
                        RoundedRectangle(cornerRadius: theme.radiusCard)
                            .strokeBorder(theme.accent.opacity(0.25), lineWidth: 1)
                    )
                }
                .buttonStyle(.plain)
            }
            .padding(.horizontal, 20)
        }
        .frame(maxWidth: .infinity)
    }

    // MARK: - Hints

    private func birthdayHint(for person: Person) -> String {
        guard let birthday = person.birthday else { return "" }
        let cal = Calendar.current
        let bdc = cal.dateComponents([.month, .day], from: birthday)
        for offset in 0..<7 {
            if let date = cal.date(byAdding: .day, value: offset, to: Date()) {
                let dc = cal.dateComponents([.month, .day], from: date)
                if dc.month == bdc.month && dc.day == bdc.day {
                    if offset == 0 { return String(localized: "Heute Geburtstag 🎂") }
                    if offset == 1 { return String(localized: "Morgen Geburtstag") }
                    return String.localizedStringWithFormat(String(localized: "In %lld Tagen Geburtstag"), Int64(offset))
                }
            }
        }
        return ""
    }

    private func plannedMeetingHint(for moment: Moment) -> String {
        let dateStr = moment.createdAt.formatted(.dateTime.weekday(.abbreviated).day().month(.abbreviated).hour().minute())
        return moment.text.isEmpty ? dateStr : "\(moment.text) · \(dateStr)"
    }

    private func reminderHint(for moment: Moment) -> String {
        guard let reminder = moment.reminderDate else { return moment.text }
        let dateStr = reminder.formatted(.dateTime.day().month(.abbreviated).hour().minute())
        let label = moment.text.isEmpty ? moment.type.displayName : moment.text
        return "\(label) · \(dateStr)"
    }

    private func completeTodo(_ todo: Todo) {
        // Sofort in die Fade-out-Liste aufnehmen, damit der Eintrag sichtbar bleibt
        fadingOutTodos.append(todo)

        withAnimation(.spring(response: 0.3, dampingFraction: 0.75)) {
            todo.isCompleted = true
            todo.completedAt = Date()
            todo.person?.touch()
        }

        // Ausstehende Push-Erinnerung abbrechen
        UNUserNotificationCenter.current()
            .removePendingNotificationRequests(withIdentifiers: ["todo-\(todo.id)"])

        // Logbuch-Eintrag erstellen
        let entry = LogEntry(type: .todoCompleted, title: todo.title, person: todo.person)
        modelContext.insert(entry)
        todo.person?.logEntries?.append(entry)

        do {
            try modelContext.save()
        } catch {
            AppEventLog.shared.record(
                "Fehler beim Abhaken des Todos: \(error.localizedDescription)",
                level: .error, category: "Todo"
            )
        }

        // Nach 5 Sek. sanft ausblenden
        DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
            withAnimation(.easeOut(duration: 0.35)) {
                fadingOutTodos.removeAll { $0.id == todo.id }
            }
        }
    }

    private func lastSeenHint(for person: Person) -> String {
        guard let last = person.lastMomentDate else { return String(localized: "Noch keine Momente festgehalten") }
        let formatter = RelativeDateTimeFormatter()
        formatter.unitsStyle = .full
        return formatter.localizedString(for: last, relativeTo: Date())
    }
}

// MARK: - Gift Suggestion Row

private enum GiftSuggestionState {
    case idle
    case loading
    case result(String, Date)
    case error(String)
}

struct GiftSuggestionRow: View {
    @Environment(\.nahbarTheme) var theme
    let person: Person

    @StateObject private var store = StoreManager.shared
    @State private var state: GiftSuggestionState = .idle
    @State private var isExpanded = false
    @State private var showPaywall = false
    @State private var showAIConsent = false
    @AppStorage("aiConsentGiven") private var aiConsentGiven = false

    var body: some View {
        VStack(alignment: .leading, spacing: 0) {
            Divider()
                .padding(.horizontal, 16)

            switch state {
            case .idle:
                idleButton
            case .loading:
                loadingView
            case .result(let text, let date):
                if isExpanded {
                    resultView(text: text, date: date)
                } else {
                    collapsedButton
                }
            case .error(let message):
                errorView(message: message)
            }
        }
        .onAppear {
            if let cached = AIAnalysisService.shared.loadCachedGift(for: person) {
                state = .result(cached.text, cached.generatedAt)
            }
        }
        .animation(.easeInOut(duration: 0.2), value: isExpanded)
        .sheet(isPresented: $showPaywall) { PaywallView(targeting: .max) }
        .sheet(isPresented: $showAIConsent) {
            AIConsentSheet {
                aiConsentGiven = true
                Task { await loadGift() }
            }
        }
    }

    private var canUseAI: Bool {
        store.isMax || AIAnalysisService.shared.hasFreeQueriesLeft
    }

    private var idleButton: some View {
        Button {
            guard canUseAI else { showPaywall = true; return }
            if aiConsentGiven {
                Task { await loadGift() }
            } else {
                showAIConsent = true
            }
        } label: {
            HStack(spacing: 8) {
                Image(systemName: "gift")
                    .font(.system(size: 13))
                Text("Geschenkidee vorschlagen")
                    .font(.system(size: 13))
                Spacer()
                if !store.isMax && canUseAI {
                    Text("\(AIAnalysisService.shared.freeQueriesRemaining) gratis")
                        .font(.system(size: 10, weight: .bold))
                        .foregroundStyle(theme.contentTertiary)
                        .padding(.horizontal, 6)
                        .padding(.vertical, 2)
                        .background(theme.backgroundSecondary)
                        .clipShape(Capsule())
                } else {
                    MaxBadge()
                }
            }
            .foregroundStyle(canUseAI ? theme.accent : theme.contentSecondary)
            .padding(.horizontal, 16)
            .padding(.vertical, 10)
        }
        .buttonStyle(.plain)
    }

    private var collapsedButton: some View {
        Button { isExpanded = true } label: {
            HStack(spacing: 8) {
                Image(systemName: "gift")
                    .font(.system(size: 13))
                Text("Geschenkidee anzeigen")
                    .font(.system(size: 13))
                Spacer()
                Image(systemName: "chevron.down")
                    .font(.system(size: 11, weight: .medium))
            }
            .foregroundStyle(theme.accent)
            .padding(.horizontal, 16)
            .padding(.vertical, 10)
        }
        .buttonStyle(.plain)
    }

    private var loadingView: some View {
        HStack(spacing: 8) {
            ProgressView()
                .scaleEffect(0.75)
            Text("Ideen werden generiert…")
                .font(.system(size: 13))
                .foregroundStyle(theme.contentSecondary)
        }
        .padding(.horizontal, 16)
        .padding(.vertical, 10)
    }

    private func resultView(text: String, date: Date) -> some View {
        VStack(alignment: .leading, spacing: 8) {
            HStack {
                Spacer()
                Button { isExpanded = false } label: {
                    Image(systemName: "chevron.up")
                        .font(.system(size: 11, weight: .medium))
                        .foregroundStyle(theme.contentTertiary)
                }
                .buttonStyle(.plain)
            }

            Text(LocalizedStringKey(text))
                .font(.system(size: 13))
                .foregroundStyle(theme.contentPrimary)
                .fixedSize(horizontal: false, vertical: true)

            HStack {
                Text(date, style: .date)
                    .font(.system(size: 11))
                    .foregroundStyle(theme.contentTertiary)
                Spacer()
                Button {
                    Task { await loadGift() }
                } label: {
                    Text("Neu laden")
                        .font(.system(size: 12))
                        .foregroundStyle(theme.accent)
                }
                .buttonStyle(.plain)
                .disabled(AIAnalysisService.shared.isRateLimited)
            }
        }
        .padding(.horizontal, 16)
        .padding(.vertical, 10)
    }

    private func errorView(message: String) -> some View {
        HStack {
            Text("Fehler: \(message)")
                .font(.system(size: 12))
                .foregroundStyle(theme.contentTertiary)
                .lineLimit(1)
            Spacer()
            Button {
                Task { await loadGift() }
            } label: {
                Text("Erneut versuchen")
                    .font(.system(size: 12))
                    .foregroundStyle(theme.accent)
            }
            .buttonStyle(.plain)
        }
        .padding(.horizontal, 16)
        .padding(.vertical, 10)
    }

    @MainActor
    private func loadGift() async {
        state = .loading
        do {
            let suggestion = try await AIAnalysisService.shared.suggestGift(person: person)
            if !store.isMax { AIAnalysisService.shared.consumeFreeQuery() }
            isExpanded = true
            state = .result(suggestion, Date())
        } catch {
            // Falls Cache vorhanden, zeige ihn zurück; sonst Fehler
            if let cached = AIAnalysisService.shared.loadCachedGift(for: person) {
                state = .result(cached.text, cached.generatedAt)
            } else {
                state = .error(error.localizedDescription)
            }
        }
    }
}

// MARK: - Person Picker Sheet (für Quick-Moment-Erfassung)

private struct TodayPersonPickerSheet: View {
    @Environment(\.nahbarTheme) var theme
    @Environment(\.dismiss) var dismiss

    let people: [Person]
    let onSelect: (Person) -> Void

    var body: some View {
        NavigationStack {
            Group {
                if people.isEmpty {
                    VStack(spacing: 12) {
                        Image(systemName: "person.2")
                            .font(.system(size: 40))
                            .foregroundStyle(theme.contentTertiary)
                        Text("Noch keine Kontakte")
                            .font(.system(size: 18, weight: .light, design: theme.displayDesign))
                            .foregroundStyle(theme.contentPrimary)
                        Text("Füge zuerst Personen im Tab \u{201E}Menschen\u{201C} hinzu.")
                            .font(.system(size: 14))
                            .foregroundStyle(theme.contentTertiary)
                            .multilineTextAlignment(.center)
                            .padding(.horizontal, 32)
                    }
                    .frame(maxWidth: .infinity, maxHeight: .infinity)
                } else {
                    ScrollView {
                        VStack(spacing: 0) {
                            ForEach(people) { person in
                                Button {
                                    onSelect(person)
                                    dismiss()
                                } label: {
                                    HStack(spacing: 12) {
                                        PersonAvatar(person: person, size: 40)
                                        VStack(alignment: .leading, spacing: 2) {
                                            Text(person.name)
                                                .font(.system(size: 15, weight: .medium, design: theme.displayDesign))
                                                .foregroundStyle(theme.contentPrimary)
                                            if !person.tag.rawValue.isEmpty {
                                                Text(person.tag.rawValue)
                                                    .font(.system(size: 12))
                                                    .foregroundStyle(theme.contentTertiary)
                                            }
                                        }
                                        Spacer()
                                        Image(systemName: "chevron.right")
                                            .font(.system(size: 11, weight: .medium))
                                            .foregroundStyle(theme.contentTertiary)
                                    }
                                    .padding(.horizontal, 16)
                                    .padding(.vertical, 12)
                                }
                                .buttonStyle(.plain)
                                if person.id != people.last?.id {
                                    RowDivider()
                                }
                            }
                        }
                        .background(theme.surfaceCard)
                        .clipShape(RoundedRectangle(cornerRadius: theme.radiusCard))
                        .padding(.horizontal, 20)
                        .padding(.vertical, 8)
                    }
                    .background(theme.backgroundPrimary.ignoresSafeArea())
                }
            }
            .background(theme.backgroundPrimary.ignoresSafeArea())
            .navigationTitle("Für wen?")
            .navigationBarTitleDisplayMode(.large)
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button("Abbrechen") { dismiss() }
                }
            }
        }
    }
}

// MARK: - Today Section

struct TodaySection<Content: View>: View {
    @Environment(\.nahbarTheme) var theme
    let title: LocalizedStringKey
    let icon: String
    @ViewBuilder let content: Content

    var body: some View {
        VStack(alignment: .leading, spacing: 10) {
            SectionHeader(title: title, icon: icon)
                .padding(.horizontal, 20)

            VStack(spacing: 0) {
                content
            }
            .background(theme.surfaceCard)
            .clipShape(RoundedRectangle(cornerRadius: theme.radiusCard))
            .padding(.horizontal, 20)
        }
    }
}

// MARK: - Today Row

struct TodayRow: View {
    @Environment(\.nahbarTheme) var theme
    let person: Person
    let hint: String

    var body: some View {
        HStack(spacing: 12) {
            PersonAvatar(person: person, size: 40)

            VStack(alignment: .leading, spacing: 2) {
                Text(person.name)
                    .font(.system(size: 15, weight: .medium, design: theme.displayDesign))
                    .foregroundStyle(theme.contentPrimary)
                if !hint.isEmpty {
                    Text(hint)
                        .font(.system(size: 13))
                        .foregroundStyle(theme.contentSecondary)
                }
            }

            Spacer()

            Image(systemName: "chevron.right")
                .font(.system(size: 11, weight: .medium))
                .foregroundStyle(theme.contentTertiary)
        }
        .padding(.horizontal, 16)
        .padding(.vertical, 12)
    }
}

// MARK: - Todo Today Row

private struct TodoTodayRow: View {
    @Environment(\.nahbarTheme) var theme
    let todo: Todo
    let onComplete: () -> Void
    let onEdit: () -> Void

    var body: some View {
        HStack(spacing: 12) {
            Button {
                guard !todo.isCompleted else { return }
                onComplete()
            } label: {
                Image(systemName: todo.isCompleted ? "checkmark.circle.fill" : "circle")
                    .font(.system(size: 20))
                    .foregroundStyle(todo.isCompleted ? Color.green : theme.contentTertiary)
            }
            .buttonStyle(.plain)

            Button { onEdit() } label: {
                VStack(alignment: .leading, spacing: 2) {
                    Text(todo.title)
                        .font(.system(size: 15, weight: .medium, design: theme.displayDesign))
                        .foregroundStyle(todo.isCompleted ? theme.contentTertiary : theme.contentPrimary)
                        .strikethrough(todo.isCompleted, color: theme.contentTertiary)
                    HStack(spacing: 4) {
                        if let person = todo.person {
                            Text(person.name)
                                .font(.system(size: 13))
                                .foregroundStyle(theme.contentSecondary)
                            Text("·")
                                .font(.system(size: 13))
                                .foregroundStyle(theme.contentTertiary)
                        }
                        Text(todo.dueDate.formatted(.dateTime.day().month(.abbreviated).locale(Locale.current)))
                            .font(.system(size: 13))
                            .foregroundStyle(isOverdue ? .red : theme.contentTertiary)
                        if todo.reminderDate != nil {
                            Image(systemName: "bell.fill")
                                .font(.system(size: 10))
                                .foregroundStyle(theme.accent.opacity(0.75))
                        }
                    }
                }
                .frame(maxWidth: .infinity, alignment: .leading)
            }
            .buttonStyle(.plain)

            if let person = todo.person {
                NavigationLink(destination: PersonDetailView(person: person)) {
                    Image(systemName: "chevron.right")
                        .font(.system(size: 11, weight: .medium))
                        .foregroundStyle(theme.contentTertiary)
                }
                .buttonStyle(.plain)
            }
        }
        .padding(.horizontal, 16)
        .padding(.vertical, 12)
        .opacity(todo.isCompleted ? 0.45 : 1.0)
        .animation(.easeOut(duration: 0.2), value: todo.isCompleted)
    }

    private var isOverdue: Bool {
        todo.dueDate < Calendar.current.startOfDay(for: Date())
    }
}
