import SwiftUI
import WebKit

struct SVGImage: UIViewRepresentable {
    let svgName: String
    
    func makeUIView(context: Context) -> WKWebView {
        let webView = WKWebView()
        webView.isOpaque = false
        webView.backgroundColor = .clear
        webView.scrollView.isScrollEnabled = false
        webView.scrollView.contentInsetAdjustmentBehavior = .never
        
        // 1. 获取 SVG 文件路径（注意：移除了 inDirectory 参数）
        guard let path = Bundle.main.path(forResource: svgName, ofType: "svg") else {
            print("❌ 无法找到 SVG 文件: \(svgName).svg")
            // 打印所有可用的资源文件，用于调试
            if let resourcePath = Bundle.main.resourcePath {
                print("可用的资源文件: \(try? FileManager.default.contentsOfDirectory(atPath: resourcePath))")
            }
            return webView
        }
        
        // 2. 创建文件 URL
        let fileURL = URL(fileURLWithPath: path)
        
        // 3. 创建 HTML 字符串
        let htmlString = """
        <!DOCTYPE html>
        <html>
        <head>
            <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
            <style>
                body, html { 
                    margin: 0; 
                    padding: 0; 
                    width: 100%; 
                    height: 100%; 
                    overflow: hidden;
                    background-color: transparent;
                }
                svg { 
                    width: 100%; 
                    height: 100%; 
                    display: block;
                }
                img {
                    max-width: 100%;
                    max-height: 100%;
                    object-fit: contain;
                }
            </style>
        </head>
        <body>
            <div style="width:100%; height:100%; display:flex; align-items:center; justify-content:center;">
                <img src="\(fileURL.lastPathComponent)" />
            </div>
        </body>
        </html>
        """
        
        // 4. 加载 HTML 字符串
        webView.loadHTMLString(htmlString, baseURL: fileURL.deletingLastPathComponent())
        return webView
    }
    
    func updateUIView(_ uiView: WKWebView, context: Context) {}
}