<!DOCTYPE html>
<html>

<head>
    <script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<div id="histogram-chart"></div>

<body>
    <script>
        // Create an array of age range values
        const ageData = <?php echo json_encode($genderData); ?>;
        // Sample age data (replace with your data)
        //   const ageData = [ /* Your age data here */ ];

        // Extract "Low" and "High" values and flatten them into a single array
        const ageValues = ageData.map(entry => [entry.Low, entry.High]).flat();

        // Define the histogram parameters
        const margin = {
            top: 20,
            right: 30,
            bottom: 30,
            left: 40
        };
        const width = 600 - margin.left - margin.right;
        const height = 400 - margin.top - margin.bottom;

        // Create an SVG container for the chart
        const svg = d3.select("#histogram-chart")
            .append("svg")
            .attr("width", width + margin.left + margin.right)
            .attr("height", height + margin.top + margin.bottom)
            .append("g")
            .attr("transform", `translate(${margin.left},${margin.top})`);

        // Set the number of bins and the range of ages
        const numBins = 10;
        const ageRange = [0, 100]; // Modify the range based on your data

        // Create a histogram function
        const histogram = d3.histogram()
            .domain(ageRange)
            .thresholds(d3.range(ageRange[0], ageRange[1], (ageRange[1] - ageRange[0]) / numBins));

        // Compute the histogram bins
        const bins = histogram(ageValues);

        // Define a color scale for the bins
        const colorScale = d3.scaleSequential(d3.interpolateBlues)
            .domain([0, d3.max(bins, d => d.length)]);

        // Define x and y scales
        const x = d3.scaleLinear()
            .domain([ageRange[0], ageRange[1]])
            .range([0, width]);

        const y = d3.scaleLinear()
            .domain([0, d3.max(bins, d => d.length)])
            .nice()
            .range([height, 0]);

        // Create and style the histogram bars
        svg.selectAll("rect")
            .data(bins)
            .enter()
            .append("rect")
            .attr("x", d => x(d.x0))
            .attr("y", d => y(d.length))
            .attr("width", d => x(d.x1) - x(d.x0))
            .attr("height", d => height - y(d.length))
            .attr("fill", d => colorScale(d.length));
        // Define scales for x and y axes
       
        // Create x and y axes
        const xAxis = d3.axisBottom(x);
        const yAxis = d3.axisLeft(y);

        // Append the x and y axes to the chart
        svg.append("g")
            .attr("class", "x-axis")
            .attr("transform", `translate(0,${height})`)
            .call(xAxis);

        svg.append("g")
            .attr("class", "y-axis")
            .call(yAxis);
    </script>
</body>

</html>
