package click.kamil.springstatemachineexporter.html.exporter;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SvgDecorator {

    public String decorate(String rawSvg) {
        String result = rawSvg;

        // 1. Properly replace width/height with 100% on the root <svg> tag
        result = result.replaceFirst("(?i)width=\"[^\"]*\"", "width=\"100%\"");
        result = result.replaceFirst("(?i)height=\"[^\"]*\"", "height=\"100%\"");
        
        // 2. Remove the hardcoded 'style' attribute if present
        result = result.replaceFirst("(?i)style=\"[^\"]*\"", "");
        
        // 3. Maintain layout integrity
        result = result.replace("preserveAspectRatio=\"none\"", "preserveAspectRatio=\"xMidYMid meet\"");

        // 4. Inject CSS for interactivity (Highlights, Halos, Animations)
        String styleBlock = """
            <style>
                .dimmed { opacity: 0.1 !important; filter: grayscale(1); transition: opacity 0.4s ease; pointer-events: none; }
                
                /* Transition Highlighting */
                .active-path path { 
                    stroke: #ef4444 !important; 
                    stroke-width: 4.5px !important; 
                    filter: drop-shadow(0 0 6px rgba(239, 68, 68, 0.4));
                    transition: all 0.3s ease;
                    stroke-dasharray: 8;
                    animation: sm-flow 1s linear infinite;
                }
                
                @keyframes sm-flow {
                    from { stroke-dashoffset: 16; }
                    to { stroke-dashoffset: 0; }
                }

                .active-path text {
                    fill: #000 !important;
                    font-weight: 800 !important;
                    paint-order: stroke;
                    stroke: #fff;
                    stroke-width: 4px;
                }

                .node circle, .node rect, .node ellipse { transition: all 0.3s ease; }
                .active-node circle, .active-node rect, .active-node ellipse {
                    stroke: #ef4444 !important;
                    stroke-width: 3.5px !important;
                }
                
                /* Hide stereotype text labels that PlantUML renders as part of stereotypes */
                svg [class*="link_"] text:last-child { display: none !important; }
            </style>
            """;

        int defsEnd = result.indexOf("</defs>");
        if (defsEnd != -1) {
            result = result.substring(0, defsEnd + 7) + styleBlock + result.substring(defsEnd + 7);
        }

        return result;
    }
}
