// Function to load data and render the chart
function renderViz() {
  // 1. Load your uploaded data.json file
  d3.json('data.json').then(data => {
    
    // Define shared encoding properties and scales
    const x_scale = { domain: [0.5, 7.5] };
    const y_scale = { domain: [40, 85] };
    const size_scale = { range: [20, 300] };

    // 2. Base Layer (For Size Legend - Hollow Gray Circles)
    const baseLayer = {
      mark: { type: 'circle', opacity: 1, fill: null, stroke: 'gray' },
      encoding: {
        x: { field: 'fertility', type: 'quantitative', scale: x_scale },
        y: { field: 'life_expect', type: 'quantitative', scale: y_scale },
        size: { 
          field: 'pop', 
          type: 'quantitative', 
          scale: size_scale, 
          legend: { title: 'pop' } // Show legend for size
        }
      }
    };

    // 3. Main Layer (For Color Encoding - Colored Hollow Circles)
    const mainLayer = {
      mark: { type: 'circle', opacity: 0.7, fill: null },
      encoding: {
        x: { field: 'fertility', type: 'quantitative', scale: x_scale },
        y: { field: 'life_expect', type: 'quantitative', scale: y_scale },
        stroke: { 
          field: 'cluster', 
          type: 'nominal', 
          legend: { title: 'cluster' } // Show legend for color
        },
        size: { 
          field: 'pop', 
          type: 'quantitative', 
          scale: size_scale, 
          legend: null // Hide redundant size legend
        },
        tooltip: [
          { field: 'country', type: 'nominal' },
          { field: 'year', type: 'ordinal' },
          { field: 'fertility', type: 'quantitative' },
          { field: 'life_expect', type: 'quantitative' },
          { field: 'pop', type: 'quantitative' },
          { field: 'cluster', type: 'nominal' }
        ]
      }
    };

    // 4. Combine layers and properties
    const vlSpec = {
      $schema: 'https://vega.github.io/schema/vega-lite/v5.json',
      data: { values: data }, // Bind the loaded data
      layer: [baseLayer, mainLayer], // Layer the two charts
      config: {
        // Optional configuration for styling
        view: { stroke: null }
      },
      // Set chart size
      width: 700,
      height: 500
    };

    // 5. Embed the visualization into the HTML container
    vegaEmbed('#vis', vlSpec);

  }).catch(error => {
    console.error('Error loading data or rendering visualization:', error);
  });
}

// Run the render function when the script loads
renderViz();