//
//  WiredTransferPhotoPreviewSheet.swift
//  suixinkan
//

import SwiftUI
import Kingfisher

/// 有线传图照片预览，支持本地 file:// 与远程 URL。
struct WiredTransferPhotoPreviewSheet: View {
    let imageSources: [String]
    let startIndex: Int
    let onDismiss: () -> Void

    @State private var currentIndex: Int

    init(imageSources: [String], startIndex: Int, onDismiss: @escaping () -> Void) {
        self.imageSources = imageSources
        self.startIndex = startIndex
        self.onDismiss = onDismiss
        let safeIndex = imageSources.isEmpty ? 0 : min(max(startIndex, 0), imageSources.count - 1)
        _currentIndex = State(initialValue: safeIndex)
    }

    var body: some View {
        NavigationStack {
            TabView(selection: $currentIndex) {
                ForEach(Array(imageSources.enumerated()), id: \.offset) { index, source in
                    previewImage(source)
                        .tag(index)
                        .frame(maxWidth: .infinity, maxHeight: .infinity)
                        .background(Color.black)
                }
            }
            .tabViewStyle(.page(indexDisplayMode: imageSources.count > 1 ? .automatic : .never))
            .background(Color.black.ignoresSafeArea())
            .navigationTitle("图片预览")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button("关闭", action: onDismiss)
                }
            }
        }
    }

    @ViewBuilder
    private func previewImage(_ source: String) -> some View {
        if let url = URL(string: source), !source.isEmpty {
            KFImage(url)
                .resizable()
                .scaledToFit()
        } else {
            Text("暂无法预览该照片")
                .foregroundStyle(.white.opacity(0.8))
        }
    }
}
