<svg id="posBarchart"></svg>

<script>
    // Define variables only in JavaScript
    const barChartWidth = 1000;
    const barChartHeight = 750;
    const margin = { top: 20, right: 30, bottom: 50, left: 50 };

    // Ensure posList exists before processing
    var posData = [];

    <#if posList?? && posList?size gt 0>
    <#list posList as token>
    posData.push({ pos: "${token.text}", count: ${token.pos} });
    </#list>
    <#else>
    posData.push({ pos: "No Data", count: 0 });
    </#if>

    console.log("Final POS Data being used:", posData);

    var svg = d3.select("#posBarchart")
        .attr("width", barChartWidth)
        .attr("height", barChartHeight);

    // Create Scales
    var xScale = d3.scaleBand()
        .domain(posData.map(d => d.pos))
        .range([margin.left, barChartWidth - margin.right])
        .padding(0.2);

    var yScale = d3.scaleLinear()
        .domain([0, d3.max(posData, d => d.count)])
        .nice()
        .range([barChartHeight - margin.bottom, margin.top]);

    var colorScale = d3.scaleOrdinal(d3.schemeCategory10);

    // Create Bars
    var bars = svg.selectAll("rect")
        .data(posData)
        .enter().append("rect")
        .attr("x", d => xScale(d.pos))
        .attr("y", d => yScale(d.count))
        .attr("width", xScale.bandwidth())
        .attr("height", d => Math.max(0, barChartHeight - margin.bottom - yScale(d.count))) // Prevents negative heights
        .attr("fill", d => colorScale(d.pos));

    console.log("Number of bars created:", bars.size());

    // X Axis
    svg.append("g")
        .attr("transform", "translate(0," + (barChartHeight - margin.bottom) + ")")
        .call(d3.axisBottom(xScale))
        .selectAll("text")
        .attr("transform", "rotate(-45)")
        .style("text-anchor", "end")
        .style("font-size", "12px");

    // Y Axis
    svg.append("g")
        .attr("transform", "translate(" + margin.left + ",0)")
        .call(d3.axisLeft(yScale));

    // Labels
    svg.selectAll("text.label")
        .data(posData)
        .enter().append("text")
        .attr("class", "label")
        .attr("x", d => xScale(d.pos) + xScale.bandwidth() / 2)
        .attr("y", d => yScale(d.count) - 5)
        .attr("text-anchor", "middle")
        .attr("fill", "#000")
        .text(d => d.count);
</script>



