Branchwell

Glimmer / app · glimmertoday.ai / native / Glimmer / Coach.swift

1import FoundationModels
2import SwiftUI
3
4/// A colored badge for an average aftertaste between -2 and +2.
5struct ScoreBadge: View {
6 let average: Double
7
8 var body: some View {
9 Text(Moment.words[min(4, max(0, Int(average.rounded()) + 2))]).font(.subheadline.monospacedDigit().weight(.bold))
10 .foregroundStyle(average >= 0 ? GlimmerColor.sage : GlimmerColor.ember)
11 .padding(.horizontal, 9).padding(.vertical, 3)
12 .background((average >= 0 ? GlimmerColor.sage : GlimmerColor.ember).opacity(0.13), in: .capsule)
13 .accessibilityLabel("Average \(score(average))")
14 }
15}
16
17struct InsightsView: View {
18 @State private var logging = false
19 @Environment(JournalStore.self) private var store
20 let catalog: Catalog
21
22 var body: some View {
23 let summary = ReflectionSummary(store.journal.moments, day: store.day, days: 14)
24 Page(title: "Insights", subtitle: "Built from the moments you chose to log.", width: 940) {
25 if summary.hasHistory {
26 ViewThatFits(in: .horizontal) {
27 HStack(alignment: .top, spacing: 18) {
28 AftertasteTally(summary: summary).frame(minWidth: 400)
29 mix(summary).frame(minWidth: 220)
30 }
31 VStack(spacing: 16) { AftertasteTally(summary: summary); mix(summary) }
32 }
33 } else {
34 Panel(padding: 20) {
35 GlyphTile("leaf.fill", tint: GlimmerColor.sage, size: 44)
36 Text(summary.moments.isEmpty ? "What stayed with you today?" : summary.moments.count == 1 ? "Your first moment" : "Your week is taking shape")
37 .font(GlimmerFont.reading(.title, weight: .medium))
38 if !summary.moments.isEmpty { Text(summary.takeaway) }
39 Text("Log moments on different days to see what changes.").foregroundStyle(.secondary)
40 Button("Log a moment") { logging = true }.glimmerButton()
41 }
42 }
43 if !summary.moments.isEmpty {
44 Panel(title: "How each activity felt") {
45 ForEach(summary.sources) { group in
46 DisclosureGroup {
47 VStack(alignment: .leading, spacing: 6) {
48 ForEach(ReflectionSummary.tagGroups(group.moments)) { tag in
49 HStack { Text(tag.name); Spacer(); ScoreBadge(average: tag.average) }.font(.callout)
50 }
51 if let active = store.journal.experiment, active.suggestion.title.localizedCaseInsensitiveContains(group.name) {
52 Label("Now trying: \(active.suggestion.title)", systemImage: "flask")
53 .font(.callout).foregroundStyle(.secondary)
54 }
55 }
56 .padding(.top, 6)
57 } label: {
58 HStack(spacing: 12) {
59 let kind = group.moments.first?.kind
60 GlyphTile(Glyph.symbol(name: group.name, category: kind), tint: Glyph.tint(for: kind))
61 VStack(alignment: .leading, spacing: 2) {
62 Text(Glyph.plainName(group.name)).font(.headline)
63 Text(([String("\(group.count) logged")] + group.commonTags).joined(separator: " · "))
64 .font(.caption).foregroundStyle(.secondary)
65 }
66 Spacer()
67 ScoreBadge(average: group.average)
68 }
69 }
70 if group.id != summary.sources.last?.id { Divider() }
71 }
72 }
73 Panel(title: "Today’s logs", accent: GlimmerColor.ember) {
74 ForEach(summary.moments.filter { $0.day == store.todayKey }) { moment in
75 HStack(alignment: .top, spacing: 12) {
76 GlyphTile(Glyph.symbol(name: moment.source, category: moment.kind), tint: Glyph.tint(for: moment.kind))
77 VStack(alignment: .leading, spacing: 3) {
78 Text(Glyph.plainName(moment.source)).font(.headline)
79 Text(([moment.date.formatted(date: .omitted, time: .shortened)] + moment.tags).joined(separator: " · ")).font(.caption).foregroundStyle(.secondary)
80 }
81 Spacer()
82 Text(moment.word).font(.subheadline.weight(.semibold))
83 }
84 .accessibilityElement(children: .combine)
85 }
86 if store.todayLogs.isEmpty { Text("Nothing logged today yet.").foregroundStyle(.secondary) }
87 }
88 }
89 }
90 .sheet(isPresented: $logging) { MomentFlow(catalog: catalog).tallSheet() }
91 }
92
93 private func mix(_ summary: ReflectionSummary) -> some View {
94 Panel(title: "Mix of inputs", accent: GlimmerColor.honey) {
95 let total = Double(max(1, summary.moments.count))
96 ForEach(summary.kinds.sorted { $0.count > $1.count }) { group in
97 VStack(alignment: .leading, spacing: 5) {
98 HStack {
99 Text(group.name).font(.callout.weight(.medium))
100 Spacer()
101 Text("\(group.count) of \(summary.moments.count)").font(.caption.monospacedDigit()).foregroundStyle(.secondary)
102 }
103 Meter(value: Double(group.count) / total, tint: GlimmerColor.honey)
104 }
105 .accessibilityElement(children: .combine)
106 }
107 }
108 }
109}
110
111private struct AftertasteTally: View {
112 let summary: ReflectionSummary
113
114 var body: some View {
115 let better = summary.moments.filter { $0.score > 0 }
116 let neutral = summary.moments.filter { $0.score == 0 }
117 let worse = summary.moments.filter { $0.score < 0 }
118 Panel(title: "How your moments felt", accent: GlimmerColor.accent) {
119 Text(headline(better: better.count, neutral: neutral.count, worse: worse.count))
120 .font(GlimmerFont.reading(.title2, weight: .medium))
121 VStack(spacing: 12) {
122 row("Felt better", moments: better, tint: GlimmerColor.sage)
123 row("Felt the same", moments: neutral, tint: .secondary)
124 row("Felt worse", moments: worse, tint: GlimmerColor.ember)
125 }
126 .padding(.vertical, 4)
127
128 if !better.isEmpty || !worse.isEmpty {
129 Label("Each block is one moment. Outlined blocks show milder feelings.", systemImage: "square")
130 .font(.caption).foregroundStyle(.secondary)
131 .fixedSize(horizontal: false, vertical: true)
132 }
133 if let lift = summary.best.first(where: { $0.count >= 3 }),
134 let drain = summary.rough.first(where: { $0.count >= 3 }) {
135 Divider()
136 Text("\(lift.name) felt better \(lift.moments.filter { $0.score > 0 }.count) of \(lift.count) times. \(drain.name) felt worse \(drain.moments.filter { $0.score < 0 }.count) of \(drain.count) times.")
137 .font(.callout)
138 }
139 Text("\(summary.moments.count) moments across \(summary.daily.count) of the last \(summary.days) days")
140 .font(.caption).foregroundStyle(.secondary)
141 }
142 .accessibilityIdentifier("insights.aftertasteTally")
143 }
144
145 private func headline(better: Int, neutral: Int, worse: Int) -> String {
146 let half = summary.moments.count / 2
147 if better > half { return "Most moments left you feeling better." }
148 if neutral > half { return "Most moments left you feeling the same." }
149 if worse > half { return "Most moments left you feeling worse." }
150 if better > worse + 1 { return "More moments lifted you than drained you." }
151 if worse > better + 1 { return "More moments drained you than lifted you." }
152 return "Your moments felt mixed."
153 }
154
155 private func row(_ title: String, moments: [Moment], tint: Color) -> some View {
156 let strong = moments.filter { abs($0.score) == 2 }.count
157 let neutral = moments.first?.score == 0
158 return VStack(alignment: .leading, spacing: 5) {
159 HStack {
160 Text(title).font(.callout.weight(.semibold))
161 Spacer()
162 Text(moments.count.formatted()).font(.callout.monospacedDigit()).foregroundStyle(.secondary)
163 }
164 if moments.isEmpty {
165 Capsule().fill(.quaternary).frame(width: 24, height: 2)
166 .frame(height: 12)
167 .accessibilityHidden(true)
168 } else {
169 FlowLayout(spacing: 3) {
170 ForEach(0..<moments.count, id: \.self) { index in
171 let block = RoundedRectangle(cornerRadius: 2)
172 Group {
173 if index < strong || neutral {
174 block.fill(tint).frame(height: neutral ? 6 : 12)
175 } else {
176 block.strokeBorder(tint, lineWidth: 1.5)
177 }
178 }
179 .frame(width: 14, height: 12)
180 }
181 }
182 .modifier(ChartReveal())
183 .accessibilityHidden(true)
184 }
185 }
186 .accessibilityElement(children: .ignore)
187 .accessibilityLabel(title)
188 .accessibilityValue(strong == 0 ? "\(moments.count)" : "\(moments.count), \(strong) strongly")
189 }
190}
191
192struct WeeklyView: View {
193 @State private var logging = false
194 @Environment(JournalStore.self) private var store
195 let catalog: Catalog
196
197 var body: some View {
198 let summary = ReflectionSummary(store.journal.moments, day: store.day, days: 7)
199 Page(title: "Your week in moments", kicker: "Last seven days", width: 900) {
200 if summary.moments.isEmpty {
201 Panel(padding: 24) {
202 GlyphTile("leaf.fill", tint: GlimmerColor.sage, size: 48)
203 Text("What’s one moment you remember this week?").font(GlimmerFont.reading(.title))
204 Text("A walk, a conversation, a few minutes to yourself. Write down how it felt.")
205 Button("Log a moment") { logging = true }.glimmerButton(.prominent)
206 }
207 } else {
208 if !summary.best.isEmpty { group("What felt lighter", summary.best, empty: "", tint: GlimmerColor.sage) }
209 if !summary.rough.isEmpty { group("What took energy", summary.rough, empty: "", tint: GlimmerColor.ember) }
210 }
211 LinkRow(title: "Compare with Apple Screen Time", detail: "Estimate one app’s weekly total, then check the same device.", icon: "hourglass", tint: GlimmerColor.dusk) { ScreenTimeCheck() }
212 .accessibilityIdentifier("weekly.screenTime")
213 if !summary.moments.isEmpty {
214 Panel(title: "Your week", accent: GlimmerColor.dusk) {
215 Text(summary.takeaway).font(GlimmerFont.display(.title3)).fixedSize(horizontal: false, vertical: true)
216 LocalCoachReflection(summary: summary, tone: store.journal.answers["coach_style"]?.first)
217 }
218 }
219 DisclosureGroup("Explore an experiment") {
220 VStack(spacing: 8) {
221 ForEach(summary.suggestions(catalog: catalog, answers: store.journal.answers, level: store.journal.guidanceLevel(asOf: store.day))) { suggestion in
222 ActionRow(title: suggestion.title, detail: suggestion.sub, icon: "flask", tint: GlimmerColor.ember,
223 trailing: "plus.circle") { store.startOrQueue(suggestion) }
224 }
225 }
226 .glassGroup(spacing: 8)
227 }
228 let alternatives = summary.best.filter { $0.moments.contains { ["Activity", "People"].contains($0.kind) } }
229 if !alternatives.isEmpty {
230 group("Real-world inputs that worked", alternatives, empty: "", tint: GlimmerColor.sage)
231 }
232 }
233 .sheet(isPresented: $logging) { MomentFlow(catalog: catalog).tallSheet() }
234 }
235
236 private func group(_ title: String, _ groups: [ReflectionSummary.Group], empty: String, tint: Color) -> some View {
237 Panel(title: title, accent: tint) {
238 if groups.isEmpty { Text(empty).foregroundStyle(.secondary) }
239 ForEach(Array(groups.prefix(3))) { group in
240 HStack {
241 VStack(alignment: .leading, spacing: 2) {
242 Text(group.name).font(.headline)
243 Text("\(group.count) logged").font(.caption).foregroundStyle(.secondary)
244 }
245 Spacer()
246 ScoreBadge(average: group.average)
247 }
248 .accessibilityElement(children: .combine)
249 }
250 }
251 .frame(maxHeight: .infinity, alignment: .top)
252 }
253}
254
255struct CoachLibrary: View {
256 @Environment(JournalStore.self) private var store
257 @Environment(\.accessibilityReduceMotion) private var reduceMotion
258 let catalog: Catalog
259 @State private var proposing = false
260 @State private var watching = false
261 @State private var practiceExpanded = false
262
263 var body: some View {
264 let summary = ReflectionSummary(store.journal.moments, day: store.day, days: 14)
265 Page(title: "Coach", width: 680) {
266 DailyReflectionPanel(catalog: catalog)
267 practiceDisclosure
268 if let experiment = store.journal.experiment { experimentPanel(experiment) }
269 DisclosureGroup("About this guidance") {
270 VStack(alignment: .leading, spacing: 6) {
271 Text(CoachingSource.credit).font(.headline)
272 Text(CoachingSource.note).fixedSize(horizontal: false, vertical: true)
273 Link("Explore Glimmer’s coaching sources", destination: CoachingSource.sourcesURL)
274 }
275 .frame(maxWidth: .infinity, alignment: .leading)
276 .padding(.vertical, 6)
277 }
278 .accessibilityIdentifier("coach.author")
279 Panel(title: "What I’m noticing", accent: GlimmerColor.ember, padding: 20) {
280 HStack(alignment: .top, spacing: 14) {
281 Text(summary.takeaway).font(GlimmerFont.display(.title3)).fixedSize(horizontal: false, vertical: true)
282 }
283 LocalCoachReflection(summary: summary, tone: store.journal.answers["coach_style"]?.first)
284 if !proposing {
285 ViewThatFits(in: .horizontal) {
286 HStack(spacing: 8) { coachActions }
287 .fixedSize(horizontal: true, vertical: false)
288 VStack(alignment: .leading, spacing: 8) { coachActions }
289 }
290 .glassGroup(spacing: 8)
291 }
292 }
293 if !store.journal.queued.isEmpty || proposing {
294 Panel(title: "Small experiments", accent: GlimmerColor.ember, plain: true) {
295 let choices = store.journal.queued + (proposing ? summary.suggestions(catalog: catalog, answers: store.journal.answers, level: store.journal.guidanceLevel(asOf: store.day)) : [])
296 let unique = choices.reduce(into: [Suggestion]()) { if !$0.map(\.id).contains($1.id) { $0.append($1) } }
297 VStack(spacing: 8) {
298 ForEach(unique) { suggestion in
299 ActionRow(title: suggestion.title, detail: suggestion.sub, icon: "flask", tint: GlimmerColor.ember,
300 trailing: "plus.circle") { store.startOrQueue(suggestion) }
301 }
302 }
303 .glassGroup(spacing: 8)
304 }
305 }
306 Panel(title: "Keep it small", accent: GlimmerColor.honey, plain: true) {
307 VStack(spacing: 8) {
308 if let tiny = catalog.nextChallenge(for: store.journal, level: store.journal.guidanceLevel(asOf: store.day)) {
309 LinkRow(title: tiny.title, detail: "\(JourneyStage.name(tiny.stage)) · \(tiny.mins) min", icon: "sparkles",
310 tint: GlimmerColor.honey) { ChallengeView(challenge: tiny) }
311 }
312 LinkRow(title: "All challenges", icon: "square.grid.2x2", tint: GlimmerColor.honey) { ChallengesView(catalog: catalog) }
313 LinkRow(title: "Open habits", icon: "leaf", tint: GlimmerColor.sage) { HabitsView(catalog: catalog) }
314 }
315 .glassGroup(spacing: 8)
316 }
317 }
318 }
319
320 private var practiceDisclosure: some View {
321 VStack(alignment: .leading, spacing: 10) {
322 Button {
323 practiceExpanded.toggle()
324 } label: {
325 HStack {
326 Text("More ways to practice").font(.headline)
327 Spacer(minLength: 8)
328 Image(systemName: "chevron.right")
329 .font(.caption.weight(.semibold))
330 .foregroundStyle(.secondary)
331 .rotationEffect(.degrees(practiceExpanded ? 90 : 0))
332 .animation(reduceMotion ? nil : .smooth(duration: 0.20), value: practiceExpanded)
333 .accessibilityHidden(true)
334 }
335 .frame(minHeight: 44)
336 .contentShape(.rect)
337 }
338 .buttonStyle(.plain)
339 .accessibilityIdentifier("coach.practiceDisclosure")
340 .accessibilityValue(practiceExpanded ? "Expanded" : "Collapsed")
341
342 ReadingDisclosure(expanded: practiceExpanded) { visible in
343 VStack(alignment: .leading, spacing: 10) { practiceOptions(visible: visible) }
344 }
345 }
346 }
347
348 @ViewBuilder private func practiceOptions(visible: Bool) -> some View {
349 if let attention = catalog.practiceTopics.first(where: { $0.id == "protect_attention" }),
350 let signal = attention.exercises.first(where: { $0.id == "try-an-80-20-day" }) {
351 LinkRow(title: signal.title, detail: "Make time for what matters today.", icon: "clock", tint: GlimmerColor.sage) {
352 Page(title: signal.title, kicker: attention.title, width: 680) {
353 Panel {
354 Text(signal.sub).fixedSize(horizontal: false, vertical: true)
355 SavePracticeButton(practice: signal)
356 }
357 }
358 }
359 .accessibilityIdentifier("coach.signal")
360 .modifier(DisclosureRowMotion(index: 0, count: 4, visible: visible))
361 }
362 if let daily = catalog.dailyPractice(on: store.day, level: store.journal.guidanceLevel(asOf: store.day)) {
363 Panel(title: "Daily Glimmer", accent: GlimmerColor.sage) {
364 Text(daily.practice.title).font(GlimmerFont.display(.title3, weight: .bold))
365 Text(daily.practice.sub).fixedSize(horizontal: false, vertical: true)
366 SavePracticeButton(practice: daily.practice)
367 if let lesson = catalog.dailyLesson(for: store.journal, on: store.day) {
368 LinkRow(title: lesson.title, detail: "Today’s lesson", icon: "book", tint: GlimmerColor.sage) { LessonReader(lesson: lesson) }
369 }
370 }
371 .modifier(DisclosureRowMotion(index: 1, count: 4, visible: visible))
372 }
373 LinkRow(title: "Practice exercises", detail: "Short exercises for work, hands-on learning, and real rest.", icon: "figure.walk.motion", tint: GlimmerColor.sage) {
374 PracticeView(topics: catalog.practiceTopics)
375 }
376 .accessibilityIdentifier("coach.practice")
377 .modifier(DisclosureRowMotion(index: 2, count: 4, visible: visible))
378 if let community = catalog.practiceTopics.first(where: { $0.id == "community_service" }) {
379 LinkRow(title: community.title, detail: "Offer time or a skill to a school, library, or neighbor.", icon: "person.2", tint: GlimmerColor.sage) {
380 PracticeView(topics: [community], title: community.title)
381 }
382 .accessibilityIdentifier("coach.community")
383 .modifier(DisclosureRowMotion(index: 3, count: 4, visible: visible))
384 }
385 }
386
387 @ViewBuilder private var coachActions: some View {
388 coachAction("Design it together", icon: "flask") {
389 proposing = true
390 watching = false
391 }
392 if !watching {
393 coachAction("Keep watching", icon: "eye") {
394 watching = true
395 store.notice = "Okay. Keep noticing for now."
396 }
397 }
398 }
399
400 private func coachAction(_ title: String, icon: String, action: @escaping () -> Void) -> some View {
401 Button(action: action) {
402 Label(title, systemImage: icon)
403 }
404 .glimmerButton()
405 .controlSize(.regular)
406 }
407
408 private func experimentPanel(_ experiment: Experiment) -> some View {
409 Panel(title: "Experiment · \(experiment.checkins.count) of 7 check-ins", accent: GlimmerColor.ember, padding: 20) {
410 Text(experiment.suggestion.title).font(GlimmerFont.display(.title2, weight: .bold))
411 .fixedSize(horizontal: false, vertical: true)
412 HStack(spacing: 5) {
413 let held = experiment.checkins.values.filter { $0 == .held }.count
414 ForEach(0..<7, id: \.self) { index in
415 Capsule().fill(index < experiment.checkins.count
416 ? (index < held ? GlimmerColor.sage : GlimmerColor.honey)
417 : Color.primary.opacity(0.10))
418 .frame(height: 8)
419 }
420 }
421 .accessibilityElement()
422 .accessibilityLabel("\(experiment.checkins.count) of 7 check-ins")
423 if experiment.readyToReview {
424 LinkRow(title: "Start the review", detail: "Decide whether to keep, adjust or drop it",
425 icon: "text.badge.checkmark", tint: GlimmerColor.ember) { ExperimentReview(experiment: experiment) }
426 } else if let result = experiment.checkins[store.todayKey] {
427 Label(result == .held ? "Nice. That’s another check-in." : "Noticing the slip is useful. Thanks for checking in.",
428 systemImage: result == .held ? "checkmark.circle" : "leaf")
429 .foregroundStyle(.secondary)
430 } else {
431 Text("How did it go today?").font(.headline)
432 HStack(spacing: 10) {
433 ForEach(Experiment.Outcome.allCases) { outcome in
434 Button(outcome.rawValue, systemImage: outcome == .held ? "checkmark" : "arrow.uturn.backward") {
435 store.change { $0.checkIn(outcome, on: store.day) }
436 }
437 .glimmerButton(.standard)
438 .buttonBorderShape(.capsule).controlSize(.large)
439 }
440 }
441 .glassGroup(spacing: 10)
442 }
443 }
444 }
445}
446
447struct DailyReflectionPanel: View {
448 @Environment(JournalStore.self) private var store
449 let catalog: Catalog
450
451 var body: some View {
452 if let topic = catalog.reflectionTopic, let practice = catalog.dailyReflection(on: store.day, level: store.journal.guidanceLevel(asOf: store.day)) {
453 Panel(padding: 22) {
454 HStack(spacing: 10) {
455 GlimmerLogo(size: 36)
456 Eyebrow("Today’s reflection")
457 }.readingArrival()
458 Text(practice.title).font(GlimmerFont.reading(.title, weight: .medium))
459 Text(practice.sub).fixedSize(horizontal: false, vertical: true)
460 SavePracticeButton(practice: practice)
461 NavigationLink("Explore all reflections") {
462 PracticeView(topics: [topic], title: topic.title)
463 }
464 .glimmerButton()
465 .accessibilityIdentifier("coach.reflections")
466 }
467 }
468 }
469}
470
471struct SavePracticeButton: View {
472 @Environment(JournalStore.self) private var store
473 let practice: Practice
474 var showSavedStatus = false
475
476 var body: some View {
477 let task = practice.task(on: store.day)
478 let saved = store.journal.tasks.contains { $0.id == task.id }
479 if saved && showSavedStatus {
480 Label("Saved to today’s plan", systemImage: "checkmark.circle")
481 .font(.callout.weight(.medium))
482 .accessibilityIdentifier("coach.practiceSaved")
483 } else {
484 Button(saved ? "Saved to today’s plan" : "Add to today’s plan") {
485 store.change { journal in
486 if !journal.tasks.contains(where: { $0.id == task.id }) { journal.tasks.append(task) }
487 }
488 }
489 .glimmerButton(.prominent)
490 .disabled(saved)
491 .completionLight(saved, outline: Capsule())
492 .accessibilityIdentifier("coach.save." + practice.id)
493 }
494 }
495}
496
497struct PracticeView: View {
498 @Environment(JournalStore.self) private var store
499 let topics: [PracticeTopic]
500 var title = "Practice exercises"
501
502 var body: some View {
503 let level = store.journal.journeyLevel(asOf: store.day)
504 Page(title: title, subtitle: topics.count == 1 ? nil : "Short exercises for work, learning, reflection, and rest. Deeper ones open as your practice grows.", width: 820) {
505 ForEach(topics) { topic in
506 Panel(title: topics.count == 1 ? nil : topic.title, accent: GlimmerColor.sage, plain: true) {
507 VStack(spacing: 8) {
508 ForEach(topic.exercises.sorted { $0.stage < $1.stage }) { exercise in
509 exerciseRow(exercise, ahead: exercise.stage > level).accessibilityIdentifier("practice." + exercise.id)
510 }
511 }
512 .glassGroup(spacing: 8)
513 }
514 }
515 }
516 }
517
518 private func exerciseRow(_ practice: Practice, ahead: Bool) -> some View {
519 let exercise = practice.suggestion
520 let active = store.journal.experiment?.suggestion.id == exercise.id
521 let hasExperiment = store.journal.experiment != nil
522 let queued = hasExperiment && store.journal.queued.contains { $0.id == exercise.id }
523 let state: String
524 if active { state = "In progress" }
525 else if queued { state = "Queued" }
526 else { state = hasExperiment ? "Queue experiment" : "Start experiment" }
527 let note = ahead ? JourneyStage.aheadNote(practice.stage) + "\n" : practice.stage > 1 ? JourneyStage.name(practice.stage) + "\n" : ""
528 return ActionRow(title: exercise.title, detail: "\(exercise.sub)\n\(note)\(state)", icon: ahead ? "leaf" : "flask",
529 tint: GlimmerColor.sage, trailing: active || queued ? "checkmark.circle" : "plus.circle") {
530 store.startOrQueue(exercise)
531 }
532 .disabled(active || queued)
533 }
534}
535
536struct ScreenTimeCheck: View {
537 var body: some View {
538 Page(title: "Check one app", subtitle: "Pick one app on this device and estimate how much time you spent in it over the past week. Then check your own device settings to see how close your guess was.", width: 680) {
539 Panel(title: "Find your weekly total") {
540 #if os(macOS)
541 Text("Open Apple menu → System Settings → Screen Time → Daily Average → Week. On older macOS versions, open App & Website Activity instead and choose a week using the date menu.")
542 Link("Apple’s Screen Time guide for Mac ↗", destination: URL(string: "https://support.apple.com/guide/mac-help/get-started-with-screen-time-mchlfafa9773/mac")!)
543 #else
544 Text("Open Settings → Screen Time → Daily Average → Week. On older iOS versions, tap See All App & Website Activity, then tap Week.")
545 if UIDevice.current.userInterfaceIdiom == .pad {
546 Link("Apple’s Screen Time guide for iPad ↗", destination: URL(string: "https://support.apple.com/guide/ipad/set-up-screen-time-for-yourself-ipad88efc1ad/ipados")!)
547 } else {
548 Link("Apple’s Screen Time guide for iPhone ↗", destination: URL(string: "https://support.apple.com/guide/iphone/set-up-screen-time-for-yourself-iphbfa595995/ios")!)
549 }
550 #endif
551 Text("Glimmer never reads your Screen Time data. If reporting is off, select Turn On App & Website Activity in Screen Time and return once a week of activity is available.").font(.callout).foregroundStyle(.secondary)
552 }
553 Panel(title: "Try it for a week", accent: GlimmerColor.sage) {
554 Text("Try one small change this week, like moving that app off your home screen or signing out after each visit. Check the total again next week and notice how your days felt.")
555 }
556 }
557 }
558}
559
560struct ExperimentReview: View {
561 @Environment(JournalStore.self) private var store
562 @Environment(\.dismiss) private var dismiss
563 let experiment: Experiment
564
565 var body: some View {
566 let held = experiment.checkins.values.filter { $0 == .held }.count
567 Page(title: "Review your experiment", subtitle: experiment.suggestion.title, width: 640) {
568 Panel(title: "Seven check-ins", accent: GlimmerColor.ember, padding: 20) {
569 HStack(spacing: 16) {
570 Stat(value: "\(held)", label: "Held", tint: GlimmerColor.sage)
571 Stat(value: "\(experiment.checkins.count - held)", label: "Slipped", tint: GlimmerColor.honey)
572 }
573 Divider()
574 ForEach(experiment.checkins.keys.sorted(), id: \.self) { day in
575 LabeledContent(day, value: experiment.checkins[day]?.rawValue ?? "").font(.callout)
576 }
577 }
578 Panel(title: "What now?", accent: GlimmerColor.ember, plain: true) {
579 VStack(spacing: 8) {
580 ForEach(Experiment.Review.allCases) { choice in
581 ActionRow(title: choice.rawValue, detail: detail(choice), icon: icon(choice), tint: GlimmerColor.ember) {
582 if store.change({ $0.reviewExperiment(choice, on: store.day) }) { dismiss() }
583 }
584 }
585 }
586 .glassGroup(spacing: 8)
587 }
588 }
589 }
590
591 private func detail(_ review: Experiment.Review) -> String {
592 switch review {
593 case .keep: "Keep it as a practice in Challenges."
594 case .adjust: "Try a smaller version for another week."
595 case .drop: "Make room for something else."
596 }
597 }
598
599 private func icon(_ review: Experiment.Review) -> String {
600 switch review {
601 case .keep: "checkmark.seal"
602 case .adjust: "slider.horizontal.3"
603 case .drop: "arrow.uturn.backward"
604 }
605 }
606}
607
608struct LocalCoachReflection: View {
609 let summary: ReflectionSummary
610 let tone: String?
611 @State private var reflection: String?
612 @State private var loading = false
613
614 var body: some View {
615 if #available(iOS 26, macOS 26, *), SystemLanguageModel.default.isAvailable, summary.moments.count >= 3 {
616 VStack(alignment: .leading, spacing: 10) {
617 Button {
618 Task { await generate() }
619 } label: {
620 HStack(spacing: 8) {
621 if loading { ReflectionOrbit() } else { Image(systemName: "apple.intelligence") }
622 Text(loading ? "Reflecting…" : "Ask for an on-device reflection")
623 }
624 }
625 .glimmerButton(.standard, tint: GlimmerColor.dusk).buttonBorderShape(.capsule)
626 .disabled(loading)
627 if let reflection {
628 Text(reflection).font(.callout).padding(14).frame(maxWidth: .infinity, alignment: .leading)
629 .background(GlimmerColor.dusk.opacity(0.10), in: .rect(cornerRadius: 14))
630 }
631 Label("Runs on this device. Only rating counts and averages are used.", systemImage: "lock")
632 .font(.caption).foregroundStyle(.secondary)
633 }
634 }
635 }
636
637 @available(iOS 26, macOS 26, *)
638 private func generate() async {
639 loading = true
640 defer { loading = false }
641 let facts = summary.sources.prefix(5).enumerated().map { index, group in
642 // Only computed statistics go to the model. Source names can contain arbitrary text.
643 "Input \(index + 1): \(group.count) moments, average \(score(group.average)) on a -2 to +2 scale"
644 }.joined(separator: "; ")
645 let allowedTones = ["gentle", "direct", "curious", "data", "funny", "minimal", "mix"]
646 let style = tone.flatMap { allowedTones.contains($0) ? $0 : nil } ?? "gentle"
647 let session = LanguageModelSession(instructions: """
648 You are a practical life coach. Offer one small, reversible reflection or question in two short
649 sentences, in a \(style) tone. The person chose what to log. Use only the supplied statistics
650 and never name the numbered inputs or guess what happened. Invite the person to consider a
651 specific change at work, a small learning project, making something, or deliberate rest when
652 relevant. Avoid medical advice and promises. Leisure can be worthwhile in its own right.
653 """)
654 do {
655 reflection = try await session.respond(to: "Recent private journal statistics: \(facts)").content
656 } catch {
657 reflection = "An on-device reflection isn’t available right now. The patterns above are still based on your logs."
658 }
659 }
660}
661
662private func score(_ number: Double) -> String { number.formatted(.number.precision(.fractionLength(1)).sign(strategy: .always())) }