import SwiftUI

/// Profile header with Dynamic Island metaball morphing.
/// Avatar shrinks, blurs, and fades as user scrolls up.
/// Name/subtitle pins to top when scrolled past (sticky header).
struct SettingsProfileHeader: View {
    let viewModel: SettingsViewModel
    let avatarImage: UIImage?
    let safeArea: EdgeInsets
    let isHavingNotch: Bool
    let screenWidth: CGFloat
    @State private var scrollProgress: CGFloat = 0

    @State private var textHeaderOffset: CGFloat = .infinity

    private let avatarFullSize: CGFloat = 100
    private let avatarMinScale: CGFloat = 0.55

    private var avatarSize: CGFloat {
        let scale = 1.0 - (1.0 - avatarMinScale) * scrollProgress
        return avatarFullSize * scale
    }

    var body: some View {
        let fixedTop: CGFloat = safeArea.top + 3

        VStack(spacing: 12) {
            // MARK: Avatar with morph tracking
            AvatarView(
                initials: viewModel.initials,
                colorIndex: viewModel.avatarColorIndex,
                size: avatarSize,
                isSavedMessages: false,
                image: avatarImage
            )
            .background(RosettaColors.Adaptive.background)
            .opacity(1 - scrollProgress)
            .blur(radius: scrollProgress * 10)
            .clipShape(Circle())
            .anchorPreference(key: AnchorKey.self, value: .bounds) {
                ["HEADER": $0]
            }
            .padding(.top, safeArea.top + 15)
            .offsetExtractor(coordinateSpace: "SETTINGS_SCROLL") { scrollRect in
                guard isHavingNotch else { return }
                let progress = -scrollRect.minY / 25
                scrollProgress = min(max(progress, 0), 1)
            }

            // MARK: Sticky text header
            VStack(spacing: 4) {
                HStack(spacing: 4) {
                    Text(viewModel.headerName)
                        .font(.system(size: 22, weight: .bold))
                        .foregroundStyle(RosettaColors.Adaptive.text)
                        .scaleEffect(1.0 - scrollProgress * 0.4)

                    VerifiedBadge(verified: viewModel.verified, size: 18)
                }

                if !viewModel.username.isEmpty {
                    Text("@\(viewModel.username)")
                        .font(.system(size: 15))
                        .foregroundStyle(RosettaColors.secondaryText)
                        .opacity(1.0 - scrollProgress)
                }
            }
            .padding(.vertical, 15)
            .background {
                Rectangle()
                    .fill(RosettaColors.Adaptive.background)
                    .frame(width: screenWidth)
                    .padding(.top, textHeaderOffset < fixedTop ? -safeArea.top : 0)
                    .shadow(
                        color: .black.opacity(min(1.0, max(0.0, (fixedTop - textHeaderOffset) / 20.0)) * 0.1),
                        radius: 5, x: 0, y: 5
                    )
            }
            .offset(y: textHeaderOffset < fixedTop ? -(textHeaderOffset - fixedTop) : 0)
            .offsetExtractor(coordinateSpace: "SETTINGS_SCROLL") {
                textHeaderOffset = $0.minY
            }
            .zIndex(1000)

            // MARK: Public key (below sticky area)
            CopyableText(
                displayText: formatPublicKey(viewModel.publicKey),
                fullText: viewModel.publicKey,
                font: .monospacedSystemFont(ofSize: 12, weight: .regular),
                textColor: UIColor(RosettaColors.tertiaryText)
            )
            .frame(height: 16)
        }
        .padding(.vertical, 8)
    }

    private func formatPublicKey(_ key: String) -> String {
        guard key.count > 16 else { return key }
        return String(key.prefix(8)) + "..." + String(key.suffix(6))
    }
}
