//
//  MeterDataGroupsTabView.swift
//  USB Meter
//

import SwiftUI

struct MeterDataGroupsTabView: View {
    @EnvironmentObject private var usbMeter: Meter

    var body: some View {
        GeometryReader { box in
            let columnTitles = [usbMeter.supportsDataGroupCommands ? "Group" : "Memory"]
                + (usbMeter.showsDataGroupEnergy ? ["Wh"] : [])
                + (usbMeter.supportsDataGroupCommands ? ["Clear"] : [])
            let columnWidth = (box.size.width - 60) / CGFloat(columnTitles.count)

            ScrollView {
                VStack(alignment: .leading, spacing: 14) {
                    VStack(alignment: .leading, spacing: 8) {
                        HStack(spacing: 8) {
                            Text(usbMeter.dataGroupsTitle)
                                .font(.system(.title3, design: .rounded).weight(.bold))
                            if let hint = usbMeter.dataGroupsHint {
                                ContextInfoButton(
                                    title: usbMeter.dataGroupsTitle,
                                    message: hint
                                )
                            }
                        }
                    }
                    .padding(18)
                    .meterCard(tint: .teal, fillOpacity: 0.18, strokeOpacity: 0.24)

                    HStack(spacing: 8) {
                        ForEach(columnTitles, id: \.self) { text in
                            headerCell(text: text, width: columnWidth)
                        }
                    }

                    VStack(spacing: 10) {
                        ForEach(usbMeter.availableDataGroupIDs, id: \.self) { groupId in
                            DataGroupRowView(
                                id: groupId,
                                width: columnWidth,
                                opacity: groupId.isMultiple(of: 2) ? 0.1 : 0.2,
                                showsCommands: usbMeter.supportsDataGroupCommands,
                                showsEnergy: usbMeter.showsDataGroupEnergy,
                                highlightsSelection: usbMeter.highlightsActiveDataGroup
                            )
                        }
                    }
                }
                .padding()
            }
            .background(
                LinearGradient(
                    colors: [.teal.opacity(0.14), Color.clear],
                    startPoint: .topLeading,
                    endPoint: .bottomTrailing
                )
                .ignoresSafeArea()
            )
        }
    }

    private func headerCell(text: String, width: CGFloat) -> some View {
        Text(text)
            .font(.footnote.weight(.bold))
            .frame(width: width)
            .frame(minHeight: 38)
            .foregroundColor(.secondary)
            .meterCard(tint: .secondary, fillOpacity: 0.14, strokeOpacity: 0.20, cornerRadius: 14)
    }
}
