import SwiftUI

/// Telegram-parity expandable profile header.
/// Collapsed: 100pt circular avatar, centered name, action buttons.
/// Expanded (pull-down): full-width rectangular photo, left-aligned name, glass buttons.
struct PeerProfileHeaderView: View {
    @Binding var isLargeHeader: Bool
    @Binding var topInset: CGFloat
    let displayName: String
    let subtitleText: String
    let effectiveVerified: Int
    let avatarImage: UIImage?
    let avatarInitials: String
    let avatarColorIndex: Int
    let isMuted: Bool
    var isSavedMessages: Bool = false
    var showCallButton: Bool = true
    var showMuteButton: Bool = true
    var showMessageButton: Bool = false
    let onCall: () -> Void
    let onMuteToggle: () -> Void
    let onSearch: () -> Void
    let onMore: () -> Void
    var onMessage: (() -> Void)?

    @Environment(\.colorScheme) private var colorScheme

    // MARK: - Body

    var body: some View {
        VStack(spacing: 12) {
            // Invisible placeholder — drives geometry for the resizable avatar behind it
            Rectangle()
                .foregroundStyle(.clear)
                .frame(width: 100, height: isLargeHeader ? 300 : 100)
                .clipShape(.circle)

            VStack(spacing: 20) {
                navigationBarContent
                    .foregroundStyle(isLargeHeader ? .white : RosettaColors.Adaptive.text)

                actionButtons
                    .foregroundStyle(isLargeHeader ? .white : RosettaColors.primaryBlue)
                    .geometryGroup()
            }
        }
        .padding(.horizontal, 15)
        .padding(.bottom, 15)
        .background(alignment: .top) { avatarBackground }
        .padding(.top, 15)
    }

    // MARK: - Avatar Background (GeometryReader parallax)

    private var avatarBackground: some View {
        GeometryReader { geo in
            let size = geo.size
            let minY = geo.frame(in: .global).minY
            let topOffset = isLargeHeader ? minY : 0

            avatarContent
                .frame(width: size.width, height: size.height + topOffset)
                .clipped()
                .clipShape(.rect(cornerRadius: isLargeHeader ? 0 : 50))
                .offset(y: -topOffset)
                .drawingGroup()
        }
        .frame(
            width: isLargeHeader ? nil : 100,
            height: isLargeHeader ? nil : 100
        )
    }

    @ViewBuilder
    private var avatarContent: some View {
        if let image = avatarImage {
            Image(uiImage: image)
                .resizable()
                .scaledToFill()
        } else if isSavedMessages {
            // Saved Messages: bookmark icon on blue background
            ZStack {
                Rectangle().fill(RosettaColors.primaryBlue)
                Image(systemName: "bookmark.fill")
                    .font(.system(size: isLargeHeader ? 80 : 38, weight: .semibold))
                    .foregroundStyle(.white)
            }
        } else {
            let pair = RosettaColors.avatarColors[avatarColorIndex % RosettaColors.avatarColors.count]
            let textColor: Color = colorScheme == .dark ? pair.text : pair.tint
            ZStack {
                Rectangle().fill(colorScheme == .dark ? Color(hex: 0x1A1B1E) : .white)
                Rectangle().fill(pair.tint.opacity(colorScheme == .dark ? 0.15 : 0.10))
                Text(avatarInitials)
                    .font(.system(size: isLargeHeader ? 120 : 38, weight: .bold, design: .rounded))
                    .foregroundStyle(textColor)
            }
        }
    }

    // MARK: - Navigation Bar Content (sticky + scale)

