//
//  LiquidGlassTabContainer.swift
//  lichunWebsocket
//
//  Container view that manages tab bar visibility based on scroll
//

import SwiftUI

// MARK: - Liquid Glass Tab Container

struct LiquidGlassTabContainer<Content: View>: View {
    @Binding var selectedTab: Int
    let items: [TabBarItem]
    let content: Content
    let onMoreTapped: () -> Void

    @State private var isMinimized = false
    @State private var lastScrollOffset: CGFloat = 0
    @State private var scrollOffset: CGFloat = 0

    init(
        selectedTab: Binding<Int>,
        items: [TabBarItem],
        onMoreTapped: @escaping () -> Void,
        @ViewBuilder content: () -> Content
    ) {
        self._selectedTab = selectedTab
        self.items = items
        self.onMoreTapped = onMoreTapped
        self.content = content()
    }

    var body: some View {
        ZStack(alignment: .bottom) {
            // Content with scroll detection
            content
                .safeAreaInset(edge: .bottom) {
                    // Reserve space for tab bar
                    Color.clear
                        .frame(height: isMinimized ? 60 : 84)
                }

            // Floating tab bar
            VStack {
                Spacer()

                LiquidGlassTabBar(
                    selectedTab: $selectedTab,
                    items: items,
                    isMinimized: isMinimized,
                    onMoreTapped: onMoreTapped
                )
            }
            .ignoresSafeArea(edges: .bottom)
        }
        .onPreferenceChange(TabBarScrollOffsetPreferenceKey.self) { value in
            handleScroll(offset: value)
        }
    }

    private func handleScroll(offset: CGFloat) {
        let delta = offset - lastScrollOffset
        lastScrollOffset = offset

        // Threshold for minimizing (scrolling down)
        let minimizeThreshold: CGFloat = 50
        // Threshold for expanding (scrolling up)
        let expandThreshold: CGFloat = -30

        withAnimation(.spring(response: 0.4, dampingFraction: 0.8)) {
            if delta > minimizeThreshold && !isMinimized {
                isMinimized = true
            } else if delta < expandThreshold && isMinimized {
                isMinimized = false
            }
        }
    }
}

// MARK: - Scroll Offset Preference Key

fileprivate struct TabBarScrollOffsetPreferenceKey: PreferenceKey {
    static var defaultValue: CGFloat = 0

    static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
        value = nextValue()
    }
}

// MARK: - Scroll Offset Modifier

extension View {
    func trackScrollOffset() -> some View {
        background(
            GeometryReader { geometry in
                Color.clear
                    .preference(
                        key: TabBarScrollOffsetPreferenceKey.self,
                        value: geometry.frame(in: .named("scroll")).minY
                    )
            }
        )
    }
}

// MARK: - Preview

#if DEBUG
struct LiquidGlassTabContainer_Previews: PreviewProvider {
    static var previews: some View {
        LiquidGlassTabContainer(
            selectedTab: .constant(0),
            items: [
                TabBarItem(id: 0, icon: "house", selectedIcon: "house.fill", label: "Home"),
                TabBarItem(id: 1, icon: "calendar", selectedIcon: "calendar", label: "Activities"),
                TabBarItem(id: 2, icon: "heart.circle", selectedIcon: "heart.circle.fill", label: "Social"),
                TabBarItem(id: 3, icon: "line.3.horizontal.circle", selectedIcon: "line.3.horizontal.circle.fill", label: "More")
            ],
            onMoreTapped: {}
        ) {
            ScrollView {
                VStack(spacing: 20) {
                    ForEach(0..<20) { i in
                        RoundedRectangle(cornerRadius: 16)
                            .fill(AppColors.surfaceElevated)
                            .frame(height: 100)
                            .padding(.horizontal)
                            .overlay(
                                Text("Item \(i)")
                                    .foregroundColor(AppColors.primaryText)
                            )
                    }
                }
                .padding(.vertical)
            }
            .coordinateSpace(name: "scroll")
        }
    }
}
#endif
