"""Example script for creating a proportional symbol map (bubble map)."""

import json
import os
from geovizpy import Geoviz

# Define output directory
output_dir = os.path.join(os.path.dirname(__file__), "html")
os.makedirs(output_dir, exist_ok=True)

data_path = os.path.join(os.path.dirname(__file__), "data", "world.json")
try:
    with open(data_path) as f:
        world_data = json.load(f)
except FileNotFoundError:
    print(f"{data_path} not found.")
    world_data = {}

viz = Geoviz(projection="EqualEarth", zoomable=True)
viz.outline()
viz.graticule(stroke="white", strokeWidth=0.4)
viz.path(datum=world_data, fill="white", fillOpacity=0.4)

# Use viz.prop instead of viz.circle to get automatic legend handling
viz.prop(
    data=world_data,
    var="pop", # 'var' is used instead of 'r' in viz.prop
    fill="#f07d75",
    tip="(d) => `${d.properties.NAMEen}\n${d.properties.pop / 1000} thousands inh.`",
    leg_type="separate",
    leg_title="Population",
    leg_pos=[30, 30], # Added position to make sure it's visible
    leg_title_fontSize=15
)

pops = [f["properties"]["pop"] for f in world_data.get("features", []) if "pop" in f["properties"]]

viz.header(
    fontSize=30,
    text="A World Map With Bubbles",
    fill="#267A8A",
    fontWeight="bold",
    fontFamily="Tangerine"
)

viz.render_html(os.path.join(output_dir, "bubble.html"))
