package org.example.petshopdesktop.ui;

import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.web.WebView;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

public final class SvgWebViewFactory {
    private SvgWebViewFactory() {
    }

    public static StackPane build(String resourcePath, double size) {
        WebView webView = new WebView();
        webView.setContextMenuEnabled(false);
        webView.setPrefSize(size, size);
        webView.setMinSize(size, size);
        webView.setMaxSize(size, size);
        webView.setZoom(1.0);
        webView.setPageFill(Color.TRANSPARENT);
        webView.setStyle("-fx-background-color: transparent;");

        String svg = loadSvg(resourcePath)
            .replaceFirst("<svg\\b", "<svg width=\"100%\" height=\"100%\" preserveAspectRatio=\"xMidYMid meet\"");

        String html = "<html><body style='margin:0;display:flex;align-items:center;justify-content:center;background:transparent;overflow:hidden;-webkit-user-select:none;user-select:none;pointer-events:none;'>"
            + svg.replace("<svg", "<svg style=\"pointer-events:none;-webkit-user-select:none;user-select:none;\"")
            + "</body></html>";
        webView.getEngine().loadContent(html, "text/html");

        StackPane container = new StackPane(webView);
        container.setPrefSize(size, size);
        container.setMinSize(size, size);
        container.setMaxSize(size, size);
        return container;
    }

    private static String loadSvg(String resourcePath) {
        try (InputStream stream = SvgWebViewFactory.class.getResourceAsStream(resourcePath)) {
            if (stream == null) {
                throw new IllegalArgumentException("Resource not found: " + resourcePath);
            }
            return new String(stream.readAllBytes(), StandardCharsets.UTF_8);
        } catch (IOException e) {
            throw new IllegalStateException("Unable to read SVG: " + resourcePath, e);
        }
    }
}