    private var navigationBarContent: some View {
        VStack(alignment: isLargeHeader ? .leading : .center, spacing: isLargeHeader ? 4 : 1) {
            HStack(spacing: 5) {
                Text(displayName)
                    .font(isLargeHeader ? .title2.weight(.semibold) : .system(size: 17, weight: .semibold))
                    .lineLimit(isLargeHeader ? 2 : 1)

                if effectiveVerified > 0 {
                    VerifiedBadge(
                        verified: effectiveVerified,
                        size: isLargeHeader ? 18 : 15,
                        badgeTint: isLargeHeader ? .white : nil
                    )
                }
            }

            Text(subtitleText)
                .font(isLargeHeader ? .callout : .system(size: 16))
                .foregroundStyle(isLargeHeader ? .white.opacity(0.7) : .secondary)
        }
        .frame(maxWidth: .infinity, alignment: isLargeHeader ? .leading : .center)
        .visualEffect { content, proxy in
            let minY = proxy.frame(in: .scrollView(axis: .vertical)).minY
            let progress = max(min(minY / 50, 1), 0)
            let contentH = proxy.size.height
            let navBarCenterY: CGFloat = -22
            let centeringOffset = navBarCenterY - contentH / 2

            return content
                .offset(y: minY < 0 ? -minY + centeringOffset * (1 - progress) : 0)
        }
        .background { navBarBackground }
        .zIndex(1000)
    }

    // MARK: - Navigation Bar Background (progressive blur)

    /// Gradient scrim color: black when photo expanded (contrast for white text),
    /// adaptive background when collapsed (blends with content).
    private var scrimColor: Color {
        isLargeHeader ? .black : RosettaColors.Adaptive.background
    }

    private static let scrimMask = LinearGradient(
        stops: [
            .init(color: .black, location: 0.0),
            .init(color: .black, location: 0.45),
            .init(color: .black.opacity(0.9), location: 0.55),
            .init(color: .black.opacity(0.75), location: 0.65),
            .init(color: .black.opacity(0.55), location: 0.75),
            .init(color: .black.opacity(0.3), location: 0.85),
            .init(color: .black.opacity(0.1), location: 0.93),
            .init(color: .clear, location: 1.0),
        ],
        startPoint: .top,
        endPoint: .bottom
    )

    private var navBarBackground: some View {
        GeometryReader { geo in
            let minY = geo.frame(in: .scrollView(axis: .vertical)).minY
            let opacity = 1.0 - max(min(minY / 50, 1), 0)

            Rectangle()
                .fill(scrimColor)
                .mask { Self.scrimMask }
                .padding(-20)
                .padding(.bottom, -40)
                .padding(.top, -topInset)
                .offset(y: -minY)
                .opacity(opacity)
                .drawingGroup()
        }
        .allowsHitTesting(false)
    }

    // MARK: - Action Buttons

    private var actionButtons: some View {
        HStack(spacing: 6) {
            if showMessageButton, let onMessage {
                profileActionButton(icon: "bubble.left.fill", title: "Message", action: onMessage)
            }
            if showCallButton {
                profileActionButton(icon: "phone.fill", title: "Call", action: onCall)
            }
            if showMuteButton {
                profileActionButton(
                    icon: isMuted ? "bell.slash.fill" : "bell.fill",
                    title: isMuted ? "Unmute" : "Mute",
                    action: onMuteToggle
                )
            }
            profileActionButton(icon: "magnifyingglass", title: "Search", action: onSearch)
            profileActionButton(icon: "ellipsis", title: "More", action: onMore)
        }
    }

    private func profileActionButton(icon: String, title: String, action: @escaping () -> Void) -> some View {
        Button(action: action) {
            VStack(spacing: 2) {
                Image(systemName: icon)
                    .font(.title3)
                    .frame(height: 30)

                Text(title)
                    .font(.caption)
            }
            .frame(maxWidth: .infinity)
            .padding(.vertical, 5)
            .background {
                RoundedRectangle(cornerRadius: 15, style: .continuous)
                    .fill(isLargeHeader ? Color.white.opacity(0.15) : telegramSectionFill)
            }
            .contentShape(.rect)
        }
        .buttonStyle(.plain)
    }
}
