import SwiftUI

struct ReaderTabView: View {
    @Bindable var vm: ReaderViewModel
    @State private var selectedSubTab = 0
    @State private var showFeedSheet = false
    @State private var showFeedManagement = false
    @State private var isCardView = true

    var body: some View {
        NavigationStack {
            VStack(spacing: 0) {
                // Sub-tab selector — ALWAYS rendered (prevents layout jitter)
                HStack(spacing: 0) {
                    ForEach(Array(subTabs.enumerated()), id: \.offset) { index, tab in
                        Button {
                            withAnimation(.easeInOut(duration: 0.2)) {
                                selectedSubTab = index
                                switch index {
                                case 0: vm.applyFilter(.unread)
                                case 1: vm.applyFilter(.starred)
                                case 2: vm.applyFilter(.all)
                                default: break
                                }
                            }
                        } label: {
                            HStack(spacing: 4) {
                                Text(tab)
                                    .font(.subheadline.weight(selectedSubTab == index ? .semibold : .regular))

                                if index == 0, let counters = vm.counters, counters.totalUnread > 0 {
                                    Text("\(counters.totalUnread)")
                                        .font(.caption2.weight(.bold))
                                        .foregroundStyle(.white)
                                        .padding(.horizontal, 6)
                                        .padding(.vertical, 2)
                                        .background(Color.accentWarm)
                                        .clipShape(Capsule())
                                }
                            }
                            .foregroundStyle(selectedSubTab == index ? Color.accentWarm : Color.textSecondary)
                            .padding(.vertical, 10)
                            .padding(.horizontal, 16)
                            .background {
                                if selectedSubTab == index {
                                    Capsule()
                                        .fill(Color.accentWarm.opacity(0.12))
                                }
                            }
                        }
                    }
                }
                .padding(.horizontal)
                .padding(.top, 8)

                // Feed filter bar — ALWAYS rendered, empty during load (stable height)
                ScrollView(.horizontal, showsIndicators: false) {
                    HStack(spacing: 8) {
                        feedFilterChip("All", isSelected: isAllSelected) {
                            let tab = selectedSubTab
                            switch tab {
                            case 0: vm.applyFilter(.unread)
                            case 1: vm.applyFilter(.starred)
                            case 2: vm.applyFilter(.all)
                            default: vm.applyFilter(.unread)
                            }
                        }

                        ForEach(vm.feeds) { feed in
                            let count = vm.counters?.count(forFeed: feed.id) ?? 0
                            feedFilterChip(
                                feed.title,
                                count: selectedSubTab == 0 ? count : nil,
                                isSelected: vm.currentFilter == .feed(feed.id)
                            ) {
                                vm.applyFilter(.feed(feed.id))
                            }
                        }
                    }
                    .padding(.horizontal)
                    .padding(.vertical, 8)
                }
                .frame(height: 44) // Fixed height prevents layout shift

                // Entry list
                EntryListView(vm: vm, isCardView: isCardView)
            }
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .background(Color.canvas)
            .navigationBarHidden(true)
            .toolbar {
                ToolbarItem(placement: .topBarTrailing) {
                    Button {
                        withAnimation(.easeInOut(duration: 0.2)) {
                            isCardView.toggle()
                        }
                    } label: {
                        Image(systemName: isCardView ? "list.bullet" : "square.grid.2x2")
                            .foregroundStyle(Color.accentWarm)
                    }
                }
                ToolbarItem(placement: .topBarTrailing) {
                    Menu {
                        Button {
                            Task { await vm.markAllRead() }
                        } label: {
                            Label("Mark All Read", systemImage: "checkmark.circle")
                        }

                        Button {
                            Task { await vm.refresh() }
                        } label: {
                            Label("Refresh Feeds", systemImage: "arrow.clockwise")
                        }

                        Divider()

                        Button {
                            showFeedManagement = true
                        } label: {
                            Label("Manage Feeds", systemImage: "list.bullet")
                        }

                        Button {
                            showFeedSheet = true
                        } label: {
                            Label("Add Feed", systemImage: "plus")
                        }
                    } label: {
                        Image(systemName: "ellipsis.circle")
                            .foregroundStyle(Color.accentWarm)
                    }
                }
            }
            .sheet(isPresented: $showFeedSheet) {
                AddFeedSheet(vm: vm)
            }
            .sheet(isPresented: $showFeedManagement) {
                FeedManagementSheet(vm: vm)
            }
        }
        .onAppear {
            ArticleRenderer.shared.reWarmIfNeeded()
        }
    }

    private var subTabs: [String] { ["Unread", "Starred", "All"] }

    private var isAllSelected: Bool {
        switch vm.currentFilter {
        case .unread, .starred, .all: return true
        default: return false
        }
    }

    private func feedFilterChip(
        _ title: String,
        count: Int? = nil,
        isSelected: Bool,
        action: @escaping () -> Void
    ) -> some View {
        Button(action: action) {
            HStack(spacing: 4) {
                Text(title)
                    .font(.caption.weight(isSelected ? .semibold : .regular))
                    .lineLimit(1)
                if let count, count > 0 {
                    Text("\(count)")
                        .font(.system(size: 10).weight(.bold))
                }
            }
            .foregroundStyle(isSelected ? Color.accentWarm : Color.textSecondary)
            .padding(.horizontal, 12)
            .padding(.vertical, 6)
            .background(isSelected ? Color.accentWarm.opacity(0.12) : Color.surfaceCard)
            .clipShape(Capsule())
        }
    }
}
