import SwiftUI
import UIKit

// MARK: - Telegram-style Navigation Bar Blur (NavigationBackgroundNode parity)
//
// Telegram uses UIVisualEffectView(UIBlurEffect(.light)) with stripped filters:
// keeps only gaussianBlur + colorSaturate, removes everything else.
// This is NOT the same as Apple's .regularMaterial.

/// UIViewRepresentable that replicates Telegram's NavigationBackgroundNode blur.
struct TelegramNavBlurView: UIViewRepresentable {
    func makeUIView(context: Context) -> TelegramNavBlurUIView {
        let view = TelegramNavBlurUIView(frame: .zero)
        view.isUserInteractionEnabled = false
        return view
    }

    func updateUIView(_ uiView: TelegramNavBlurUIView, context: Context) {}
}

/// UIKit implementation of Telegram's NavigationBackgroundNode blur.
/// Uses UIBlurEffect(.light) with only gaussianBlur + colorSaturate filters.
final class TelegramNavBlurUIView: UIView {
    private let effectView: UIVisualEffectView
    private let tintLayer = CALayer()

    override init(frame: CGRect) {
        self.effectView = UIVisualEffectView(effect: UIBlurEffect(style: .light))

        super.init(frame: frame)
        clipsToBounds = true
        isUserInteractionEnabled = false

        // Strip UIVisualEffectView subviews (same as Telegram)
        for subview in effectView.subviews {
            if subview.description.contains("VisualEffectSubview") {
                subview.isHidden = true
            }
        }

        // Keep only gaussianBlur + colorSaturate filters on the backdrop sublayer
        if let sublayer = effectView.layer.sublayers?[0], let filters = sublayer.filters {
            sublayer.backgroundColor = nil
            sublayer.isOpaque = false
            let allowedKeys: [String] = ["colorSaturate", "gaussianBlur"]
            sublayer.filters = filters.filter { filter in
                guard let filter = filter as? NSObject else { return true }
                let filterName = String(describing: filter)
                return allowedKeys.contains(filterName)
            }
        }

        addSubview(effectView)

        // Tint overlay — Telegram applies the bar color on top of blur
        tintLayer.backgroundColor = UIColor { traits in
            traits.userInterfaceStyle == .dark
                ? UIColor(white: 0.0, alpha: 0.85)
                : UIColor(white: 1.0, alpha: 0.85)
        }.cgColor
        layer.addSublayer(tintLayer)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        effectView.frame = bounds
        tintLayer.frame = bounds
    }

    override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        super.traitCollectionDidChange(previousTraitCollection)
        guard traitCollection.userInterfaceStyle != previousTraitCollection?.userInterfaceStyle else { return }
        tintLayer.backgroundColor = traitCollection.userInterfaceStyle == .dark
            ? UIColor(white: 0.0, alpha: 0.85).cgColor
            : UIColor(white: 1.0, alpha: 0.85).cgColor
    }
}

// MARK: - Glass Navigation Bar Modifier

/// iOS 26+: native glassmorphism (no explicit background needed).
/// iOS < 26: Telegram-style blur (UIBlurEffect(.light) + stripped filters).
struct GlassNavBarModifier: ViewModifier {
    func body(content: Content) -> some View {
        content
            .toolbarBackground(.hidden, for: .navigationBar)
            .background {
                TelegramNavBlurView()
                    .ignoresSafeArea(edges: .top)
            }
    }
}

extension View {
    func applyGlassNavBar() -> some View {
        modifier(GlassNavBarModifier())
    }
}

// MARK: - Glass Search Bar Modifier

/// iOS 26+: glassmorphism capsule.
/// iOS < 26: no-op (standard search bar appearance).
struct GlassSearchBarModifier: ViewModifier {
    func body(content: Content) -> some View {
        content
    }
}

extension View {
    func applyGlassSearchBar() -> some View {
        modifier(GlassSearchBarModifier())
    }
}
