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
        
        if let url = Bundle.main.url(forResource: svgName, withExtension: "svg") {
            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;
                    }
                    svg { 
                        width: 100%; 
                        height: 100%; 
                        display: block;
                    }
                </style>
            </head>
            <body>
                <div style="width:100%; height:100%; display:flex; align-items:center; justify-content:center;">
                    <img src="\(url.absoluteString)" style="max-width:100%; max-height:100%;" />
                </div>
            </body>
            </html>
            """
            
            webView.loadHTMLString(htmlString, baseURL: nil)
        }
        
        return webView
    }
    
    func updateUIView(_ uiView: WKWebView, context: Context) {}
}

// MARK: - View Modifier for SVG Image
struct SVGImageModifier: ViewModifier {
    let size: CGSize
    
    func body(content: Content) -> some View {
        content
            .frame(width: size.width, height: size.height)
            .aspectRatio(contentMode: .fit)
    }
}

extension View {
    func svgImageStyle(size: CGSize) -> some View {
        self.modifier(SVGImageModifier(size: size))
    }
}

// Usage:
// SVGImage(svgName: "Avatar")
