import SwiftUI
import NucleicCore

/// A glanceable "what just happened" card floated in the corner of a conversation,
/// for quickly re-orienting when bouncing between sessions. The text is produced by
/// the selected Apple Foundation Models model (or the local heuristic when off).
struct ConversationSummaryCard: View {
    let text: String
    let summarizing: Bool
    /// The session's agent finished its task — the card becomes a "Done" recap.
    var completed: Bool = false
    /// The agent is mid-turn — the card collapses to a fixed "Working…" pill with a
    /// spinner and no body. The expand/collapse and regenerate controls are hidden;
    /// `text` is ignored in this mode.
    var working: Bool = false
    @Binding var isExpanded: Bool
    let onRefresh: () -> Void
    @Environment(\.appPalette) private var palette

    var body: some View {
        VStack(alignment: .leading, spacing: 6) {
            Button {
                withAnimation(.easeInOut(duration: 0.15)) { isExpanded.toggle() }
            } label: {
                HStack(spacing: 5) {
                    Image(systemName: working ? "gearshape" : (completed ? "checkmark.circle.fill" : "sparkles"))
                        .foregroundStyle(working ? palette.accent : (completed ? palette.success : palette.accent))
                    Text(working ? "Working…" : (completed ? "Done" : "Summary")).font(.title3.bold())
                    if working || summarizing { ProgressView().controlSize(.small) }
                    Spacer()
                    // While working the card is a fixed "Working…" pill — no recap body to
                    // reveal — so the regenerate and expand/collapse affordances are hidden.
                    if !working {
                        if isExpanded {
                            Button(action: onRefresh) {
                                Image(systemName: "arrow.clockwise").font(.caption2)
                            }
                            .buttonStyle(.plain).help("Regenerate summary")
                        }
                        Image(systemName: isExpanded ? "chevron.up" : "chevron.down")
                            .font(.caption2).foregroundStyle(.secondary)
                    }
                }
                .contentShape(Rectangle())
            }
            .buttonStyle(.plain)
            .disabled(working)

            if isExpanded && !working {
                Group {
                    if summarizing && text.isEmpty {
                        Text("Summarizing…").font(.callout).foregroundStyle(.secondary)
                    } else if text.isEmpty {
                        Text("No summary yet.").font(.callout).foregroundStyle(.secondary)
                    } else {
                        // A finished session collapses to a flat recap: merged Done/Just-now
                        // bullets, no "Next", no section headings (the "Done" header above
                        // stands in for them).
                        MarkdownText(markdown: completed ? HeuristicSummary.completedRecap(text) : text)
                            .font(.callout)
                            .foregroundStyle(.secondary)
                            .fixedSize(horizontal: false, vertical: true)
                    }
                }
                // Pin the body to the expanded inner width (240 frame − 2×10 padding) so
                // it lays out once and doesn't reflow as the card animates wider — the
                // card edge wipes across stable text instead of text rewrapping mid-grow.
                .frame(width: 220, alignment: .leading)
                // A little breathing room below the body so the text doesn't crowd the
                // card's bottom edge.
                .padding(.bottom, 6)
                .transition(.identity)
            }
        }
        .padding(10)
        .frame(width: (isExpanded && !working) ? 240 : 150, alignment: .leading)
        .background(.regularMaterial, in: .rect(cornerRadius: 10))
        .overlay(RoundedRectangle(cornerRadius: 10).stroke(.quaternary, lineWidth: 1))
        // Use the card itself as a mask: clip the body to the rounded rect so the text
        // is revealed *by* the growing card and can never paint outside it. Geometry
        // and reveal stay in lockstep by construction — no opacity timing to drift.
        // Shadow comes after the clip so it isn't clipped away.
        .clipShape(.rect(cornerRadius: 10))
        .shadow(color: .black.opacity(0.12), radius: 5, y: 2)
    }
}
