/* global d3, responsivefy */

// D3 convention: define margin as an object called margin with these props:
let margin = {
  top: 10,
  right: 20,
  bottom: 30,
  left: 30
};
let width = 400 - margin.left - margin.right;
let height = 600 - margin.top - margin.bottom;

let svg = d3.select(".chart")
  .append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .call(responsivefy)
  .append("g")
    .attr("transform", () => `translate(${margin.left},${margin.top})`);

d3.json("data/data.json", function (err, data) {
  let yScale = d3.scaleLinear()
    .domain(d3.extent(data, d => d.expectancy))
    .range([height, 0])
    .nice();

  let yAxis = d3.axisLeft(yScale);
  svg.call(yAxis);

  let xScale = d3.scaleLinear()
    .domain(d3.extent(data, d => d.cost))
    .range([0, width])
    .nice();
  let xAxis = d3.axisBottom(xScale)
    .ticks(5);

  svg.append("g")
    .attr("transform", `translate(0, ${height})`)
    .call(xAxis);

  // To scale the area, we need the sqrt() of the value, since area = pi*r^2
  let rScale = d3.scaleSqrt()
    .domain([0, d3.max(data, d => d.population)])
    .range([0, 40]);

  let circles = svg
    .selectAll(".ball")
    .data(data)
    .enter()
    .append("g")
    .attr("class", "ball")
    .attr("transform", d => {
      return `translate(${xScale(d.cost)},${yScale(d.expectancy)})`;
    });

  circles
    .append("circle")
    // center X, center Y
    .attr("cx", 0)
    .attr("cy", 0)
    .attr("r", d => rScale(d.population));

  circles
    .append("text")
    .style("text-anchor", "middle")
    .style("fill", "black")
    .text(d => d.code)
    .attr('y', 4);

});