# render-test

<div id="remote-fragment" aria-live="polite"></div>
  <noscript>A static image or table could go here for no-JS fallback.</noscript>

<!-- 2-b  Load DOMPurify to sanitise the HTML we’ll fetch -->
<script src="https://cdn.jsdelivr.net/npm/dompurify@3/dist/purify.min.js" defer></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/5.4.3/echarts.min.js"></script>
<script>
    const scanResultsData = {
        "name": "Retrievability Audit",
        "children": [
            {
                "name": "Content Accessibility",
                "children": [
                    {
                        "name": "Javascript Dependent Content",
                        "value": 8,
                        "score": 6,
                        "details": "SPA framework detected",
                        "recommendation": null
                    },
                    {
                        "name": "Performance Rendering",
                        "value": 4,
                        "score": 9,
                        "details": "Page load time: 546ms. JS bundle size: 74KB. Image size: 0KB. Total size: 74KB. Server-side rendering detected.",
                        "recommendation": null
                    },
                    {
                        "name": "Paywalls Licensing Restrictions",
                        "value": 8,
                        "score": 7,
                        "details": "API access mentioned. ",
                        "recommendation": null
                    },
                    {
                        "name": "Media Heavy Content Without Transcripts",
                        "value": 9,
                        "score": 9,
                        "details": "Images: 25 total, 7 with alt text (28.0%).",
                        "recommendation": null
                    },
                    {
                        "name": "Lazy Loaded Content",
                        "value": 7,
                        "score": 9,
                        "details": "Content changed after scrolling (height: 6592 → 6601, elements: 3856 → 3856). 'View All' mode available.",
                        "recommendation": null
                    },
                    {
                        "name": "PDF and Document Exports as Primary Content Sources",
                        "value": 7,
                        "score": 9,
                        "details": "Document links: PDF=0, Word=0, Excel=0, CSV=0 (total=0). Document download prompts detected. ",
                        "recommendation": null
                    },
                    {
                        "name": "Content Embedded in Canvas or SVG Elements",
                        "value": 8,
                        "score": 9,
                        "details": "SVG elements: 388. Chart library detected.",
                        "recommendation": null
                    },
                    {
                        "name": "Alternative Text Format Availability",
                        "value": 5,
                        "score": 2,
                        "details": "Structured data markup present.",
                        "recommendation": "Provide markdown or plain text versions of content; offer RSS/Atom feeds; create API endpoints with structured text data; link to alternative formats in HTML head."
                    },
                    {
                        "name": "Image Optimization for AI",
                        "value": 6,
                        "score": 4,
                        "details": "Total images: 25. Images with alt text: 25 (100%). Images with descriptive alt: 2. Images with captions: 0.",
                        "recommendation": "Add descriptive alt text to all images; use <figure> and <figcaption> for complex images; avoid generic alt text like 'image' or filenames; mark decorative images with empty alt attributes."
                    }
                ]
            },
            {
                "name": "Data Formatting & Consistency",
                "children": [
                    {
                        "name": "Data Formatting Consistency",
                        "value": 3,
                        "score": 7,
                        "details": "Currency formats: usd (6) . Non-UTF8 characters detected. Content attributes: 27.",
                        "recommendation": null
                    },
                    {
                        "name": "Error Handling Signals",
                        "value": 6,
                        "score": 2,
                        "details": "Proper 404 status code returned for non-existent pages. No machine-readable error format detected. No rate limit headers found. ",
                        "recommendation": "Return appropriate HTTP status codes (404, 429, 500); provide JSON/XML error payloads and `Retry-After` headers."
                    },
                    {
                        "name": "Ambiguous Language Links",
                        "value": 3,
                        "score": 5,
                        "details": "Links: total=415, ambiguous=35, empty=5 (9.6% ambiguous). ARIA labeled links: 21. Tooltips detected. ",
                        "recommendation": null
                    },
                    {
                        "name": "Internationalization Localized Content",
                        "value": 4,
                        "score": 0,
                        "details": "HTML lang attribute: en. No hreflang tags. Language switcher detected. Content structure changes by locale. ",
                        "recommendation": "Use `hreflang` tags and explicit URL structures (e.g., `/en-au/`); provide a locale-agnostic API endpoint."
                    },
                    {
                        "name": "Content Freshness Indicators",
                        "value": 6,
                        "score": 1,
                        "details": "Date indicators found: 0. ",
                        "recommendation": "Add last-modified HTTP headers; include datePublished and dateModified in structured data; use <time> elements with datetime attributes for visible dates."
                    }
                ]
            },
            {
                "name": "Technical Implementation",
                "children": [
                    {
                        "name": "Robot Access Crawl Policies",
                        "value": 7,
                        "score": 5,
                        "details": "robots.txt found. No API documentation found. No rate limit headers detected.",
                        "recommendation": null
                    },
                    {
                        "name": "Mobile Responsive Variants",
                        "value": 5,
                        "score": 6,
                        "details": "Desktop elements: 3848. Mobile elements: 3841. Difference: 0.2%. Hidden elements (desktop): 2338 (60.8%). Hidden elements (mobile): 2282 (59.4%). Responsive viewport meta tag detected. ",
                        "recommendation": null
                    },
                    {
                        "name": "Tool Invocation Gaps",
                        "value": 4,
                        "score": 7,
                        "details": "Forms: total=2, with labels=2, with ARIA labels=2. Schema.org Action markup detected. No OpenAPI/Swagger documentation found.",
                        "recommendation": null
                    },
                    {
                        "name": "Graphql RPC Style Endpoints",
                        "value": 5,
                        "score": 9,
                        "details": "",
                        "recommendation": null
                    },
                    {
                        "name": "Dynamic Resource Urls Tokenized Pagination",
                        "value": 6,
                        "score": 0,
                        "details": "Dynamic URL patterns detected (long tokens, UUIDs, or hash fragments).",
                        "recommendation": "Expose stable URL structures; document URL formats and parameters."
                    },
                    {
                        "name": "Content Delivered Via WebSockets Or SSE",
                        "value": 6,
                        "score": 0,
                        "details": "",
                        "recommendation": "Offer REST endpoints that mirror WebSocket data; provide a \"snapshot\" mode with complete state at a given timestamp."
                    },
                    {
                        "name": "Page Redirection Analysis",
                        "value": 6,
                        "score": 5,
                        "details": "Redirect count: 0. Unexpected redirect detected. Mobile-specific redirect behavior detected.",
                        "recommendation": null
                    },
                    {
                        "name": "API Documentation Availability",
                        "value": 8,
                        "score": 0,
                        "details": "No API documentation detected.",
                        "recommendation": "Provide OpenAPI/Swagger documentation; create developer portal with API key management; document rate limits and authentication methods; publish machine-readable API specifications."
                    },
                    {
                        "name": "Search Functionality Accessibility",
                        "value": 6,
                        "score": 4,
                        "details": "Search forms found: 2. Well-formed forms: 0. Visible forms: 2. Labeled forms: 2. GET method available. Search links found.",
                        "recommendation": "Implement visible search form with clear labels; use standard parameter names (q, search, query); provide GET method for simple URL-based search; add SearchAction schema markup; consider OpenSearch description."
                    }
                ]
            },
            {
                "name": "Structural Design",
                "children": [
                    {
                        "name": "Semantic Structure Markup",
                        "value": 6,
                        "score": 7,
                        "details": "Semantic element ratio: 0.13. Total semantic elements: 56. ARIA elements: 71. Generic divs: 948. Schema.org markup present.",
                        "recommendation": null
                    },
                    {
                        "name": "Logical Content Organization",
                        "value": 5,
                        "score": 0,
                        "details": "Shadow DOM detected. iframe count: 5. Maximum DOM depth: 39. Complex nested structures detected.",
                        "recommendation": "Flatten primary content into the main DOM; use schema.org sections or clear container elements."
                    },
                    {
                        "name": "Context Fragmentation",
                        "value": 4,
                        "score": 9,
                        "details": "Multi-step forms detected. Structured linking (JSON-LD/breadcrumbs) detected.",
                        "recommendation": null
                    },
                    {
                        "name": "Structural Volatility",
                        "value": 7,
                        "score": 5,
                        "details": "Classes: total=315, auto-generated=997 (316.5%). Stable attributes: id=333, data-*=391 (ratio=2.30). Angular detected. ",
                        "recommendation": null
                    },
                    {
                        "name": "AB Testing Personalization",
                        "value": 6,
                        "score": 9,
                        "details": "A/B testing frameworks detected. Personalization scripts detected. Canonical URL provided.",
                        "recommendation": null
                    },
                    {
                        "name": "Mixed Content Types In Single Views",
                        "value": 5,
                        "score": 7,
                        "details": "Content types: 5 (lists, paragraphs, headings, images, interactive elements, charts). Semantic structure: section tags, main tag. Machine-readable annotations: Schema.org markup, ARIA roles.",
                        "recommendation": null
                    },
                    {
                        "name": "Inconsistent Field Naming Across Pages",
                        "value": 4,
                        "score": 9,
                        "details": "Total fields: 4. Fields with inconsistent naming: 0 (0.0%). Total naming variants: 0. No data dictionary/glossary found.",
                        "recommendation": null
                    },
                    {
                        "name": "Schema.org Implementation Quality",
                        "value": 7,
                        "score": 6,
                        "details": "JSON-LD schemas found: 1. Total properties: 10. Microdata elements: 33. Organization schema present. ",
                        "recommendation": null
                    },
                    {
                        "name": "Heading Hierarchy Compliance",
                        "value": 5,
                        "score": 9,
                        "details": "Total headings: 75. H1 count: 1. ",
                        "recommendation": null
                    }
                ]
            },
            {
                "name": "Content Quality & RAG",
                "children": [
                    {
                        "name": "RAG Keyword Focus Score",
                        "value": 5,
                        "score": 3,
                        "details": "Keyword density: 0.019. Query found in headings: no.",
                        "recommendation": "Improve keyword relevance and include terms in headings for clearer topical focus."
                    },
                    {
                        "name": "RAG Distraction Penalty",
                        "value": 5,
                        "score": 0,
                        "details": "Word count: 1078. Link count: 415. Link density: 0.385.",
                        "recommendation": "Page contains too many links relative to its content — may be index-like or diluted."
                    },
                    {
                        "name": "RAG Boilerplate Ratio",
                        "value": 4,
                        "score": 0,
                        "details": "Boilerplate ratio: 0.015 (text: 5563 chars, html: 378195 chars).",
                        "recommendation": "Too much of the page is boilerplate or layout. Consider using cleaner markup or separating main content."
                    },
                    {
                        "name": "RAG Concept Density",
                        "value": 4,
                        "score": 1,
                        "details": "Concept density: 0.010 (4 of 416 unique words matched query).",
                        "recommendation": "Page may cover too many unrelated topics. Focus content more tightly around the query intent."
                    },
                    {
                        "name": "Duplicate Content Detection",
                        "value": 7,
                        "score": 5,
                        "details": "Total content blocks: 727. Duplicate blocks: 442. Unique blocks: 285. ",
                        "recommendation": null
                    }
                ]
            },
            {
                "name": "Authentication & Security",
                "children": [
                    {
                        "name": "Authentication Session Management",
                        "value": 9,
                        "score": 2,
                        "details": "Login form detected. ",
                        "recommendation": "Offer public or sandbox API access with OAuth/JWT; document rate limits using proper 429 headers."
                    },
                    {
                        "name": "Security Tokens Access Control",
                        "value": 8,
                        "score": 0,
                        "details": "Cookies: total=31. ",
                        "recommendation": "Offer token-based APIs with clear header requirements; document cookie lifecycles and renewal endpoints."
                    },
                    {
                        "name": "Cookie Consent Overlay Popups",
                        "value": 7,
                        "score": 3,
                        "details": "Overlay popups detected. ",
                        "recommendation": "Expose a \"no-consent\" mode (e.g. `?consent=false`) for agents; provide a clean HTML snapshot without overlays."
                    },
                    {
                        "name": "Anti-Scraping Honeypots",
                        "value": 7,
                        "score": 2,
                        "details": "Hidden honeypot links: 326. Hidden honeypot inputs: 1. Potential honeypot patterns in robots.txt. ",
                        "recommendation": "Document honeypot patterns in `robots.txt` or developer guide; provide a whitelist of \"safe\" crawling paths."
                    },
                    {
                        "name": "Captcha Evolution Invisible Challenges",
                        "value": 9,
                        "score": 5,
                        "details": "Browser fingerprinting scripts detected. ",
                        "recommendation": null
                    },
                    {
                        "name": "Rate Limiting Without Clear Signals",
                        "value": 8,
                        "score": 9,
                        "details": "",
                        "recommendation": null
                    },
                    {
                        "name": "SSL/TLS Implementation Quality",
                        "value": 5,
                        "score": 8,
                        "details": "Uses HTTPS: true. HSTS enabled. X-Frame-Options set. Security headers: 3/5.",
                        "recommendation": null
                    },
                    {
                        "name": "Bot Detection and Anti-Scraping Resistance",
                        "value": 8,
                        "score": 9,
                        "details": "Agents tested: 19. Blocked agents: 0 (0%). Categories completely blocked: 0/6. HTTP Libraries: 0/6 blocked. Search Engines: 0/2 blocked. Scraping Frameworks: 0/2 blocked. Research Crawlers: 0/2 blocked. Browser Automation: 0/3 blocked. AI Services: 0/4 blocked. ",
                        "recommendation": null
                    }
                ]
            }
        ]
    };
    const fingerprint = [{"label":"Javascript Dependent Content","value":8,"score":6},{"label":"Authentication Session Management","value":9,"score":2},{"label":"Semantic Structure Markup","value":6,"score":7},{"label":"Robot Access Crawl Policies","value":7,"score":5},{"label":"Logical Content Organization","value":5,"score":0},{"label":"Performance Rendering","value":4,"score":9},{"label":"Data Formatting Consistency","value":3,"score":7},{"label":"Mobile Responsive Variants","value":5,"score":6},{"label":"Error Handling Signals","value":6,"score":2},{"label":"Security Tokens Access Control","value":8,"score":0},{"label":"Context Fragmentation","value":4,"score":9},{"label":"Ambiguous Language Links","value":3,"score":5},{"label":"Tool Invocation Gaps","value":4,"score":7},{"label":"Structural Volatility","value":7,"score":5},{"label":"AB Testing Personalization","value":6,"score":9},{"label":"Cookie Consent Overlay Popups","value":7,"score":3},{"label":"Paywalls Licensing Restrictions","value":8,"score":7},{"label":"Graphql RPC Style Endpoints","value":5,"score":9},{"label":"Dynamic Resource Urls Tokenized Pagination","value":6,"score":0},{"label":"Media Heavy Content Without Transcripts","value":9,"score":9},{"label":"Anti-Scraping Honeypots","value":7,"score":2},{"label":"Internationalization Localized Content","value":4,"score":0},{"label":"Lazy Loaded Content","value":7,"score":9},{"label":"Captcha Evolution Invisible Challenges","value":9,"score":5},{"label":"Content Delivered Via WebSockets Or SSE","value":6,"score":0},{"label":"Mixed Content Types In Single Views","value":5,"score":7},{"label":"Rate Limiting Without Clear Signals","value":8,"score":9},{"label":"PDF and Document Exports as Primary Content Sources","value":7,"score":9},{"label":"Content Embedded in Canvas or SVG Elements","value":8,"score":9},{"label":"Inconsistent Field Naming Across Pages","value":4,"score":9},{"label":"RAG Keyword Focus Score","value":5,"score":3},{"label":"RAG Distraction Penalty","value":5,"score":0},{"label":"RAG Boilerplate Ratio","value":4,"score":0},{"label":"RAG Concept Density","value":4,"score":1},{"label":"Page Redirection Analysis","value":6,"score":5},{"label":"Alternative Text Format Availability","value":5,"score":2},{"label":"Schema.org Implementation Quality","value":7,"score":6},{"label":"Content Freshness Indicators","value":6,"score":1},{"label":"API Documentation Availability","value":8,"score":0},{"label":"Heading Hierarchy Compliance","value":5,"score":9},{"label":"Image Optimization for AI","value":6,"score":4},{"label":"Duplicate Content Detection","value":7,"score":5},{"label":"SSL/TLS Implementation Quality","value":5,"score":8},{"label":"Search Functionality Accessibility","value":6,"score":4},{"label":"Bot Detection and Anti-Scraping Resistance","value":8,"score":9}];
    const competitorFingerprints = [];
    const entityName = 'nab';

    function getColorForScore(score) {
        if (score <= 2) return '#e41a1c';
        if (score <= 4) return '#ff7f00';
        if (score <= 6) return '#ffff33';
        if (score <= 8) return '#a6d96a';
        return '#4daf4a';
    }

    function getStatusForScore(score) {
        if (score <= 2) return 'Poor';
        if (score <= 4) return 'Marginal';
        if (score <= 6) return 'Fair';
        if (score <= 8) return 'Good';
        return 'Excellent';
    }

    function calculateAverageScore(data) {
        if (!data || data.length === 0) return 0;
        const total = data.reduce((sum, item) => sum + item.score, 0);
        return total / data.length;
    }

    // Helper function to split long text into two lines
    function splitLongText(text, maxLength = 20) {
        if (text.length <= maxLength) {
            return text;
        }

        // Try to split at a space near the middle
        const middle = Math.floor(text.length / 2);
        let splitPoint = middle;

        // Look for a space within 5 characters of the middle
        for (let i = middle - 5; i <= middle + 5; i++) {
            if (i >= 0 && i < text.length && text[i] === ' ') {
                splitPoint = i;
                break;
            }
        }

        // If no space found, split at the middle
        if (text[splitPoint] !== ' ') {
            splitPoint = middle;
        }

        const firstLine = text.substring(0, splitPoint).trim();
        const secondLine = text.substring(splitPoint).trim();

        return firstLine + '\n' + secondLine;
    }

    function createVisualization(data) {
        const container = document.getElementById('visualization');
        const containerRect = container.getBoundingClientRect();
        const width = containerRect.width;
        const height = containerRect.height;

        // Use D3 for circle packing calculation
        const hierarchy = d3.hierarchy(data)
            .sum(d => d.value || 1)
            .sort((a, b) => b.value - a.value);

        const pack = d3.pack()
            .size([width - 40, height - 40])
            .padding(3);

        const root = pack(hierarchy);

        // Transform D3 hierarchy into ECharts data format
        const groupSeries = [];
        const testSeries = [];
        const groupLabels = [];

        root.descendants().forEach(d => {
            if (d.depth === 1) {
                // Group circles
                groupSeries.push({
                    value: [d.x, d.y, d.r * 2],
                    name: d.data.name,
                    itemStyle: {
                        color: 'rgba(68, 68, 68, 0.3)',
                        borderColor: '#666',
                        borderWidth: 1
                    },
                    label: {
                        show: true,
                        position: 'inside',
                        formatter: splitLongText(d.data.name),
                        color: '#ffffff',
                        fontWeight: 'bold',
                        fontSize: Math.min(d.r / 4, 12),
                        textShadowColor: 'rgba(0,0,0,0.8)',
                        textShadowBlur: 4,
                        lineHeight: Math.min(d.r / 3, 14)
                    }
                });
            } else if (d.depth === 2) {
                // Individual test circles
                testSeries.push({
                    value: [d.x, d.y, d.r * 2],
                    name: d.data.name,
                    score: d.data.score,
                    impact: d.data.value,
                    details: d.data.details,
                    recommendation: d.data.recommendation,
                    itemStyle: {
                        color: getColorForScore(d.data.score),
                        borderColor: getColorForScore(d.data.score),
                        borderWidth: 2
                    }
                });
            }
        });

        // Initialize ECharts
        const chart = echarts.init(container, 'dark');

        const option = {
            backgroundColor: '#151515',
            tooltip: {
                trigger: 'item',
                backgroundColor: 'rgba(20, 20, 20, 0.95)',
                borderColor: '#444',
                borderWidth: 1,
                textStyle: {
                    color: '#e0e0e0',
                    fontSize: 12
                },
                formatter: function(params) {
                    if (params.seriesName === 'Groups') {
                        return `<strong>${params.data.name}</strong><br/>Group Container`;
                    } else {
                        let content = `<strong>${params.data.name}</strong><br/>`;
                        content += `Score: ${params.data.score} (${getStatusForScore(params.data.score)})<br/>`;
                        content += `Impact: ${params.data.impact}<br/>`;
                        return content;
                    }
                }
            },
            xAxis: {
                type: 'value',
                show: false,
                min: 0,
                max: width
            },
            yAxis: {
                type: 'value',
                show: false,
                min: 0,
                max: height
            },
            series: [
                {
                    name: 'Groups',
                    type: 'scatter',
                    symbolSize: function(value) {
                        return value[2];
                    },
                    data: groupSeries,
                    silent: true,  // Disable mouse events for group circles
                    emphasis: {
                        disabled: true  // Disable emphasis effects
                    },
                    animation: true,
                    animationDelay: function(idx) {
                        return idx * 100;
                    }
                },
                {
                    name: 'Tests',
                    type: 'scatter',
                    symbolSize: function(value) {
                        return value[2];
                    },
                    data: testSeries,
                    emphasis: {
                        itemStyle: {
                            borderWidth: 4,
                            shadowBlur: 10,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    },
                    animation: true,
                    animationDelay: function(idx) {
                        return 200 + idx * 50;
                    }
                }
            ]
        };

        chart.setOption(option);

        // Handle resize
        window.addEventListener('resize', function() {
            chart.resize();
        });

        generateSummary(root);

        return chart;
    }
    function createGaugeChart(averageScore) {
        const gaugeContainer = document.getElementById('gauge-chart');
        const gaugeChart = echarts.init(gaugeContainer, 'dark');

        const gaugeOption = {
            backgroundColor: 'transparent',
            series: [
                {
                    name: 'Score',
                    type: 'gauge',
                    startAngle: 180,
                    endAngle: 0,
                    center: ['50%', '60%'],
                    radius: '95%',
                    min: 0,
                    max: 10,
                    splitNumber: 4,
                    axisLine: {
                        lineStyle: {
                            width: 35,
                            color: [
                                [0.25, '#e41a1c'],    // Poor (0-2.5)
                                [0.5, '#ff7f00'],     // Marginal (2.5-5)
                                [0.75, '#ffff33'],    // Fair (5-7.5)
                                [1, '#4daf4a']        // Good/Excellent (7.5-10)
                            ]
                        }
                    },
                    pointer: {
                        itemStyle: {
                            color: '#ffffff',
                            shadowColor: 'rgba(0, 0, 0, 0.5)',
                            shadowBlur: 10,
                            shadowOffsetX: 2,
                            shadowOffsetY: 2
                        },
                        length: '75%',
                        width: 8
                    },
                    axisTick: {
                        show: false
                    },
                    splitLine: {
                        show: false
                    },
                    axisLabel: {
                        show: false
                    },
                    detail: {
                        show: false  // Remove the number display
                    },
                    title: {
                        show: false  // Remove the title text
                    },
                    data: [
                        {
                            value: averageScore
                        }
                    ]
                }
            ]
        };

        gaugeChart.setOption(gaugeOption);

        // Handle resize for gauge
        let gaugeResizeTimeout;
        window.addEventListener('resize', function () {
            clearTimeout(gaugeResizeTimeout);
            gaugeResizeTimeout = setTimeout(() => {
                gaugeChart.resize();
            }, 250);
        });

        return gaugeChart;
    }
    function generateSummary(root) {
        let totalTests = 0;
        let scoreTotal = 0;
        const groupScores = {};

        root.leaves().forEach(leaf => {
            totalTests++;
            scoreTotal += leaf.data.score;
        });

        const avgScore = scoreTotal / totalTests;

        root.children.forEach(group => {
            const groupName = group.data.name;
            let groupTotal = 0;
            let groupCount = 0;

            group.leaves().forEach(leaf => {
                groupTotal += leaf.data.score;
                groupCount++;
            });

            groupScores[groupName] = groupTotal / groupCount;
        });

        // Sort groups by average score (ascending - we want to show problem areas first)
        const sortedGroups = Object.entries(groupScores)
            .sort((a, b) => a[1] - b[1])
            .slice(0, 3);

        const summaryDiv = document.getElementById('summary-stats');
        let summaryHTML = `
                <p><strong>Total Tests:</strong> ${totalTests}</p>
                <p><strong>Average Score:</strong> ${avgScore.toFixed(1)} (${getStatusForScore(Math.round(avgScore))})</p>
                <p><strong>Groups Needing Most Attention:</strong></p>
                <ul>
            `;

        sortedGroups.forEach(([group, score]) => {
            summaryHTML += `<li>${group}: ${score.toFixed(1)} (${getStatusForScore(Math.round(score))})</li>`;
        });

        summaryHTML += '</ul>';
        summaryDiv.innerHTML = summaryHTML;
        // Create the gauge chart
        createGaugeChart(avgScore);        }
    function renderStackedBar(data, container) {
        container.innerHTML = '';
        const total = data.reduce((sum, r) => sum + r.value, 0);
        data.forEach((r, i) => {
            const seg = document.createElement('div');
            seg.className = 'bar-segment';
            seg.style.width = (r.value / total * 100) + '%';
            seg.style.background = getColorForScore(r.score);
            seg.title = `${r.label}\nValue: ${r.value}\nScore: ${r.score} (${getStatusForScore(r.score)})`;
            container.appendChild(seg);
        });
    }
    function getGrayscaleColor(score) {
        // Generate grayscale colors based on score (lighter = better, darker = worse)
        const intensity = Math.max(50, Math.min(200, 50 + (score * 15)));
        return `rgb(${intensity}, ${intensity}, ${intensity})`;
    }
    function generateRandomFingerprintData(numSegments = 5) {
        const labels = ['Security', 'Performance', 'Reliability', 'Compliance', 'Innovation'];
        const data = [];

        for (let i = 0; i < numSegments; i++) {
            data.push({
                label: labels[i] || `Metric ${i + 1}`,
                value: Math.floor(Math.random() * 50) + 10, // Random value between 10-59
                score: Math.floor(Math.random() * 10) + 1    // Random score between 1-10
            });
        }

        return data;
    }
    function generateRandomCompetitors(count = 4) {
        const competitorNames = ['Company A', 'Company B', 'Company C', 'Company D', 'Company E'];
        const competitors = [];

        for (let i = 0; i < count; i++) {
            competitors.push({
                name: competitorNames[i] || `Competitor ${i + 1}`,
                data: generateRandomFingerprintData(),
                isYourOrg: false
            });
        }

        return competitors;
    }
    function renderStackedBar(data, container, useGrayscale = false) {
        container.innerHTML = '';
        const total = data.reduce((sum, r) => sum + r.value, 0);
        data.forEach((r, i) => {
            const seg = document.createElement('div');
            seg.className = 'bar-segment';
            seg.style.width = (r.value / total * 100) + '%';

            // Use grayscale or normal colors
            if (useGrayscale) {
                seg.style.background = getGrayscaleColor(r.score);
                seg.title = `${r.label}\nValue: ${r.value}\nScore: ${r.score}`;
            } else {
                seg.style.background = getColorForScore(r.score);
                seg.title = `${r.label}\nValue: ${r.value}\nScore: ${r.score} (${getStatusForScore(r.score)})`;
            }

            container.appendChild(seg);
        });
    }
    function renderFingerprintTable() {
        const container = document.getElementById('fingerprint-rows');
        container.innerHTML = '';

        // Create array starting with your organization
        const allOrganizations = [
            {
                name: entityName,
                data: fingerprint,
                isYourOrg: true
            }
        ];

        // Add random competitors with grayscale styling
        const randomCompetitors = generateRandomCompetitors();
        allOrganizations.push(...randomCompetitors);

        // Render each organization row
        allOrganizations.forEach((org, index) => {
            const row = document.createElement('div');
            row.className = 'fingerprint-row';

            // Organization name
            const nameCell = document.createElement('div');
            nameCell.className = `entity-name-cell ${org.isYourOrg ? 'your-org' : 'competitor-org'}`;
            nameCell.textContent = org.name + (org.isYourOrg ? ' (You)' : '');

            // Average score
            const avgScore = calculateAverageScore(org.data);
            const scoreCell = document.createElement('div');
            scoreCell.className = 'score-cell';

            if (org.isYourOrg) {
                scoreCell.innerHTML = `&nbsp ${avgScore.toFixed(1)} &nbsp;<small style="color: ${getColorForScore(Math.round(avgScore))}">(${getStatusForScore(Math.round(avgScore))})</small>`;
            } else {
                // Grayscale styling for competitors
                scoreCell.innerHTML = `&nbsp ${avgScore.toFixed(1)} &nbsp;<small style="color: #666">(-)</small>`;
            }

            // Stacked bar
            const barCell = document.createElement('div');
            const barContainer = document.createElement('div');
            barContainer.className = 'stacked-bar';
            barCell.appendChild(barContainer);

            row.appendChild(nameCell);
            row.appendChild(scoreCell);
            row.appendChild(barCell);
            container.appendChild(row);

            // Render the stacked bar (grayscale for non-first organizations)
            renderStackedBar(org.data, barContainer, !org.isYourOrg);
        });
    }
    let chart;

</script>
<script>
document.addEventListener('DOMContentLoaded', async () => {

  /* Build the fragment URL from the query-string, e.g. ?report=testpart */
  const qs      = new URLSearchParams(location.search);
  const slug    = qs.get('report') || 'testpart';
  const src     = `https://hub.retrievable.ai/trialaudit/reports/${slug}.htmlpart`;

  /* Fetch – requires CORS headers from hub.retrievable.ai */
  try {
    const r = await fetch(src, { credentials: 'omit' });
    if (!r.ok) throw new Error(`HTTP ${r.status}`);
    const html = await r.text();

    /* Insert SAFE markup only */
    const mount = document.getElementById('remote-fragment');
    mount.innerHTML = DOMPurify.sanitize(html);

    /*  Optional: hydrate inline scripts that were stripped/not executed  */
    Array.from(mount.querySelectorAll('script')).forEach(s => {
      const c = document.createElement('script');
      if (s.src)      c.src = s.src;           // external file
      else            c.textContent = s.textContent;   // inline JS
      c.defer = true; document.head.appendChild(c);
    });

  } catch (e) {
    console.error(e);
    document.getElementById('remote-fragment')
            .textContent = 'Could not load the report fragment.';
  }
});
</script>

---
HTML version: https://retrievable.ai/render-test/
