import folium
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors

def plot_coordinates(df, lat_feature="lat", lon_feature="lon", color_feature=None):
    """
    Plots points from a DataFrame on a Folium map.

    Parameters:
        df (pd.DataFrame): DataFrame containing coordinates and optional feature for color.
        lat_feature (str): Name of the latitude column.
        lon_feature (str): Name of the longitude column.
        color_feature (str or None): Column name for coloring points. If None, all points are one color.

    Returns:
        folium.Map: Folium map object with plotted points.
    """

    center_lat = df[lat_feature].median()
    center_lon = df[lon_feature].median()

    m = folium.Map(location=[center_lat, center_lon], zoom_start=10)

    if color_feature:
        unique_values = df[color_feature].unique()
        cmap = plt.get_cmap("tab20")
        colors = {val: mcolors.to_hex(cmap(i % 20)) for i, val in enumerate(unique_values)}
    else:
        colors = {"default": "blue"}

    for _, row in df.iterrows():
        if color_feature:
            color = colors[row[color_feature]]
        else:
            color = colors["default"]
        folium.CircleMarker(
            location=(row[lat_feature], row[lon_feature]),
            radius=5,
            color=color,
            fill=True,
            fill_color=color,
            fill_opacity=0.7
        ).add_to(m)

    return m