"""H3 hex binning, metric grid aggregation, and standalone interactive map generation.

Aggregates matching residential houses into H3 hexagons (resolutions 7 & 8)
and exports GeoJSON density layers plus a self-contained interactive Folium map.
"""

from __future__ import annotations

import json
import logging
import math
import statistics
from collections import Counter
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple

import folium
from branca.element import MacroElement, Template
from folium import Element
from folium.plugins import FastMarkerCluster
import h3

logger = logging.getLogger(__name__)


def compute_median(values: List[float], default: float = 0.0, ndigits: Optional[int] = 2) -> float:
    """Safely calculate median of a numeric list."""
    clean = [v for v in values if v is not None and not math_isnan(v)]
    if not clean:
        return default
    med = float(statistics.median(clean))
    return round(med, ndigits) if ndigits is not None else med


def math_isnan(val: Any) -> bool:
    try:
        import math
        return math.isnan(float(val))
    except (TypeError, ValueError):
        return False


def get_dominant_value(values: List[str], default: str = "N/A") -> str:
    """Find the most frequent string value in a list."""
    clean = [v for v in values if v and v != "None"]
    if not clean:
        return default
    return Counter(clean).most_common(1)[0][0]


def extract_feature_bbox(feat: Dict[str, Any]) -> List[float]:
    """Extract [min_lat, min_lon, max_lat, max_lon] from a GeoJSON feature."""
    geom = feat.get("geometry") or {}
    gtype = geom.get("type", "")
    coords = geom.get("coordinates") or []
    lats: List[float] = []
    lons: List[float] = []

    if gtype == "Polygon":
        for ring in coords:
            for pt in ring:
                if len(pt) >= 2:
                    lons.append(float(pt[0]))
                    lats.append(float(pt[1]))
    elif gtype == "MultiPolygon":
        for poly in coords:
            for ring in poly:
                for pt in ring:
                    if len(pt) >= 2:
                        lons.append(float(pt[0]))
                        lats.append(float(pt[1]))

    if lats and lons:
        return [round(min(lats), 6), round(min(lons), 6), round(max(lats), 6), round(max(lons), 6)]

    props = feat.get("properties") or {}
    c_lat = float(props.get("centroid_lat") or props.get("viewpoint_lat") or 0.0)
    c_lon = float(props.get("centroid_lon") or props.get("viewpoint_lon") or 0.0)
    return [c_lat - 0.005, c_lon - 0.005, c_lat + 0.005, c_lon + 0.005]


def get_cell_latlng(cell: str) -> Tuple[float, float]:
    """Safely get (latitude, longitude) center coordinate of an H3 cell."""
    try:
        return h3.cell_to_latlng(cell)
    except AttributeError:
        return h3.h3_to_geo(cell)


def format_street_view_url(lat: float, lon: float) -> str:
    """Generate official Google Maps Street View panorama URL."""
    return f"https://www.google.com/maps/@?api=1&map_action=pano&viewpoint={lat:.6f},{lon:.6f}"


def format_street_view_html(lat: float, lon: float) -> str:
    """Generate clickable HTML link opening Street View in a new browser window/tab."""
    if not lat or not lon:
        return ""
    url = format_street_view_url(lat, lon)
    return (
        f'<a href="{url}" target="_blank" rel="noopener noreferrer" '
        f'style="color: #1a73e8; font-weight: bold; text-decoration: underline;">'
        f'🔭 Open Street View ↗</a>'
    )


def format_real_estate_search_html(postal_code: str | int | None) -> str:
    """Generate 1-click real estate portal search buttons for Swiss house listings."""
    if not postal_code:
        return ""
    pc = str(postal_code).strip()
    if not pc or pc == "0":
        return ""
    hg_url = f"https://www.homegate.ch/buy/house/zip-{pc}/matching-list"
    immo_url = f"https://www.immoscout24.ch/en/house/buy/zip-{pc}"
    return (
        f'<div style="margin-top: 6px; display: flex; gap: 8px; flex-wrap: wrap;">'
        f'<a href="{hg_url}" target="_blank" rel="noopener noreferrer" '
        f'style="display: inline-block; background: #e02424; color: #ffffff !important; padding: 4px 9px; border-radius: 4px; font-weight: 700; text-decoration: none; font-size: 11px; box-shadow: 0 1px 3px rgba(0,0,0,0.2);">'
        f'🏠 Homegate ↗</a>'
        f'<a href="{immo_url}" target="_blank" rel="noopener noreferrer" '
        f'style="display: inline-block; background: #0284c7; color: #ffffff !important; padding: 4px 9px; border-radius: 4px; font-weight: 700; text-decoration: none; font-size: 11px; box-shadow: 0 1px 3px rgba(0,0,0,0.2);">'
        f'🔍 ImmoScout24 ↗</a>'
        f'</div>'
    )



def aggregate_to_h3(
    houses: List[Dict[str, Any]],
    resolution: int = 7,
) -> List[Dict[str, Any]]:
    """Group house records into H3 hexagons and compute aggregate statistics."""
    bins: Dict[str, List[Dict[str, Any]]] = {}

    for house in houses:
        lat = house.get("lat")
        lon = house.get("lon")
        if lat is None or lon is None:
            continue
        try:
            # H3 v4 API
            cell = h3.latlng_to_cell(float(lat), float(lon), resolution)
        except AttributeError:
            # H3 v3 fallback
            cell = h3.geo_to_h3(float(lat), float(lon), resolution)
        bins.setdefault(cell, []).append(house)

    features: List[Dict[str, Any]] = []

    for cell, group in bins.items():
        try:
            # H3 v4 API
            boundary = h3.cell_to_boundary(cell)
        except AttributeError:
            # H3 v3 fallback
            boundary = h3.h3_to_geo_boundary(cell)

        # Boundary is list of (lat, lng); GeoJSON requires [[lon, lat], ...]
        coords = [[lng, lat] for lat, lng in boundary]
        if coords:
            coords.append(coords[0])  # Close polygon ring

        gardens = [h.get("estimated_garden_m2", 0.0) for h in group]
        greens = [h.get("green_ratio", 0.0) for h in group]
        densities = [h.get("local_pop_density", 0.0) for h in group]
        dwellings = [h.get("num_dwellings", 1) for h in group]
        transits = [str(h.get("ov_class", "")) for h in group]
        walk_transits = [h.get("walk_time_transit_min") for h in group if h.get("walk_time_transit_min") is not None]
        walk_rests = [h.get("walk_time_restaurant_min") for h in group if h.get("walk_time_restaurant_min") is not None]
        num_restos = [h.get("num_restaurants_nearby") for h in group if h.get("num_restaurants_nearby") is not None]
        num_cafes = [h.get("num_cafes_nearby") for h in group if h.get("num_cafes_nearby") is not None]
        walk_sms = [h.get("walk_time_supermarket_min") for h in group if h.get("walk_time_supermarket_min") is not None]
        walk_gyms = [h.get("walk_time_gym_min") for h in group if h.get("walk_time_gym_min") is not None]
        sm_brands = [str(h.get("supermarket_brand", "")) for h in group if h.get("supermarket_brand")]
        htypes = [str(h.get("house_type", "house")) for h in group]
        prices_m2 = [h.get("median_price_per_m2") for h in group if h.get("median_price_per_m2") is not None]
        house_prices = [h.get("estimated_price_chf") for h in group if h.get("estimated_price_chf") is not None]
        cadences = [h.get("transit_cadence_min") for h in group if h.get("transit_cadence_min") is not None]
        commutes = [h.get("transit_travel_time_min") for h in group if h.get("transit_travel_time_min") is not None]
        total_commutes = [h.get("total_commute_min") for h in group if h.get("total_commute_min") is not None]
        hops_list = [h.get("transit_hops") for h in group if h.get("transit_hops") is not None]
        routes = [str(h.get("transit_route_desc")) for h in group if h.get("transit_route_desc")]
        dominant_route = Counter(routes).most_common(1)[0][0] if routes else "1 bus + 1 train (1 transfer)"
        median_transit_hops = compute_median(hops_list, default=1)
        big_cities = [str(h.get("nearest_big_city", "")) for h in group if h.get("nearest_big_city")]
        dominant_big_city = Counter(big_cities).most_common(1)[0][0] if big_cities else "Zürich"
        dominant_sm = Counter(sm_brands).most_common(1)[0][0] if sm_brands else "Supermarkt"

        # Lake & Mountain Viewshed metrics
        lake_views = [h.get("has_lake_view", False) for h in group]
        lake_pcts = [h.get("lake_view_pct", 0.0) for h in group if h.get("lake_view_pct") is not None]
        visible_lakes = [str(h.get("visible_lake")) for h in group if h.get("visible_lake")]
        mountain_views = [h.get("has_mountain_view", False) for h in group]
        mountain_scores = [h.get("mountain_view_score", 0.0) for h in group if h.get("mountain_view_score") is not None]
        peaks_list = [str(h.get("visible_peaks")) for h in group if h.get("visible_peaks")]

        dominant_lake = Counter(visible_lakes).most_common(1)[0][0] if visible_lakes else None
        dominant_peaks = Counter(peaks_list).most_common(1)[0][0] if peaks_list else None
        lake_view_ratio = round(sum(1 for v in lake_views if v) / max(len(group), 1), 2)
        mountain_view_ratio = round(sum(1 for v in mountain_views if v) / max(len(group), 1), 2)
        median_lake_pct = compute_median(lake_pcts, default=0.0)
        median_mtn_score = compute_median(mountain_scores, default=0.0)

        lake_view_summary = f"{dominant_lake} ({int(median_lake_pct)}%)" if (dominant_lake and median_lake_pct >= 15.0) else "None"
        mountain_view_summary = f"{dominant_peaks} (Score {int(median_mtn_score)})" if (dominant_peaks and median_mtn_score >= 25.0) else "None"

        # Schools & Daycares
        walk_schools = [h.get("walk_time_school_min") for h in group if h.get("walk_time_school_min") is not None]
        schools = [str(h.get("nearest_school")) for h in group if h.get("nearest_school")]
        dominant_school = Counter(schools).most_common(1)[0][0] if schools else "Primary School"
        median_walk_school = compute_median(walk_schools, default=8.0)

        walk_daycares = [h.get("walk_time_daycare_min") for h in group if h.get("walk_time_daycare_min") is not None]
        access_daycares = [h.get("daycare_access_min") for h in group if h.get("daycare_access_min") is not None]
        daycares = [str(h.get("nearest_daycare")) for h in group if h.get("nearest_daycare")]
        dominant_daycare = Counter(daycares).most_common(1)[0][0] if daycares else "Daycare / Crèche"
        daycare_modes = [str(h.get("daycare_access_mode") or "walk") for h in group if h.get("daycare_access_mode")]
        dominant_dc_mode = Counter(daycare_modes).most_common(1)[0][0] if daycare_modes else "walk"
        median_walk_daycare = compute_median(walk_daycares, default=8.0)
        median_daycare_access = compute_median(access_daycares, default=8.0)

        # Quietness vs Road Safety
        quietness = [h.get("quietness_score") for h in group if h.get("quietness_score") is not None]
        road_safeties = [h.get("road_safety_score") for h in group if h.get("road_safety_score") is not None]
        dist_main_roads = [h.get("dist_to_main_road_m") for h in group if h.get("dist_to_main_road_m") is not None]
        median_quietness = compute_median(quietness, default=85.0)
        median_road_safety = compute_median(road_safeties, default=80.0)
        median_dist_main_road = compute_median(dist_main_roads, default=100.0)

        # Natural Hazard
        hazard_houses = sum(1 for h in group if h.get("in_hazard_zone"))
        hazard_free = (hazard_houses == 0)
        hazard_status = "✅ Hazard-Free Zone" if hazard_free else "⚠️ Hazard Zone"

        # Microclimate & Solar Aspect
        sun_scores = [h.get("sun_exposure_score") for h in group if h.get("sun_exposure_score") is not None]
        aspects = [str(h.get("slope_aspect")) for h in group if h.get("slope_aspect")]
        dominant_aspect = Counter(aspects).most_common(1)[0][0] if aspects else "South-West (Open Plateau)"
        median_sun_score = compute_median(sun_scores, default=75.0)
        south_facing_cnt = sum(1 for h in group if h.get("is_south_facing"))
        is_south_facing = (south_facing_cnt / max(len(group), 1)) >= 0.5

        # Municipal Taxes
        taxes = [h.get("tax_multiplier_pct") for h in group if h.get("tax_multiplier_pct") is not None]
        tax_tiers = [str(h.get("tax_tier")) for h in group if h.get("tax_tier")]
        dominant_tax_tier = Counter(tax_tiers).most_common(1)[0][0] if tax_tiers else "Moderate"
        median_tax_multiplier = compute_median(taxes, default=65.0)
        tax_summary = f"{median_tax_multiplier:.1f}% ({dominant_tax_tier})" if taxes else "N/A"

        # Postal code and real estate portal links
        postal_codes = [str(h.get("postal_code")) for h in group if h.get("postal_code")]
        dominant_postal = Counter(postal_codes).most_common(1)[0][0] if postal_codes else ""
        portal_search_html = format_real_estate_search_html(dominant_postal)

        # Airport proximity metrics
        airports = [str(h.get("nearest_airport", "")) for h in group if h.get("nearest_airport")]
        dominant_airport = Counter(airports).most_common(1)[0][0] if airports else None
        airport_dists = [h.get("dist_to_airport_km") for h in group if h.get("dist_to_airport_km") is not None]
        median_dist_airport = compute_median(airport_dists, default=15.0)
        airport_summary = f"{dominant_airport} ({median_dist_airport} km)" if dominant_airport else "None"

        # Coordinates for centroid and Street View viewpoint (centered on matching houses)
        cell_lat, cell_lon = get_cell_latlng(cell)
        house_lats = [h.get("lat") for h in group if h.get("lat") is not None]
        house_lons = [h.get("lon") for h in group if h.get("lon") is not None]
        view_lat = compute_median(house_lats, default=cell_lat, ndigits=6)
        view_lon = compute_median(house_lons, default=cell_lon, ndigits=6)

        street_view_url = format_street_view_url(view_lat, view_lon)
        google_street_view = format_street_view_html(view_lat, view_lon)

        props = {
            "cell_id": cell,
            "resolution": resolution,
            "count": len(group),
            "street_view_url": street_view_url,
            "google_street_view": google_street_view,
            "real_estate_search": portal_search_html,
            "centroid_lat": round(float(cell_lat), 6),
            "centroid_lon": round(float(cell_lon), 6),
            "viewpoint_lat": round(float(view_lat), 6),
            "viewpoint_lon": round(float(view_lon), 6),
            "postal_code": dominant_postal,
            "median_garden_m2": compute_median(gardens),
            "median_green_ratio": compute_median(greens),
            "median_dwellings": compute_median(dwellings, default=1.0),
            "median_pop_density": compute_median(densities),
            "dominant_ov_class": get_dominant_value(transits),
            "median_walk_transit_min": compute_median(walk_transits, default=5.0),
            "median_walk_restaurant_min": compute_median(walk_rests, default=5.0),
            "median_restaurants_nearby": int(compute_median(num_restos, default=0)),
            "median_cafes_nearby": int(compute_median(num_cafes, default=0)),
            "median_walk_supermarket_min": compute_median(walk_sms, default=5.0),
            "dominant_supermarket": dominant_sm,
            "median_walk_gym_min": compute_median(walk_gyms, default=10.0),
            "dominant_school": dominant_school,
            "median_walk_school_min": median_walk_school,
            "dominant_daycare": dominant_daycare,
            "median_walk_daycare_min": median_walk_daycare,
            "median_daycare_access_min": median_daycare_access,
            "dominant_daycare_mode": dominant_dc_mode,
            "median_quietness_score": median_quietness,
            "median_road_safety_score": median_road_safety,
            "median_dist_main_road_m": median_dist_main_road,
            "hazard_free": hazard_free,
            "hazard_status": hazard_status,
            "dominant_slope_aspect": dominant_aspect,
            "median_sun_exposure_score": median_sun_score,
            "is_south_facing": is_south_facing,
            "tax_multiplier_pct": median_tax_multiplier,
            "tax_tier": dominant_tax_tier,
            "tax_summary": tax_summary,
            "dominant_house_type": get_dominant_value(htypes, default="standalone"),
            "median_price_per_m2": compute_median(prices_m2, default=8800.0),
            "median_house_price_chf": compute_median(house_prices, default=1350000.0),
            "nearest_big_city": dominant_big_city,
            "median_transit_cadence_min": compute_median(cadences, default=15.0),
            "median_commute_min": compute_median(commutes, default=12.0),
            "median_total_commute_min": compute_median(total_commutes, default=16.0),
            "median_transit_hops": median_transit_hops,
            "dominant_transit_route": dominant_route,
            "has_lake_view": lake_view_ratio >= 0.5,
            "lake_view_ratio": lake_view_ratio,
            "median_lake_view_pct": median_lake_pct,
            "visible_lake": dominant_lake or "None",
            "lake_view_summary": lake_view_summary,
            "has_mountain_view": mountain_view_ratio >= 0.5,
            "mountain_view_ratio": mountain_view_ratio,
            "median_mountain_score": median_mtn_score,
            "visible_peaks": dominant_peaks or "None",
            "mountain_view_summary": mountain_view_summary,
            "nearest_airport": dominant_airport or "None",
            "median_dist_airport_km": median_dist_airport,
            "airport_summary": airport_summary,
        }

        features.append({
            "type": "Feature",
            "geometry": {
                "type": "Polygon",
                "coordinates": [coords],
            },
            "properties": props,
        })

    return features


def aggregate_to_metric_grid(
    houses: List[Dict[str, Any]],
    grid_size_m: int = 1000,
) -> List[Dict[str, Any]]:
    """Fallback 1km metric grid aggregation in Swiss LV95 (EPSG:2056)."""
    bins: Dict[Tuple[int, int], List[Dict[str, Any]]] = {}

    for h in houses:
        gkode = h.get("gkode")
        gkodn = h.get("gkodn")
        if gkode is None or gkodn is None:
            continue
        gx = int(gkode // grid_size_m * grid_size_m)
        gy = int(gkodn // grid_size_m * grid_size_m)
        bins.setdefault((gx, gy), []).append(h)

    cells: List[Dict[str, Any]] = []
    for (gx, gy), group in bins.items():
        gardens = [h.get("estimated_garden_m2", 0.0) for h in group]
        greens = [h.get("green_ratio", 0.0) for h in group]
        cells.append({
            "grid_x": gx,
            "grid_y": gy,
            "count": len(group),
            "median_garden_m2": compute_median(gardens),
            "median_green_ratio": compute_median(greens),
        })
    return cells


def load_matching_houses_geojson(geojson_path: Path) -> List[Dict[str, Any]]:
    """Load house properties and coordinates from GeoJSON."""
    if not geojson_path.exists():
        return []
    with open(geojson_path, "r", encoding="utf-8") as f:
        data = json.load(f)

    houses = []
    for feat in data.get("features", []):
        props = dict(feat.get("properties", {}))
        geom = feat.get("geometry", {})
        coords = geom.get("coordinates", [])
        if len(coords) >= 2:
            props["lon"] = coords[0]
            props["lat"] = coords[1]
        houses.append(props)
    return houses


def detect_garden_enclaves(
    houses: List[Dict[str, Any]],
    min_houses: int = 5,
    max_houses: int = 100,
    resolution: int = 9,
) -> List[Dict[str, Any]]:
    """Detect intimate urban/suburban garden enclaves (small patches of 5-100 houses)."""
    bins: Dict[str, List[Dict[str, Any]]] = {}

    for house in houses:
        lat = house.get("lat")
        lon = house.get("lon")
        if lat is None or lon is None:
            continue
        try:
            cell = h3.latlng_to_cell(float(lat), float(lon), resolution)
        except AttributeError:
            cell = h3.geo_to_h3(float(lat), float(lon), resolution)
        bins.setdefault(cell, []).append(house)

    features: List[Dict[str, Any]] = []

    for cell, group in bins.items():
        count = len(group)
        if not (min_houses <= count <= max_houses):
            continue

        try:
            boundary = h3.cell_to_boundary(cell)
        except AttributeError:
            boundary = h3.h3_to_geo_boundary(cell)

        coords = [[lng, lat] for lat, lng in boundary]
        if coords:
            coords.append(coords[0])

        streets = [str(h.get("street", "")).strip() for h in group if h.get("street")]
        street_counts = Counter(streets).most_common(4)
        top_streets = [s[0] for s in street_counts if s[0]]

        cities = [str(h.get("city", "")).strip() for h in group if h.get("city")]
        dominant_city = Counter(cities).most_common(1)[0][0] if cities else "Switzerland"

        postals = [str(h.get("postal_code", "")).strip() for h in group if h.get("postal_code")]
        dominant_postal = Counter(postals).most_common(1)[0][0] if postals else ""

        cantons = [str(h.get("canton", "")).strip() for h in group if h.get("canton")]
        dominant_canton = Counter(cantons).most_common(1)[0][0] if cantons else ""

        gardens = [h.get("estimated_garden_m2", 0.0) for h in group]
        greens = [h.get("green_ratio", 0.0) for h in group]
        walk_transits = [h.get("walk_time_transit_min") for h in group if h.get("walk_time_transit_min") is not None]
        walk_rests = [h.get("walk_time_restaurant_min") for h in group if h.get("walk_time_restaurant_min") is not None]
        num_restos = [h.get("num_restaurants_nearby") for h in group if h.get("num_restaurants_nearby") is not None]
        num_cafes = [h.get("num_cafes_nearby") for h in group if h.get("num_cafes_nearby") is not None]
        walk_sms = [h.get("walk_time_supermarket_min") for h in group if h.get("walk_time_supermarket_min") is not None]
        walk_gyms = [h.get("walk_time_gym_min") for h in group if h.get("walk_time_gym_min") is not None]
        gym_names = [str(h.get("nearest_gym", "")) for h in group if h.get("nearest_gym")]
        dominant_gym = Counter(gym_names).most_common(1)[0][0] if gym_names else "Fitnesscenter"
        sm_brands = [str(h.get("supermarket_brand", "")) for h in group if h.get("supermarket_brand")]
        dominant_sm = Counter(sm_brands).most_common(1)[0][0] if sm_brands else "Supermarkt"
        bldg_areas = [h.get("building_area_m2") for h in group if h.get("building_area_m2") is not None]

        # Schools & Daycares
        walk_schools = [h.get("walk_time_school_min") for h in group if h.get("walk_time_school_min") is not None]
        schools = [str(h.get("nearest_school")) for h in group if h.get("nearest_school")]
        dominant_school = Counter(schools).most_common(1)[0][0] if schools else "Primary School"
        median_walk_school = compute_median(walk_schools, default=8.0)

        walk_daycares = [h.get("walk_time_daycare_min") for h in group if h.get("walk_time_daycare_min") is not None]
        access_daycares = [h.get("daycare_access_min") for h in group if h.get("daycare_access_min") is not None]
        daycares = [str(h.get("nearest_daycare")) for h in group if h.get("nearest_daycare")]
        dominant_daycare = Counter(daycares).most_common(1)[0][0] if daycares else "Daycare / Crèche"
        daycare_modes = [str(h.get("daycare_access_mode") or "walk") for h in group if h.get("daycare_access_mode")]
        dominant_dc_mode = Counter(daycare_modes).most_common(1)[0][0] if daycare_modes else "walk"
        median_walk_daycare = compute_median(walk_daycares, default=8.0)
        median_daycare_access = compute_median(access_daycares, default=8.0)

        # Quietness vs Road Safety
        quietness = [h.get("quietness_score", 100.0) for h in group if h.get("quietness_score") is not None]
        road_safeties = [h.get("road_safety_score") for h in group if h.get("road_safety_score") is not None]
        dist_main_roads = [h.get("dist_to_main_road_m") for h in group if h.get("dist_to_main_road_m") is not None]
        median_quietness = compute_median(quietness, default=95.0)
        median_road_safety = compute_median(road_safeties, default=85.0)
        median_dist_main_road = compute_median(dist_main_roads, default=120.0)
        calm_lanes = sum(1 for h in group if h.get("street_typology") == "calm_lane")

        # Natural Hazard
        hazard_houses = sum(1 for h in group if h.get("in_hazard_zone"))
        hazard_free = (hazard_houses == 0)
        hazard_status = "✅ Hazard-Free Zone" if hazard_free else "⚠️ Hazard Zone"

        # Microclimate & Solar Aspect
        sun_scores = [h.get("sun_exposure_score") for h in group if h.get("sun_exposure_score") is not None]
        aspects = [str(h.get("slope_aspect")) for h in group if h.get("slope_aspect")]
        dominant_aspect = Counter(aspects).most_common(1)[0][0] if aspects else "South-West (Open Plateau)"
        median_sun_score = compute_median(sun_scores, default=75.0)
        south_facing_cnt = sum(1 for h in group if h.get("is_south_facing"))
        is_south_facing = (south_facing_cnt / max(count, 1)) >= 0.5

        # Municipal Taxes
        taxes = [h.get("tax_multiplier_pct") for h in group if h.get("tax_multiplier_pct") is not None]
        tax_tiers = [str(h.get("tax_tier")) for h in group if h.get("tax_tier")]
        dominant_tax_tier = Counter(tax_tiers).most_common(1)[0][0] if tax_tiers else "Moderate"
        median_tax_multiplier = compute_median(taxes, default=65.0)
        tax_summary = f"{median_tax_multiplier:.1f}% ({dominant_tax_tier})" if taxes else "N/A"

        # Postal code and real estate portal links
        portal_search_html = format_real_estate_search_html(dominant_postal)
        prices_m2 = [h.get("median_price_per_m2") for h in group if h.get("median_price_per_m2") is not None]
        house_prices = [h.get("estimated_price_chf") for h in group if h.get("estimated_price_chf") is not None]
        cadences = [h.get("transit_cadence_min") for h in group if h.get("transit_cadence_min") is not None]
        commutes = [h.get("transit_travel_time_min") for h in group if h.get("transit_travel_time_min") is not None]
        total_commutes = [h.get("total_commute_min") for h in group if h.get("total_commute_min") is not None]
        hops_list = [h.get("transit_hops") for h in group if h.get("transit_hops") is not None]
        routes = [str(h.get("transit_route_desc")) for h in group if h.get("transit_route_desc")]
        dominant_route = Counter(routes).most_common(1)[0][0] if routes else "1 bus + 1 train (1 transfer)"
        median_transit_hops = compute_median(hops_list, default=1)
        big_cities = [str(h.get("nearest_big_city", "")) for h in group if h.get("nearest_big_city")]
        dominant_big_city = Counter(big_cities).most_common(1)[0][0] if big_cities else "Zürich"

        # Lake & Mountain Viewshed metrics
        lake_views = [h.get("has_lake_view", False) for h in group]
        lake_pcts = [h.get("lake_view_pct", 0.0) for h in group if h.get("lake_view_pct") is not None]
        visible_lakes = [str(h.get("visible_lake")) for h in group if h.get("visible_lake")]
        mountain_views = [h.get("has_mountain_view", False) for h in group]
        mountain_scores = [h.get("mountain_view_score", 0.0) for h in group if h.get("mountain_view_score") is not None]
        peaks_list = [str(h.get("visible_peaks")) for h in group if h.get("visible_peaks")]

        dominant_lake = Counter(visible_lakes).most_common(1)[0][0] if visible_lakes else None
        dominant_peaks = Counter(peaks_list).most_common(1)[0][0] if peaks_list else None
        lake_view_ratio = round(sum(1 for v in lake_views if v) / max(count, 1), 2)
        mountain_view_ratio = round(sum(1 for v in mountain_views if v) / max(count, 1), 2)
        median_lake_pct = compute_median(lake_pcts, default=0.0)
        median_mtn_score = compute_median(mountain_scores, default=0.0)

        lake_view_summary = f"{dominant_lake} ({int(median_lake_pct)}%)" if (dominant_lake and median_lake_pct >= 15.0) else "None"
        mountain_view_summary = f"{dominant_peaks} (Score {int(median_mtn_score)})" if (dominant_peaks and median_mtn_score >= 25.0) else "None"

        # Airport proximity metrics
        airports = [str(h.get("nearest_airport", "")) for h in group if h.get("nearest_airport")]
        dominant_airport = Counter(airports).most_common(1)[0][0] if airports else None
        airport_dists = [h.get("dist_to_airport_km") for h in group if h.get("dist_to_airport_km") is not None]
        median_dist_airport = compute_median(airport_dists, default=15.0)
        airport_summary = f"{dominant_airport} ({median_dist_airport} km)" if dominant_airport else "None"

        label = f"{dominant_postal} {dominant_city}"
        if top_streets:
            label += f" ({', '.join(top_streets[:2])})"

        # Coordinates for centroid and Street View viewpoint (centered on matching houses)
        cell_lat, cell_lon = get_cell_latlng(cell)
        house_lats = [h.get("lat") for h in group if h.get("lat") is not None]
        house_lons = [h.get("lon") for h in group if h.get("lon") is not None]
        view_lat = compute_median(house_lats, default=cell_lat, ndigits=6)
        view_lon = compute_median(house_lons, default=cell_lon, ndigits=6)

        street_view_url = format_street_view_url(view_lat, view_lon)
        google_street_view = format_street_view_html(view_lat, view_lon)

        props = {
            "cell_id": cell,
            "enclave_label": label,
            "house_count": count,
            "street_view_url": street_view_url,
            "google_street_view": google_street_view,
            "real_estate_search": portal_search_html,
            "centroid_lat": round(float(cell_lat), 6),
            "centroid_lon": round(float(cell_lon), 6),
            "viewpoint_lat": round(float(view_lat), 6),
            "viewpoint_lon": round(float(view_lon), 6),
            "postal_code": dominant_postal,
            "city": dominant_city,
            "canton": dominant_canton,
            "top_streets": top_streets,
            "nearest_big_city": dominant_big_city,
            "median_garden_m2": compute_median(gardens),
            "median_green_ratio": compute_median(greens),
            "median_building_m2": compute_median(bldg_areas, default=65.0),
            "median_walk_transit_min": compute_median(walk_transits, default=3.0),
            "median_walk_restaurant_min": compute_median(walk_rests, default=4.0),
            "median_restaurants_nearby": int(compute_median(num_restos, default=0)),
            "median_cafes_nearby": int(compute_median(num_cafes, default=0)),
            "median_walk_supermarket_min": compute_median(walk_sms, default=5.0),
            "dominant_supermarket": dominant_sm,
            "median_walk_gym_min": compute_median(walk_gyms, default=10.0),
            "dominant_gym": dominant_gym,
            "dominant_school": dominant_school,
            "median_walk_school_min": median_walk_school,
            "dominant_daycare": dominant_daycare,
            "median_walk_daycare_min": median_walk_daycare,
            "median_daycare_access_min": median_daycare_access,
            "dominant_daycare_mode": dominant_dc_mode,
            "median_quietness_score": median_quietness,
            "median_road_safety_score": median_road_safety,
            "median_dist_main_road_m": median_dist_main_road,
            "hazard_free": hazard_free,
            "hazard_status": hazard_status,
            "dominant_slope_aspect": dominant_aspect,
            "median_sun_exposure_score": median_sun_score,
            "is_south_facing": is_south_facing,
            "tax_multiplier_pct": median_tax_multiplier,
            "tax_tier": dominant_tax_tier,
            "tax_summary": tax_summary,
            "calm_lanes_ratio": round(calm_lanes / max(count, 1), 2),
            "median_price_per_m2": compute_median(prices_m2, default=8800.0),
            "median_house_price_chf": compute_median(house_prices, default=1350000.0),
            "under_3m_ratio": round(sum(1 for p in house_prices if p <= 3000000.0) / max(len(house_prices), 1), 2) if house_prices else 1.0,
            "median_transit_cadence_min": compute_median(cadences, default=15.0),
            "median_commute_min": compute_median(commutes, default=12.0),
            "median_total_commute_min": compute_median(total_commutes, default=15.0),
            "median_transit_hops": median_transit_hops,
            "dominant_transit_route": dominant_route,
            "has_lake_view": lake_view_ratio >= 0.5,
            "lake_view_ratio": lake_view_ratio,
            "median_lake_view_pct": median_lake_pct,
            "visible_lake": dominant_lake or "None",
            "lake_view_summary": lake_view_summary,
            "has_mountain_view": mountain_view_ratio >= 0.5,
            "mountain_view_ratio": mountain_view_ratio,
            "median_mountain_score": median_mtn_score,
            "visible_peaks": dominant_peaks or "None",
            "mountain_view_summary": mountain_view_summary,
            "nearest_airport": dominant_airport or "None",
            "median_dist_airport_km": median_dist_airport,
            "airport_summary": airport_summary,
        }

        features.append({
            "type": "Feature",
            "geometry": {
                "type": "Polygon",
                "coordinates": [coords],
            },
            "properties": props,
        })

    return features


def generate_density_layers(
    houses: List[Dict[str, Any]],
    output_dir: Path | str = "output",
    resolutions: List[int] = (7, 8, 9),
) -> Dict[str, Path]:
    """Generate H3 GeoJSON density files and garden enclaves GeoJSON."""
    out_path = Path(output_dir)
    out_path.mkdir(parents=True, exist_ok=True)
    generated: Dict[str, Path] = {}

    for res in resolutions:
        features = aggregate_to_h3(houses, resolution=res)
        geojson_doc = {
            "type": "FeatureCollection",
            "name": f"housing_density_h3_res{res}",
            "features": features,
        }
        res_file = out_path / f"density_hex_res{res}.geojson"
        with open(res_file, "w", encoding="utf-8") as f:
            json.dump(geojson_doc, f, indent=2)
        logger.info("Saved H3 resolution %d density GeoJSON: %s (%d hexes)", res, res_file, len(features))
        generated[f"res{res}"] = res_file

    # Also detect and export intimate garden enclaves (small patches of 5-100 houses)
    enclave_features = detect_garden_enclaves(houses, min_houses=5, max_houses=100, resolution=9)
    enclave_file = out_path / "garden_enclaves.geojson"
    with open(enclave_file, "w", encoding="utf-8") as f:
        json.dump({
            "type": "FeatureCollection",
            "name": "garden_enclaves",
            "features": enclave_features,
        }, f, indent=2)
    logger.info("Saved garden enclaves GeoJSON: %s (%d enclaves)", enclave_file, len(enclave_features))
    generated["enclaves"] = enclave_file

    # Save primary density_hex.geojson (default res 7)
    primary_res = resolutions[0] if resolutions else 7
    primary_features = aggregate_to_h3(houses, resolution=primary_res)
    primary_file = out_path / "density_hex.geojson"
    with open(primary_file, "w", encoding="utf-8") as f:
        json.dump({
            "type": "FeatureCollection",
            "name": "density_hex",
            "features": primary_features,
        }, f, indent=2)
    logger.info("Saved primary density GeoJSON: %s", primary_file)
    generated["primary"] = primary_file

    # Also discover and export natural residential neighborhoods (DBSCAN + Concave Hull)
    try:
        from ch_housing.neighborhoods import discover_neighborhoods, export_neighborhoods
        neighborhood_features = discover_neighborhoods(houses, eps_m=75.0, min_houses=15, max_houses=350)
        nb_files = export_neighborhoods(neighborhood_features, output_dir=out_path)
        generated.update(nb_files)
    except Exception as e:
        logger.warning("Could not generate neighborhoods: %s", e)

    return generated


def get_color_for_count(count: int, max_count: int, log_scale: bool = True) -> str:
    """Color ramp for density hexes using logarithmic normalization (YlGnBu).
    
    Prevents highly concentrated border hexes (e.g. Basel/Geneva) from washing out
    widespread rich garden suburbs and cities like Zurich.
    """
    if count <= 0:
        return "#ffffcc"
    if log_scale and max_count > 1:
        ratio = min(1.0, math.log(count + 1) / math.log(max_count + 1))
    else:
        ratio = min(1.0, count / max(max_count, 1))

    if ratio < 0.25:
        return "#ffffcc"  # pale yellow
    elif ratio < 0.45:
        return "#a1dab4"  # soft teal
    elif ratio < 0.65:
        return "#41b6c4"  # vivid cyan teal
    elif ratio < 0.85:
        return "#225ea8"  # royal blue
    else:
        return "#081d58"  # deep navy blue


def get_color_for_price(price_per_m2: float) -> str:
    """Color ramp for price per m² (CHF) using Swiss real estate benchmarks.
    
    < 7,000 CHF/m²: #1a9850 (Affordable / Forest Green)
    7,000 - 9,500 CHF/m²: #91cf60 (Moderate / Light Green)
    9,500 - 12,000 CHF/m²: #fee08b (Medium / Warm Yellow)
    12,000 - 15,000 CHF/m²: #fc8d59 (High / Orange)
    > 15,000 CHF/m²: #d73027 (Luxury / Crimson Red)
    """
    if price_per_m2 <= 0:
        return "#91cf60"
    if price_per_m2 < 7000:
        return "#1a9850"
    elif price_per_m2 < 9500:
        return "#91cf60"
    elif price_per_m2 < 12000:
        return "#fee08b"
    elif price_per_m2 < 15000:
        return "#fc8d59"
    else:
        return "#d73027"


BASEMAP_CONFIGS: Dict[str, Dict[str, Any]] = {
    "swisstopo-gray": {
        "name": "Swisstopo Gray (Official Federal OGD)",
        "tiles": "https://wmts.geo.admin.ch/1.0.0/ch.swisstopo.pixelkarte-grau/default/current/3857/{z}/{x}/{y}.jpeg",
        "attr": '&copy; <a href="https://www.swisstopo.admin.ch/">swisstopo</a> (Federal Office of Topography)',
        "max_zoom": 19,
        "min_zoom": 7,
    },
    "swisstopo-color": {
        "name": "Swisstopo Color (Official Federal OGD)",
        "tiles": "https://wmts.geo.admin.ch/1.0.0/ch.swisstopo.pixelkarte-farbe/default/current/3857/{z}/{x}/{y}.jpeg",
        "attr": '&copy; <a href="https://www.swisstopo.admin.ch/">swisstopo</a> (Federal Office of Topography)',
        "max_zoom": 19,
        "min_zoom": 7,
    },
    "swisstopo-imagery": {
        "name": "Swisstopo SWISSIMAGE (Aerial)",
        "tiles": "https://wmts.geo.admin.ch/1.0.0/ch.swisstopo.swissimage/default/current/3857/{z}/{x}/{y}.jpeg",
        "attr": '&copy; <a href="https://www.swisstopo.admin.ch/">swisstopo</a> (Federal Office of Topography)',
        "max_zoom": 19,
        "min_zoom": 7,
    },
    "cartodb-positron": {
        "name": "CartoDB Positron (Light)",
        "tiles": "https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png",
        "attr": '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors &copy; <a href="https://carto.com/attributions">CARTO</a>',
        "max_zoom": 19,
        "min_zoom": 1,
    },
    "openstreetmap": {
        "name": "OpenStreetMap (Standard)",
        "tiles": "https://tile.openstreetmap.org/{z}/{x}/{y}.png",
        "attr": '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
        "max_zoom": 19,
        "min_zoom": 1,
    },
}


class StackingPaneSetup(MacroElement):
    """Creates dedicated Leaflet map panes to guarantee strict visual stacking order:
    hexPane (z-index 410) < enclavesPane (z-index 420) < neighborhoodsPane (z-index 430).
    
    Ensures that regardless of activation order, toggling, or resolution switching,
    the hex grid is always below enclaves, which are always below neighborhoods.
    """

    def __init__(self):
        super().__init__()
        self._template = Template("""
        {% macro script(this, kwargs) %}
            var mapObj = {{ this._parent.get_name() }};
            // Create explicit Leaflet map panes with dedicated z-indexes:
            mapObj.createPane('hexPane');
            mapObj.getPane('hexPane').style.zIndex = 410;
            
            mapObj.createPane('enclavesPane');
            mapObj.getPane('enclavesPane').style.zIndex = 420;
            
            mapObj.createPane('neighborhoodsPane');
            mapObj.getPane('neighborhoodsPane').style.zIndex = 430;
        {% endmacro %}
        """)


def build_interactive_density_map(
    houses: List[Dict[str, Any]],
    output_html_path: Path | str = "output/density_map.html",
    h3_resolution: int = 7,
    max_house_markers: int = 1500,
    default_basemap: str = "swisstopo-gray",
    include_selector: bool = False,
    neighborhood_features: Optional[List[Dict[str, Any]]] = None,
) -> Path:
    """Build a standalone, self-contained interactive Folium map with density hexes and markers.
    
    Adheres strictly to map tile policies:
    - Exclusively uses official Swiss Federal Open Government Data (wmts.geo.admin.ch): Swisstopo Gray.
    - Eliminates unauthorized/heavy automated requests to OpenStreetMap volunteer tile servers.
    - Full proper attribution is provided.
    - Selector control is removed by default for a clean presentation, but can be enabled with include_selector=True.
    """
    out_file = Path(output_html_path)
    out_file.parent.mkdir(parents=True, exist_ok=True)

    # Swiss geographic center (approx Sachseln/Kerns, OW)
    switzerland_center = [46.8182, 8.2275]
    if houses:
        lats = [h["lat"] for h in houses if "lat" in h and h["lat"]]
        lons = [h["lon"] for h in houses if "lon" in h and h["lon"]]
        if lats and lons:
            switzerland_center = [sum(lats) / len(lats), sum(lons) / len(lons)]

    # Initialize map without default tiles to configure compliant basemaps
    m = folium.Map(
        location=switzerland_center,
        zoom_start=8,
        tiles=None,
        control_scale=True,
    )

    # Establish strict visual stacking panes: hex (410) < enclaves (420) < neighborhoods (430)
    m.add_child(StackingPaneSetup())

    # Use ONLY Swisstopo Gray (Official Federal OGD) as the sole basemap
    swisstopo_cfg = BASEMAP_CONFIGS.get("swisstopo-gray", {
        "name": "Swisstopo Gray (Official Federal OGD)",
        "tiles": "https://wmts.geo.admin.ch/1.0.0/ch.swisstopo.pixelkarte-grau/default/current/3857/{z}/{x}/{y}.jpeg",
        "attr": '&copy; <a href="https://www.swisstopo.admin.ch/">swisstopo</a> (Federal Office of Topography)',
        "max_zoom": 19,
        "min_zoom": 7,
    })
    folium.TileLayer(
        tiles=swisstopo_cfg["tiles"],
        attr=swisstopo_cfg["attr"],
        name=swisstopo_cfg["name"],
        overlay=False,
        control=False,
        max_zoom=swisstopo_cfg.get("max_zoom", 19),
        min_zoom=swisstopo_cfg.get("min_zoom", 1),
    ).add_to(m)

    # 1. H3 Hex Density Layers (always build 7, 8, and 9 for interactive resolution switching)
    resolutions_to_build = [7, 8, 9]
    hex_layer_info: List[Dict[str, Any]] = []
    for res in resolutions_to_build:
        hex_features = aggregate_to_h3(houses, resolution=res)
        if not hex_features:
            continue
        max_count = max((f["properties"]["count"] for f in hex_features), default=1)
        is_default = (res == h3_resolution)
        res_label = "Regional" if res == 7 else ("Suburb" if res == 8 else "Neighborhood")

        feature_collection = {
            "type": "FeatureCollection",
            "features": hex_features,
        }

        # Dynamic color style function
        def make_hex_style(max_c: int):
            return lambda feat: {
                "fillColor": get_color_for_count(feat["properties"]["count"], max_c, log_scale=True),
                "color": "#2b5c3b",
                "weight": 1.0,
                "fillOpacity": 0.60,
            }

        hex_layer = folium.GeoJson(
            feature_collection,
            name=f"H3 Density (Res {res} - {res_label})",
            style_function=make_hex_style(max_count),
            tooltip=folium.GeoJsonTooltip(
                fields=["cell_id", "count", "dominant_house_type", "median_garden_m2", "median_price_per_m2", "median_house_price_chf", "median_commute_min", "dominant_transit_route", "median_transit_cadence_min", "median_walk_transit_min", "median_restaurants_nearby", "median_cafes_nearby", "median_walk_supermarket_min", "median_walk_gym_min", "median_walk_school_min", "median_walk_daycare_min", "median_road_safety_score", "dominant_slope_aspect", "tax_summary", "lake_view_summary", "mountain_view_summary", "airport_summary"],
                aliases=["Hex Cell:", "Matching Houses:", "Dominant Type:", "Median Garden (m²):", "💰 Price / m² (CHF):", "🏷️ Est. Price (CHF):", "🚆 Commute to City (min):", "🚆 Commute Route:", "⏱️ Day Cadence (min):", "🚶 Walk to Stop (min):", "🍽️ Dining (10m):", "☕ Cafés (10m):", "🛒 Supermarket Walk (min):", "🏋️ Gym Walk (min):", "🏫 School Walk (min):", "👶 Daycare Walk (min):", "🛡️ Road Safety (0-100):", "☀️ Microclimate / Aspect:", "🏛️ Municipal Tax:", "🌅 Lake View:", "🏔️ Mountain View:", "✈️ Airport:"],
                localize=True,
            ),
            popup=folium.GeoJsonPopup(
                fields=["cell_id", "count", "dominant_house_type", "hazard_status", "tax_summary", "dominant_slope_aspect", "median_sun_exposure_score", "median_road_safety_score", "median_quietness_score", "median_garden_m2", "median_price_per_m2", "median_house_price_chf", "nearest_big_city", "median_commute_min", "dominant_transit_route", "median_transit_cadence_min", "median_walk_transit_min", "dominant_ov_class", "median_walk_restaurant_min", "median_restaurants_nearby", "median_cafes_nearby", "median_walk_supermarket_min", "dominant_supermarket", "median_walk_gym_min", "dominant_school", "median_walk_school_min", "dominant_daycare", "median_walk_daycare_min", "lake_view_summary", "mountain_view_summary", "airport_summary", "median_pop_density", "real_estate_search"],
                aliases=["H3 Cell:", "Matching Houses:", "Dominant House Type:", "🛡️ Hazard Protection:", "🏛️ Municipal Tax:", "☀️ Microclimate / Aspect:", "☀️ Sun Exposure Score:", "🛡️ Road Safety (0-100):", "🍃 Quietness Score (0-100):", "Median Garden (m²):", "💰 Median Price/m² (CHF):", "🏷️ Est. House Price (CHF):", "Nearest Big City:", "🚆 Transit Ride (min):", "🚆 Transit Route (Max Hops):", "⏱️ Day Cadence (min):", "🚶 Walk to Stop (min):", "Transit Class:", "Restaurant Walk (min):", "🍽️ Restos & Take-Away (10m):", "☕ Cafés (10m):", "🛒 Supermarket Walk (min):", "Nearest Supermarket:", "🏋️ Walk to Gym (min):", "🏫 Nearest School:", "🏫 School Walk (min):", "👶 Nearest Daycare:", "👶 Daycare Walk (min):", "🌅 Lake View:", "🏔️ Mountain View:", "✈️ Nearest Airport:", "Local Pop Density (residents/ha):", "🏡 Real Estate Listings:"],
                max_width=540,
                min_width=440,
            ),
            show=is_default,
        )
        hex_layer.options["pane"] = "hexPane"
        hex_layer.add_to(m)
        hex_layer_info.append({
            "name": hex_layer.get_name(),
            "resolution": res,
            "maxCount": max_count,
        })

    # 2. Urban Garden Enclaves & Pockets Layer (5 to 100 Houses)
    enclaves = detect_garden_enclaves(houses, min_houses=5, max_houses=100, resolution=9)
    enclave_layer_name = None
    if enclaves:
        enclaves_fc = {
            "type": "FeatureCollection",
            "features": enclaves,
        }
        enclaves_layer = folium.GeoJson(
            enclaves_fc,
            name="🏡 Small Garden Enclaves (5-100 Houses)",
            style_function=lambda feat: {
                "fillColor": "#31a354",
                "color": "#e6550d",
                "weight": 2.2,
                "fillOpacity": 0.65,
            },
            tooltip=folium.GeoJsonTooltip(
                fields=["enclave_label", "house_count", "median_garden_m2", "median_price_per_m2", "median_house_price_chf", "nearest_big_city", "median_commute_min", "dominant_transit_route", "median_transit_cadence_min", "median_walk_transit_min", "median_restaurants_nearby", "median_cafes_nearby", "median_walk_supermarket_min", "median_walk_gym_min", "median_walk_school_min", "median_walk_daycare_min", "median_road_safety_score", "dominant_slope_aspect", "tax_summary", "lake_view_summary", "mountain_view_summary", "airport_summary", "median_quietness_score"],
                aliases=["🏡 Garden Enclave:", "Matching Houses:", "Median Garden (m²):", "💰 Price / m² (CHF):", "🏷️ Est. Price (CHF):", "Big City:", "🚆 Commute (min):", "🚆 Commute Route:", "⏱️ Cadence (min):", "🚶 Walk to Stop (min):", "🍽️ Dining (10m):", "☕ Cafés (10m):", "🛒 Supermarket Walk (min):", "🏋️ Gym Walk (min):", "🏫 School Walk (min):", "👶 Daycare Walk (min):", "🛡️ Road Safety (0-100):", "☀️ Aspect / Slope:", "🏛️ Municipal Tax:", "🌅 Lake View:", "🏔️ Mountain View:", "✈️ Airport:", "🍃 Quietness Score:"],
                localize=True,
            ),
            popup=folium.GeoJsonPopup(
                fields=["enclave_label", "house_count", "hazard_status", "tax_summary", "dominant_slope_aspect", "median_sun_exposure_score", "median_road_safety_score", "median_quietness_score", "nearest_big_city", "median_commute_min", "dominant_transit_route", "median_transit_cadence_min", "median_total_commute_min", "median_walk_transit_min", "median_garden_m2", "median_price_per_m2", "median_house_price_chf", "median_green_ratio", "median_building_m2", "median_walk_restaurant_min", "median_restaurants_nearby", "median_cafes_nearby", "median_walk_supermarket_min", "dominant_supermarket", "median_walk_gym_min", "dominant_gym", "dominant_school", "median_walk_school_min", "dominant_daycare", "median_walk_daycare_min", "lake_view_summary", "mountain_view_summary", "airport_summary", "real_estate_search"],
                aliases=["Enclave:", "Houses in Cluster:", "🛡️ Hazard Protection:", "🏛️ Municipal Tax:", "☀️ Microclimate / Aspect:", "☀️ Sun Exposure Score:", "🛡️ Road Safety (0-100):", "🍃 Quietness Score (0-100):", "Commute Target City:", "🚆 Transit Ride (min):", "🚆 Transit Route (Max Hops):", "⏱️ Day Cadence (min):", "🚪 Door-to-Door Commute (min):", "🚶 Walk to Stop (min):", "Median Garden (m²):", "💰 Median Price/m² (CHF):", "🏷️ Est. House Price (CHF):", "Green Buffer Ratio:", "Avg Building Area (m²):", "Restaurant Walk (min):", "🍽️ Restos & Take-Away (10m):", "☕ Cafés (10m):", "🛒 Supermarket Walk (min):", "Nearest Supermarket:", "🏋️ Walk to Gym (min):", "Nearest Gym / Sports:", "🏫 Nearest School:", "🏫 School Walk (min):", "👶 Nearest Daycare:", "👶 Daycare Walk (min):", "🌅 Lake View:", "🏔️ Mountain View:", "✈️ Nearest Airport:", "🏡 Real Estate Listings:"],
                max_width=540,
                min_width=440,
            ),
            show=True,
        )
        enclaves_layer.options["pane"] = "enclavesPane"
        enclaves_layer.add_to(m)
        enclave_layer_name = enclaves_layer.get_name()

    # 2b. Discovered Neighborhoods Layer (Organic Clusters via DBSCAN & Concave Hull)
    if neighborhood_features is None:
        try:
            from ch_housing.neighborhoods import discover_neighborhoods
            neighborhood_features = discover_neighborhoods(houses, eps_m=75.0, min_houses=15, max_houses=350)
        except Exception as e:
            logger.warning("Could not discover neighborhoods for map: %s", e)
            neighborhood_features = []

    # Enrich neighborhood properties with formatted display strings if needed
    for feat in (neighborhood_features or []):
        p = feat.setdefault("properties", {})
        if "hazard_status" not in p:
            p["hazard_status"] = "✅ Hazard-Free Zone" if p.get("hazard_free", True) else "⚠️ Hazard Zone"
        if "tax_summary" not in p:
            t_pct = p.get("tax_multiplier_pct")
            t_tier = p.get("tax_tier", "Moderate")
            p["tax_summary"] = f"{t_pct:.1f}% ({t_tier})" if t_pct is not None else "N/A"
        if "dominant_transit_route" not in p:
            p["dominant_transit_route"] = "Direct train (0 transfers)" if p.get("median_transit_hops", 1) == 0 else "1 bus + 1 train (1 transfer)"
        if "real_estate_search" not in p:
            p["real_estate_search"] = format_real_estate_search_html(p.get("postal_code"))

    nb_layer_name = None
    if neighborhood_features:
        nb_fc = {
            "type": "FeatureCollection",
            "features": neighborhood_features,
        }
        nb_layer = folium.GeoJson(
            nb_fc,
            name="🏘️ Discovered Neighborhoods (Organic Clusters)",
            style_function=lambda feat: {
                "fillColor": "#756bb1",
                "color": "#54278f",
                "weight": 2.2,
                "fillOpacity": 0.45,
            },
            tooltip=folium.GeoJsonTooltip(
                fields=["neighborhood_label", "house_count", "livability_score", "median_garden_m2", "median_price_per_m2", "median_house_price_chf", "nearest_big_city", "median_commute_min", "dominant_transit_route", "median_restaurants_nearby", "median_cafes_nearby", "median_walk_supermarket_min", "median_walk_gym_min", "median_walk_school_min", "median_walk_daycare_min", "median_road_safety_score", "dominant_slope_aspect", "tax_summary", "lake_view_summary", "mountain_view_summary", "median_quietness_score"],
                aliases=["🏘️ Neighborhood:", "Matching Houses:", "⭐ Livability Score:", "Median Garden (m²):", "💰 Price / m² (CHF):", "🏷️ Est. Price (CHF):", "Target City:", "🚆 Commute (min):", "🚆 Commute Route:", "🍽️ Dining (10m):", "☕ Cafés (10m):", "🛒 Supermarket Walk (min):", "🏋️ Gym Walk (min):", "🏫 School Walk (min):", "👶 Daycare Walk (min):", "🛡️ Road Safety (0-100):", "☀️ Microclimate / Aspect:", "🏛️ Municipal Tax:", "🌅 Lake View:", "🏔️ Mountain View:", "🍃 Quietness:"],
                localize=True,
            ),
            popup=folium.GeoJsonPopup(
                fields=["neighborhood_label", "house_count", "dominant_house_type", "livability_score", "hazard_status", "tax_summary", "dominant_slope_aspect", "median_sun_exposure_score", "median_road_safety_score", "median_quietness_score", "nearest_big_city", "median_commute_min", "dominant_transit_route", "median_transit_cadence_min", "median_total_commute_min", "median_walk_transit_min", "median_garden_m2", "median_green_ratio", "median_price_per_m2", "median_house_price_chf", "median_walk_restaurant_min", "median_restaurants_nearby", "median_cafes_nearby", "median_walk_supermarket_min", "dominant_supermarket", "median_walk_gym_min", "dominant_gym", "dominant_school", "median_walk_school_min", "dominant_daycare", "median_walk_daycare_min", "lake_view_summary", "mountain_view_summary", "airport_summary", "real_estate_search"],
                aliases=["Neighborhood:", "Houses in Cluster:", "Dominant Architecture:", "⭐ Livability Score (0-100):", "🛡️ Hazard Protection:", "🏛️ Municipal Tax:", "☀️ Microclimate / Aspect:", "☀️ Sun Exposure Score:", "🛡️ Road Safety (0-100):", "🍃 Quietness Score (0-100):", "Commute Target City:", "🚆 Transit Ride (min):", "🚆 Transit Route (Max Hops):", "⏱️ Day Cadence (min):", "🚪 Door-to-Door Commute (min):", "🚶 Walk to Stop (min):", "Median Garden (m²):", "Green Buffer Ratio:", "💰 Median Price/m² (CHF):", "🏷️ Est. House Price (CHF):", "Restaurant Walk (min):", "🍽️ Restos & Take-Away (10m):", "☕ Cafés (10m):", "🛒 Supermarket Walk (min):", "Nearest Supermarket:", "🏋️ Walk to Gym (min):", "Nearest Gym / Sports:", "🏫 Nearest School:", "🏫 School Walk (min):", "👶 Nearest Daycare:", "👶 Daycare Walk (min):", "🌅 Lake View:", "🏔️ Mountain View:", "✈️ Airport:", "🏡 Real Estate Listings:"],
                max_width=540,
                min_width=440,
            ),
            show=True,
        )
        nb_layer.options["pane"] = "neighborhoodsPane"
        nb_layer.add_to(m)
        nb_layer_name = nb_layer.get_name()

    # 3. Fast Marker Cluster for All Matching Houses (optional with selector)
    if include_selector:
        house_coords = [[h["lat"], h["lon"]] for h in houses if "lat" in h and "lon" in h and h["lat"] and h["lon"]]
        if house_coords:
            fmc = FastMarkerCluster(
                data=house_coords,
                name="📍 All Houses (Interactive Cluster)",
            )
            fmc.show = False
            fmc.add_to(m)

    # Prepare compact neighborhood metadata for instant client-side viewport filtering
    nb_summaries: List[Dict[str, Any]] = []
    for feat in (neighborhood_features or []):
        props = feat.get("properties") or {}
        bbox = extract_feature_bbox(feat)
        nb_summaries.append({
            "id": str(props.get("neighborhood_id", "")),
            "label": str(props.get("neighborhood_label", "")),
            "score": float(props.get("livability_score") or 0.0),
            "houses": int(props.get("house_count") or 0),
            "garden": float(props.get("median_garden_m2") or 0.0),
            "price_m2": float(props.get("median_price_per_m2") or 0.0),
            "house_price": float(props.get("median_house_price_chf") or 0.0),
            "city": str(props.get("nearest_big_city") or props.get("city") or ""),
            "commute": float(props.get("median_commute_min") or 0.0),
            "hops": int(props.get("median_transit_hops") if props.get("median_transit_hops") is not None else 1),
            "transit_route": str(props.get("dominant_transit_route") or ""),
            "gym": float(props.get("median_walk_gym_min") or 0.0),
            "dominant_gym": str(props.get("dominant_gym") or ""),
            "restaurants": int(props.get("median_restaurants_nearby") or 0),
            "cafes": int(props.get("median_cafes_nearby") or 0),
            "school": float(props.get("median_walk_school_min") or 0.0),
            "dominant_school": str(props.get("dominant_school") or ""),
            "daycare": float(props.get("median_daycare_access_min") or props.get("median_walk_daycare_min") or 0.0),
            "dominant_daycare": str(props.get("dominant_daycare") or ""),
            "daycare_mode": str(props.get("dominant_daycare_mode") or "walk"),
            "road_safety": float(props.get("median_road_safety_score") or 0.0),
            "quietness": float(props.get("median_quietness_score") or 0.0),
            "sun": float(props.get("median_sun_exposure_score") or 0.0),
            "aspect": str(props.get("dominant_slope_aspect") or ""),
            "is_south": bool(props.get("is_south_facing")),
            "tax": float(props.get("tax_multiplier_pct") or 0.0),
            "tax_tier": str(props.get("tax_tier") or ""),
            "hazard_free": bool(props.get("hazard_free", True)),
            "postal": str(props.get("postal_code") or ""),
            "lake": bool(props.get("has_lake_view")),
            "mountain": bool(props.get("has_mountain_view")),
            "lat": float(props.get("centroid_lat") or props.get("viewpoint_lat") or 0.0),
            "lon": float(props.get("centroid_lon") or props.get("viewpoint_lon") or 0.0),
            "b": bbox,
        })
    nb_summaries_json = json.dumps(nb_summaries)

    # Embed Interactive Controls Panel (Metric & Resolution Switcher) & Viewport Top 15 Panel
    nb_count_label = f"({len(neighborhood_features):,})" if neighborhood_features else ""
    toggle_html = f"""
    <style>
        .leaflet-popup-content-wrapper {{
            border-radius: 12px !important;
            box-shadow: 0 5px 25px rgba(0, 0, 0, 0.25) !important;
            padding: 2px !important;
        }}
        .leaflet-popup-content {{
            min-width: 440px !important;
            max-width: 540px !important;
            width: 460px !important;
            margin: 14px 16px 12px 16px !important;
            font-size: 12px !important;
            line-height: 1.45 !important;
        }}
        .leaflet-popup-content table {{
            width: 100% !important;
            border-collapse: collapse !important;
        }}
        .leaflet-popup-content th {{
            white-space: nowrap !important;
            color: #495057 !important;
            font-weight: 600 !important;
            padding: 5px 10px 5px 0 !important;
            border-bottom: 1px solid #f1f3f5 !important;
            vertical-align: top !important;
            width: 40% !important;
        }}
        .leaflet-popup-content td {{
            padding: 5px 0 5px 8px !important;
            border-bottom: 1px solid #f1f3f5 !important;
            vertical-align: top !important;
            color: #212529 !important;
        }}
        .nb-card {{
            background: #ffffff;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 8px 10px;
            margin-bottom: 8px;
            cursor: pointer;
            transition: all 0.15s ease-in-out;
            box-shadow: 0 1px 3px rgba(0,0,0,0.04);
            position: relative;
        }}
        .nb-card:hover {{
            border-color: #756bb1;
            box-shadow: 0 3px 10px rgba(84, 39, 143, 0.16);
            background: #faf8ff;
            transform: translateY(-1px);
        }}
        .nb-card.active {{
            border-color: #54278f;
            border-left: 4px solid #54278f;
            background: #f5f3ff;
        }}
        #viewport-nb-body::-webkit-scrollbar {{
            width: 6px;
        }}
        #viewport-nb-body::-webkit-scrollbar-track {{
            background: #f1f5f9;
            border-radius: 4px;
        }}
        #viewport-nb-body::-webkit-scrollbar-thumb {{
            background: #cbd5e1;
            border-radius: 4px;
        }}
        #viewport-nb-body::-webkit-scrollbar-thumb:hover {{
            background: #94a3b8;
        }}
        @media (max-width: 768px) {{
            #viewport-neighborhoods-panel {{
                left: 10px !important;
                top: 60px !important;
                width: calc(100vw - 20px) !important;
                max-height: 45vh !important;
            }}
        }}
    </style>

    <!-- Top 15 Viewport Neighborhoods Panel (Left Side) -->
    <div id="viewport-neighborhoods-panel" style="
        position: fixed;
        top: 12px;
        left: 56px;
        width: 330px;
        max-height: calc(100vh - 24px);
        z-index: 1000;
        background: rgba(255, 255, 255, 0.97);
        border-radius: 10px;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.22);
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
        display: flex;
        flex-direction: column;
        overflow: hidden;
        line-height: 1.35;
    ">
        <!-- Panel Header -->
        <div style="
            padding: 10px 12px;
            background: #f8fafc;
            border-bottom: 1px solid #e2e8f0;
            display: flex;
            align-items: center;
            justify-content: space-between;
            user-select: none;
        ">
            <div>
                <div style="font-weight: 700; color: #1e293b; font-size: 13px; display: flex; align-items: center; gap: 6px;">
                    <span>🏘️ Top 15 in Viewport</span>
                    <span id="viewport-nb-count-badge" style="
                        background: #ede9fe;
                        color: #5b21b6;
                        font-size: 10px;
                        font-weight: 700;
                        padding: 1px 6px;
                        border-radius: 10px;
                    ">0 in view</span>
                </div>
                <div style="font-size: 10px; color: #64748b; margin-top: 2px;">
                    Ranked by Livability Score &bull; Updates on pan/zoom
                </div>
            </div>
            <div style="display: flex; align-items: center; gap: 4px;">
                <button id="btn-reload-viewport-panel" onclick="updateViewportNeighborhoods()" style="
                    background: #ffffff;
                    border: 1px solid #cbd5e1;
                    border-radius: 4px;
                    cursor: pointer;
                    font-size: 11px;
                    color: #475569;
                    padding: 3px 6px;
                    box-shadow: 0 1px 2px rgba(0,0,0,0.05);
                    transition: all 0.15s;
                " title="Reload current viewport">🔄</button>
                <button id="btn-toggle-viewport-panel" onclick="toggleViewportPanel()" style="
                    background: #ffffff;
                    border: 1px solid #cbd5e1;
                    border-radius: 4px;
                    cursor: pointer;
                    font-size: 11px;
                    font-weight: bold;
                    color: #475569;
                    padding: 3px 8px;
                    box-shadow: 0 1px 2px rgba(0,0,0,0.05);
                    transition: all 0.15s;
                " title="Collapse / Expand panel">—</button>
            </div>
        </div>

        <!-- Scrollable Cards Body -->
        <div id="viewport-nb-body" style="
            overflow-y: auto;
            padding: 10px;
            flex: 1;
            max-height: calc(100vh - 85px);
        ">
            <div id="viewport-nb-list">
                <div style="padding: 20px 10px; text-align: center; color: #64748b; font-size: 12px;">
                    Scanning viewport...
                </div>
            </div>
        </div>
    </div>

    <!-- Metric & Resolution Controls Panel (Top Right) -->
    <div id="metric-toggle-container" style="
        position: fixed;
        top: 20px;
        right: 20px;
        z-index: 1000;
        background: rgba(255, 255, 255, 0.96);
        padding: 12px 14px;
        border-radius: 8px;
        box-shadow: 0 2px 12px rgba(0,0,0,0.25);
        font-family: Arial, sans-serif;
        font-size: 12px;
        min-width: 255px;
        line-height: 1.3;
    ">
        <!-- Layer Visibility & Stacking Order (Top to Bottom) -->
        <div style="font-weight: bold; color: #1e3a2f; margin-bottom: 6px; font-size: 11px; text-transform: uppercase; letter-spacing: 0.5px;">
            Layers & Stacking Order
        </div>
        <div style="margin-bottom: 10px;">
            <label style="display: flex; align-items: center; cursor: pointer; font-size: 11px; color: #333; margin-bottom: 5px;">
                <input type="checkbox" id="chk-neighborhoods" checked onchange="toggleNeighborhoods(this)" style="margin-right: 6px; cursor: pointer;">
                <span style="font-weight: bold; color: #54278f;">🏘️ Discovered Neighborhoods {nb_count_label}</span>
                <span style="margin-left: auto; font-size: 9px; color: #54278f; background: #f0eef7; padding: 1px 5px; border-radius: 3px; font-weight: bold;">Top</span>
            </label>
            <label style="display: flex; align-items: center; cursor: pointer; font-size: 11px; color: #333; margin-bottom: 5px;">
                <input type="checkbox" id="chk-enclaves" checked onchange="toggleEnclaves(this)" style="margin-right: 6px; cursor: pointer;">
                <span style="font-weight: bold; color: #d95f02;">🏡 Small Garden Enclaves (5-100)</span>
                <span style="margin-left: auto; font-size: 9px; color: #d95f02; background: #fff2e6; padding: 1px 5px; border-radius: 3px; font-weight: bold;">Mid</span>
            </label>
            <label style="display: flex; align-items: center; cursor: pointer; font-size: 11px; color: #333;">
                <input type="checkbox" id="chk-hexgrid" checked onchange="toggleHexGrid(this)" style="margin-right: 6px; cursor: pointer;">
                <span style="font-weight: bold; color: #225ea8;">⬡ H3 Hexagon Grid</span>
                <span style="margin-left: auto; font-size: 9px; color: #225ea8; background: #eef4fb; padding: 1px 5px; border-radius: 3px; font-weight: bold;">Base</span>
            </label>
        </div>

        <div id="hex-controls-wrapper" style="border-top: 1px solid #eee; padding-top: 8px; transition: opacity 0.2s;">
            <div style="font-weight: bold; color: #1e3a2f; margin-bottom: 6px; font-size: 11px; text-transform: uppercase; letter-spacing: 0.5px;">
                Hex Coloring
            </div>
            <div style="display: flex; gap: 6px; margin-bottom: 10px;">
                <button id="btn-metric-density" onclick="switchHexMetric('density')" style="
                    flex: 1;
                    border: none;
                    background: #225ea8;
                    color: white;
                    padding: 6px 8px;
                    border-radius: 5px;
                    cursor: pointer;
                    font-weight: bold;
                    font-size: 11px;
                    box-shadow: 0 1px 3px rgba(0,0,0,0.2);
                    transition: all 0.15s;
                ">📊 Density</button>
                <button id="btn-metric-price" onclick="switchHexMetric('price')" style="
                    flex: 1;
                    border: 1px solid #ccc;
                    background: #f8f9fa;
                    color: #333;
                    padding: 6px 8px;
                    border-radius: 5px;
                    cursor: pointer;
                    font-weight: bold;
                    font-size: 11px;
                    transition: all 0.15s;
                ">💰 Price / m²</button>
            </div>

            <div style="font-weight: bold; color: #1e3a2f; margin-bottom: 6px; font-size: 11px; text-transform: uppercase; letter-spacing: 0.5px;">
                H3 Hex Resolution
            </div>
            <div id="hex-resolution-section" style="display: flex; gap: 4px;">
                <button id="btn-res-7" onclick="switchHexResolution(7)" style="
                    flex: 1;
                    border: 1px solid #1e3a2f;
                    background: {'#1e3a2f' if h3_resolution == 7 else '#f8f9fa'};
                    color: {'white' if h3_resolution == 7 else '#333'};
                    padding: 5px 3px;
                    border-radius: 5px;
                    cursor: pointer;
                    font-weight: bold;
                    font-size: 11px;
                    transition: all 0.15s;
                ">Res 7<br><span style="font-size: 9px; font-weight: normal; opacity: 0.9;">Regional</span></button>
                <button id="btn-res-8" onclick="switchHexResolution(8)" style="
                    flex: 1;
                    border: 1px solid #ccc;
                    background: {'#1e3a2f' if h3_resolution == 8 else '#f8f9fa'};
                    color: {'white' if h3_resolution == 8 else '#333'};
                    padding: 5px 3px;
                    border-radius: 5px;
                    cursor: pointer;
                    font-weight: bold;
                    font-size: 11px;
                    transition: all 0.15s;
                ">Res 8<br><span style="font-size: 9px; font-weight: normal; opacity: 0.8;">Suburb</span></button>
                <button id="btn-res-9" onclick="switchHexResolution(9)" style="
                    flex: 1;
                    border: 1px solid #ccc;
                    background: {'#1e3a2f' if h3_resolution == 9 else '#f8f9fa'};
                    color: {'white' if h3_resolution == 9 else '#333'};
                    padding: 5px 3px;
                    border-radius: 5px;
                    cursor: pointer;
                    font-weight: bold;
                    font-size: 11px;
                    transition: all 0.15s;
                ">Res 9<br><span style="font-size: 9px; font-weight: normal; opacity: 0.8;">Local</span></button>
            </div>
        </div>
    </div>
    """
    m.get_root().html.add_child(Element(toggle_html))

    # Dynamic client-side layer recoloring and resolution switching script
    map_var_name = m.get_name()
    hex_layers_json = json.dumps(hex_layer_info)
    enclave_var_json = json.dumps(enclave_layer_name)
    nb_var_json = json.dumps(nb_layer_name)
    toggle_script = f"""
    <script>
    (function() {{
        var mapName = '{map_var_name}';
        var hexLayers = {hex_layers_json};
        var enclaveLayerName = {enclave_var_json};
        var nbLayerName = {nb_var_json};
        var allNeighborhoods = {nb_summaries_json};
        window.currentHexMetric = 'density';
        window.currentHexRes = {h3_resolution};
        window.isHexGridVisible = true;
        window.selectedNeighborhoodId = null;

        var mapInitAttempts = 0;
        var maxMapInitAttempts = 60; // 6 seconds max
        var mapInitTimer = null;

        function getDensityColor(count, maxCount) {{
            if (!count || count <= 0) return "#ffffcc";
            var ratio = Math.min(1.0, Math.log(count + 1) / Math.log(Math.max(maxCount, 2)));
            if (ratio < 0.25) return "#ffffcc";
            if (ratio < 0.45) return "#a1dab4";
            if (ratio < 0.65) return "#41b6c4";
            if (ratio < 0.85) return "#225ea8";
            return "#081d58";
        }}

        function getPriceColor(price) {{
            if (!price || price <= 0) return "#91cf60";
            if (price < 7000) return "#1a9850";
            if (price < 9500) return "#91cf60";
            if (price < 12000) return "#fee08b";
            if (price < 15000) return "#fc8d59";
            return "#d73027";
        }}

        function getMapInstance() {{
            return window[mapName] || null;
        }}

        function applyLayerStyle(layerObj) {{
            var layer = window[layerObj.name];
            if (!layer || typeof layer.setStyle !== 'function') return;
            if (window.currentHexMetric === 'price') {{
                layer.setStyle(function(feature) {{
                    var p = feature.properties ? (feature.properties.median_price_per_m2 || 0) : 0;
                    return {{
                        fillColor: getPriceColor(p),
                        color: "#4a1c1c",
                        weight: 1.0,
                        fillOpacity: 0.65
                    }};
                }});
            }} else {{
                var maxCount = layerObj.maxCount;
                layer.setStyle(function(feature) {{
                    var c = feature.properties ? (feature.properties.count || 0) : 0;
                    return {{
                        fillColor: getDensityColor(c, maxCount),
                        color: "#2b5c3b",
                        weight: 1.0,
                        fillOpacity: 0.60
                    }};
                }});
            }}
        }}

        window.toggleHexGrid = function(chk) {{
            var map = getMapInstance();
            window.isHexGridVisible = chk.checked;
            hexLayers.forEach(function(item) {{
                var layer = window[item.name];
                if (!layer || !map) return;
                if (chk.checked && item.resolution === window.currentHexRes) {{
                    if (!map.hasLayer(layer)) {{
                        map.addLayer(layer);
                    }}
                    applyLayerStyle(item);
                }} else {{
                    if (map.hasLayer(layer)) {{
                        map.removeLayer(layer);
                    }}
                }}
            }});
            var hexSection = document.getElementById('hex-controls-wrapper');
            if (hexSection) {{
                hexSection.style.opacity = chk.checked ? '1.0' : '0.45';
            }}
        }};

        window.switchHexResolution = function(targetRes) {{
            window.currentHexRes = targetRes;
            var map = getMapInstance();
            var chkHex = document.getElementById('chk-hexgrid');
            if (chkHex && !chkHex.checked) {{
                chkHex.checked = true;
                window.isHexGridVisible = true;
                var hexSection = document.getElementById('hex-controls-wrapper');
                if (hexSection) hexSection.style.opacity = '1.0';
            }}

            [7, 8, 9].forEach(function(r) {{
                var btn = document.getElementById('btn-res-' + r);
                if (btn) {{
                    if (r === targetRes) {{
                        btn.style.background = '#1e3a2f';
                        btn.style.color = '#ffffff';
                        btn.style.borderColor = '#1e3a2f';
                        btn.style.boxShadow = '0 1px 3px rgba(0,0,0,0.2)';
                    }} else {{
                        btn.style.background = '#f8f9fa';
                        btn.style.color = '#333333';
                        btn.style.borderColor = '#ccc';
                        btn.style.boxShadow = 'none';
                    }}
                }}
            }});

            hexLayers.forEach(function(item) {{
                var layer = window[item.name];
                if (!layer || !map) return;
                if (item.resolution === targetRes && window.isHexGridVisible) {{
                    if (!map.hasLayer(layer)) {{
                        map.addLayer(layer);
                    }}
                    applyLayerStyle(item);
                }} else {{
                    if (map.hasLayer(layer)) {{
                        map.removeLayer(layer);
                    }}
                }}
            }});
        }};

        window.switchHexMetric = function(metric) {{
            window.currentHexMetric = metric;
            var btnDensity = document.getElementById('btn-metric-density');
            var btnPrice = document.getElementById('btn-metric-price');
            var legDensity = document.getElementById('legend-density-section');
            var legPrice = document.getElementById('legend-price-section');

            if (metric === 'price') {{
                if (btnPrice) {{
                    btnPrice.style.background = '#d73027';
                    btnPrice.style.color = '#ffffff';
                    btnPrice.style.border = 'none';
                    btnPrice.style.boxShadow = '0 1px 3px rgba(0,0,0,0.2)';
                }}
                if (btnDensity) {{
                    btnDensity.style.background = '#f8f9fa';
                    btnDensity.style.color = '#333333';
                    btnDensity.style.border = '1px solid #ccc';
                    btnDensity.style.boxShadow = 'none';
                }}
                if (legDensity) legDensity.style.display = 'none';
                if (legPrice) legPrice.style.display = 'block';
            }} else {{
                if (btnDensity) {{
                    btnDensity.style.background = '#225ea8';
                    btnDensity.style.color = '#ffffff';
                    btnDensity.style.border = 'none';
                    btnDensity.style.boxShadow = '0 1px 3px rgba(0,0,0,0.2)';
                }}
                if (btnPrice) {{
                    btnPrice.style.background = '#f8f9fa';
                    btnPrice.style.color = '#333333';
                    btnPrice.style.border = '1px solid #ccc';
                    btnPrice.style.boxShadow = 'none';
                }}
                if (legDensity) legDensity.style.display = 'block';
                if (legPrice) legPrice.style.display = 'none';
            }}

            hexLayers.forEach(function(item) {{
                applyLayerStyle(item);
            }});

            if (nbLayerName) {{
                var nbLayer = window[nbLayerName];
                if (nbLayer && typeof nbLayer.setStyle === 'function') {{
                    if (metric === 'price') {{
                        nbLayer.setStyle(function(feature) {{
                            var p = feature.properties ? (feature.properties.median_price_per_m2 || 0) : 0;
                            return {{
                                fillColor: getPriceColor(p),
                                color: "#54278f",
                                weight: 2.5,
                                fillOpacity: 0.55
                            }};
                        }});
                    }} else {{
                        nbLayer.setStyle(function(feature) {{
                            return {{
                                fillColor: "#756bb1",
                                color: "#54278f",
                                weight: 2.2,
                                fillOpacity: 0.45
                            }};
                        }});
                    }}
                }}
            }}
        }};

        window.toggleNeighborhoods = function(chk) {{
            var map = getMapInstance();
            if (!nbLayerName) return;
            var layer = window[nbLayerName];
            if (!layer || !map) return;
            if (chk.checked) {{
                if (!map.hasLayer(layer)) {{
                    map.addLayer(layer);
                }}
            }} else {{
                if (map.hasLayer(layer)) {{
                    map.removeLayer(layer);
                }}
            }}
        }};

        window.toggleEnclaves = function(chk) {{
            var map = getMapInstance();
            if (!enclaveLayerName) return;
            var layer = window[enclaveLayerName];
            if (!layer || !map) return;
            if (chk.checked) {{
                if (!map.hasLayer(layer)) {{
                    map.addLayer(layer);
                }}
            }} else {{
                if (map.hasLayer(layer)) {{
                    map.removeLayer(layer);
                }}
            }}
        }};

        // --- Viewport Neighborhoods Engine ---
        function escapeHtml(str) {{
            if (!str) return '';
            return String(str)
                .replace(/&/g, '&amp;')
                .replace(/</g, '&lt;')
                .replace(/>/g, '&gt;')
                .replace(/"/g, '&quot;');
        }}

        window.updateViewportNeighborhoods = function() {{
            var map = getMapInstance();
            if (!map) {{
                var listEl = document.getElementById('viewport-nb-list');
                if (listEl) {{
                    listEl.innerHTML = '<div style="padding: 16px 10px; text-align: center; color: #475569; font-size: 11px;">' +
                        '<b>Map initializing...</b><br>' +
                        '<span style="font-size: 10px; color: #64748b;">Waiting for map viewport</span><br>' +
                        '<button onclick="window.setupViewportNeighborhoods(true)" style="margin-top: 8px; padding: 4px 12px; font-size: 11px; font-weight: bold; background: #54278f; color: white; border: none; border-radius: 4px; cursor: pointer;">🔄 Reload Viewport</button>' +
                        '</div>';
                }}
                return;
            }}

            var bounds;
            try {{
                bounds = map.getBounds();
            }} catch (err) {{
                console.warn('Could not get map bounds:', err);
                return;
            }}

            var south = bounds.getSouth();
            var north = bounds.getNorth();
            var west = bounds.getWest();
            var east = bounds.getEast();

            var matches = [];
            for (var i = 0; i < allNeighborhoods.length; i++) {{
                var item = allNeighborhoods[i];
                if (item.b && item.b.length === 4) {{
                    if ((item.b[2] >= south) && (item.b[0] <= north) &&
                        (item.b[3] >= west) && (item.b[1] <= east)) {{
                        matches.push(item);
                    }}
                }} else if (item.lat && item.lon) {{
                    if (item.lat >= south && item.lat <= north &&
                        item.lon >= west && item.lon <= east) {{
                        matches.push(item);
                    }}
                }}
            }}

            // Rank descending by Livability score, then house count
            matches.sort(function(a, b) {{
                if (b.score !== a.score) {{
                    return b.score - a.score;
                }}
                return b.houses - a.houses;
            }});

            var top15 = matches.slice(0, 15);
            renderNeighborhoodList(top15, matches.length);
        }};

        function renderNeighborhoodList(items, totalInView) {{
            var countBadge = document.getElementById('viewport-nb-count-badge');
            if (countBadge) {{
                countBadge.textContent = totalInView + ' in view';
            }}

            var listEl = document.getElementById('viewport-nb-list');
            if (!listEl) return;

            if (!items || items.length === 0) {{
                listEl.innerHTML = '<div style="padding: 24px 12px; text-align: center; color: #64748b; font-size: 12px;">' +
                    '<div style="font-size: 24px; margin-bottom: 6px;">🔍</div>' +
                    '<b>No neighborhoods in view</b><br>' +
                    '<span style="font-size: 11px; opacity: 0.85;">Pan or zoom out to see top neighborhoods.</span>' +
                    '</div>';
                return;
            }}

            var html = '';
            for (var i = 0; i < items.length; i++) {{
                var item = items[i];
                var rank = i + 1;
                var rankBg = rank === 1 ? '#d97706' : (rank === 2 ? '#64748b' : (rank === 3 ? '#b45309' : '#e2e8f0'));
                var rankColor = rank <= 3 ? '#ffffff' : '#334155';

                var scoreBg = '#f1f5f9';
                var scoreColor = '#334155';
                var scoreBorder = '#e2e8f0';
                if (item.score >= 80) {{
                    scoreBg = '#dcfce7'; scoreColor = '#15803d'; scoreBorder = '#bbf7d0';
                }} else if (item.score >= 60) {{
                    scoreBg = '#e0f2fe'; scoreColor = '#0369a1'; scoreBorder = '#bae6fd';
                }} else if (item.score >= 40) {{
                    scoreBg = '#fef3c7'; scoreColor = '#b45309'; scoreBorder = '#fde68a';
                }}

                var labelParts = (item.label || '').split(' - ');
                var titlePlace = labelParts[0] || 'Neighborhood';
                var streetSub = labelParts.length > 1 ? labelParts.slice(1).join(' - ') : '';

                var isActive = (window.selectedNeighborhoodId === item.id);
                var activeClass = isActive ? ' active' : '';

                var perks = '';
                if (item.lake) {{
                    perks += '<span style="background: #e0f2fe; color: #0284c7; padding: 1px 4px; border-radius: 3px; font-size: 9px; font-weight: 700; margin-left: 2px;">🌅 Lake</span>';
                }}
                if (item.mountain) {{
                    perks += '<span style="background: #f1f5f9; color: #475569; border: 1px solid #cbd5e1; padding: 0 4px; border-radius: 3px; font-size: 9px; font-weight: 700; margin-left: 2px;">🏔️ Alps</span>';
                }}
                if (item.hazard_free) {{
                    perks += '<span style="background: #ecfdf5; color: #059669; border: 1px solid #a7f3d0; padding: 0 4px; border-radius: 3px; font-size: 9px; font-weight: 700; margin-left: 2px;" title="100% Safe from Natural Hazards">🛡️ Safe</span>';
                }}
                if (item.hops === 0) {{
                    perks += '<span style="background: #f0fdf4; color: #15803d; border: 1px solid #bbf7d0; padding: 0 4px; border-radius: 3px; font-size: 9px; font-weight: 700; margin-left: 2px;" title="Direct transit to big city (0 transfers)">⚡ Direct</span>';
                }} else if (item.hops === 1) {{
                    perks += '<span style="background: #eff6ff; color: #1d4ed8; border: 1px solid #bfdbfe; padding: 0 4px; border-radius: 3px; font-size: 9px; font-weight: 700; margin-left: 2px;" title="1 transit transfer to big city (e.g. 1 bus + 1 train)">🔄 1 Hop</span>';
                }}

                var priceStr = item.price_m2 > 0 ? ('CHF ' + Math.round(item.price_m2).toLocaleString() + '/m²') : '';
                var gardenStr = item.garden > 0 ? (Math.round(item.garden).toLocaleString() + ' m²') : '';
                var hopLabel = item.hops === 0 ? ' (direct)' : ' (1 hop)';
                var commuteStr = item.commute > 0 ? (Math.round(item.commute) + 'm to ' + escapeHtml(item.city || 'city') + hopLabel) : '';
                var gymStr = item.gym > 0 ? (Math.round(item.gym) + 'm gym') : '';
                var restoStr = item.restaurants > 0 ? ('🍽️ ' + item.restaurants + ' dining') : '';
                var cafeStr = item.cafes > 0 ? ('☕ ' + item.cafes + ' cafés') : '';
                var schoolStr = item.school > 0 ? (Math.round(item.school) + 'm school') : '';
                var dcMode = item.daycare_mode ? (' (' + item.daycare_mode + ')') : '';
                var daycareStr = item.daycare > 0 ? (Math.round(item.daycare) + 'm crèche' + dcMode) : '';
                var safetyStr = item.road_safety > 0 ? ('🛡️ ' + Math.round(item.road_safety) + ' road') : '';
                var sunStr = item.sun > 0 ? ('☀️ ' + Math.round(item.sun) + ' sun') : '';
                var taxStr = item.tax > 0 ? ('🏛️ ' + Math.round(item.tax) + '% tax') : '';

                var portalBtns = '';
                if (item.postal) {{
                    var hgUrl = 'https://www.homegate.ch/buy/house/zip-' + item.postal + '/matching-list';
                    var immoUrl = 'https://www.immoscout24.ch/en/house/buy/zip-' + item.postal;
                    portalBtns = '<div style="margin-top: 5px; padding-top: 4px; border-top: 1px dashed #e2e8f0; display: flex; gap: 6px; align-items: center;" onclick="event.stopPropagation();">' +
                        '<a href="' + hgUrl + '" target="_blank" rel="noopener noreferrer" style="font-size: 9.5px; font-weight: 700; background: #e02424; color: #ffffff !important; padding: 2px 6px; border-radius: 3px; text-decoration: none;">🏠 Homegate ↗</a>' +
                        '<a href="' + immoUrl + '" target="_blank" rel="noopener noreferrer" style="font-size: 9.5px; font-weight: 700; background: #0284c7; color: #ffffff !important; padding: 2px 6px; border-radius: 3px; text-decoration: none;">🔍 ImmoScout24 ↗</a>' +
                        '</div>';
                }}

                html += '<div class="nb-card' + activeClass + '" id="card-' + item.id + '" data-id="' + item.id + '">' +
                    '<div style="display: flex; align-items: flex-start; justify-content: space-between; gap: 6px;">' +
                        '<div style="display: flex; align-items: center; gap: 6px; min-width: 0; flex: 1;">' +
                            '<span style="background: ' + rankBg + '; color: ' + rankColor + '; font-size: 10px; font-weight: 700; padding: 1px 5px; border-radius: 4px; flex-shrink: 0;">#' + rank + '</span>' +
                            '<span style="font-weight: 700; font-size: 11.5px; color: #0f172a; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;" title="' + escapeHtml(titlePlace) + '">' + escapeHtml(titlePlace) + '</span>' +
                        '</div>' +
                        '<span style="background: ' + scoreBg + '; color: ' + scoreColor + '; border: 1px solid ' + scoreBorder + '; font-size: 10.5px; font-weight: 700; padding: 1px 5px; border-radius: 4px; flex-shrink: 0;" title="Livability Score (0-100)">⭐ ' + item.score.toFixed(1) + '</span>' +
                    '</div>';

                if (streetSub) {{
                    html += '<div style="font-size: 10px; color: #64748b; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; margin-top: 2px;" title="' + escapeHtml(streetSub) + '">' + escapeHtml(streetSub) + '</div>';
                }}

                html += '<div style="display: flex; align-items: center; flex-wrap: wrap; gap: 4px; margin-top: 5px; font-size: 10px; color: #334155;">' +
                    '<span style="background: #f8fafc; padding: 1px 4px; border-radius: 3px; border: 1px solid #e2e8f0;">🏡 ' + item.houses + ' houses</span>' +
                    (gardenStr ? '<span style="background: #f8fafc; padding: 1px 4px; border-radius: 3px; border: 1px solid #e2e8f0;">🌱 ' + gardenStr + '</span>' : '') +
                    (commuteStr ? '<span style="background: #f8fafc; padding: 1px 4px; border-radius: 3px; border: 1px solid #e2e8f0;">🚆 ' + commuteStr + '</span>' : '') +
                    (schoolStr ? '<span style="background: #f8fafc; padding: 1px 4px; border-radius: 3px; border: 1px solid #e2e8f0;">🏫 ' + schoolStr + '</span>' : '') +
                    (daycareStr ? '<span style="background: #f8fafc; padding: 1px 4px; border-radius: 3px; border: 1px solid #e2e8f0;">👶 ' + daycareStr + '</span>' : '') +
                    (safetyStr ? '<span style="background: #f8fafc; padding: 1px 4px; border-radius: 3px; border: 1px solid #e2e8f0;">' + safetyStr + '</span>' : '') +
                    (sunStr ? '<span style="background: #f8fafc; padding: 1px 4px; border-radius: 3px; border: 1px solid #e2e8f0;">' + sunStr + '</span>' : '') +
                    (taxStr ? '<span style="background: #f8fafc; padding: 1px 4px; border-radius: 3px; border: 1px solid #e2e8f0;">' + taxStr + '</span>' : '') +
                    (priceStr ? '<span style="background: #f8fafc; padding: 1px 4px; border-radius: 3px; border: 1px solid #e2e8f0;">💰 ' + priceStr + '</span>' : '') +
                    (restoStr ? '<span style="background: #f8fafc; padding: 1px 4px; border-radius: 3px; border: 1px solid #e2e8f0;">' + restoStr + '</span>' : '') +
                    (cafeStr ? '<span style="background: #f8fafc; padding: 1px 4px; border-radius: 3px; border: 1px solid #e2e8f0;">' + cafeStr + '</span>' : '') +
                    (gymStr ? '<span style="background: #f8fafc; padding: 1px 4px; border-radius: 3px; border: 1px solid #e2e8f0;">🏋️ ' + gymStr + '</span>' : '') +
                    perks +
                '</div>' +
                portalBtns +
                '</div>';
            }}
            listEl.innerHTML = html;

            // Setup card interactions via event delegation on container
            var bodyEl = document.getElementById('viewport-nb-body');
            if (bodyEl && !bodyEl._hasListeners) {{
                bodyEl._hasListeners = true;
                bodyEl.addEventListener('click', function(e) {{
                    var card = e.target.closest('.nb-card');
                    if (card && card.dataset && card.dataset.id) {{
                        window.focusNeighborhood(card.dataset.id);
                    }}
                }});
                bodyEl.addEventListener('mouseover', function(e) {{
                    var card = e.target.closest('.nb-card');
                    if (card && card.dataset && card.dataset.id) {{
                        window.highlightNeighborhood(card.dataset.id, true);
                    }}
                }});
                bodyEl.addEventListener('mouseout', function(e) {{
                    var card = e.target.closest('.nb-card');
                    if (card && card.dataset && card.dataset.id) {{
                        window.highlightNeighborhood(card.dataset.id, false);
                    }}
                }});
            }}
        }}

        window.focusNeighborhood = function(nbId) {{
            window.selectedNeighborhoodId = nbId;
            var item = null;
            for (var i = 0; i < allNeighborhoods.length; i++) {{
                if (allNeighborhoods[i].id === nbId) {{
                    item = allNeighborhoods[i];
                    break;
                }}
            }}
            if (!item) return;

            var map = getMapInstance();
            if (!map) return;

            // Auto-enable neighborhood layer if turned off
            var chkNb = document.getElementById('chk-neighborhoods');
            if (chkNb && !chkNb.checked) {{
                chkNb.checked = true;
                window.toggleNeighborhoods(chkNb);
            }}

            // Update card active styles
            var allCards = document.querySelectorAll('.nb-card');
            for (var c = 0; c < allCards.length; c++) {{
                allCards[c].classList.remove('active');
            }}
            var targetCard = document.getElementById('card-' + nbId);
            if (targetCard) targetCard.classList.add('active');

            // Fit bounds or fly to center
            if (item.b && item.b.length === 4) {{
                map.fitBounds([[item.b[0], item.b[1]], [item.b[2], item.b[3]]], {{ maxZoom: 15, padding: [60, 60], animate: true }});
            }} else if (item.lat && item.lon) {{
                map.flyTo([item.lat, item.lon], 15, {{ animate: true }});
            }}

            // Open polygon popup after movement
            setTimeout(function() {{
                if (nbLayerName && window[nbLayerName] && typeof window[nbLayerName].eachLayer === 'function') {{
                    window[nbLayerName].eachLayer(function(l) {{
                        if (l.feature && l.feature.properties && l.feature.properties.neighborhood_id === nbId) {{
                            if (typeof l.openPopup === 'function') {{
                                l.openPopup();
                            }}
                        }}
                    }});
                }}
            }}, 350);
        }};

        window.highlightNeighborhood = function(nbId, isHover) {{
            if (!nbLayerName || !window[nbLayerName] || typeof window[nbLayerName].eachLayer !== 'function') return;
            window[nbLayerName].eachLayer(function(l) {{
                if (l.feature && l.feature.properties && l.feature.properties.neighborhood_id === nbId) {{
                    if (isHover) {{
                        if (typeof l.setStyle === 'function') {{
                            l.setStyle({{
                                color: '#e11d48',
                                weight: 3.5,
                                fillOpacity: 0.70
                            }});
                        }}
                        if (typeof l.bringToFront === 'function') {{
                            l.bringToFront();
                        }}
                    }} else {{
                        if (typeof l.setStyle === 'function') {{
                            if (window.currentHexMetric === 'price') {{
                                var p = (l.feature && l.feature.properties) ? (l.feature.properties.median_price_per_m2 || 0) : 0;
                                l.setStyle({{
                                    fillColor: getPriceColor(p),
                                    color: "#54278f",
                                    weight: 2.5,
                                    fillOpacity: 0.55
                                }});
                            }} else {{
                                l.setStyle({{
                                    fillColor: "#756bb1",
                                    color: "#54278f",
                                    weight: 2.2,
                                    fillOpacity: 0.45
                                }});
                            }}
                        }}
                    }}
                }}
            }});
        }};

        window.toggleViewportPanel = function() {{
            var panel = document.getElementById('viewport-neighborhoods-panel');
            var body = document.getElementById('viewport-nb-body');
            var btn = document.getElementById('btn-toggle-viewport-panel');
            if (!panel || !body || !btn) return;
            if (body.style.display === 'none') {{
                body.style.display = 'block';
                panel.style.maxHeight = 'calc(100vh - 24px)';
                btn.textContent = '—';
                btn.title = 'Collapse panel';
            }} else {{
                body.style.display = 'none';
                panel.style.maxHeight = 'auto';
                btn.textContent = '➕';
                btn.title = 'Expand panel';
            }}
        }};

        window.toggleLegendBanner = function() {{
            var content = document.getElementById('legend-banner-content');
            var btn = document.getElementById('btn-toggle-legend');
            if (!content || !btn) return;
            if (content.style.display === 'none') {{
                content.style.display = 'block';
                btn.textContent = '—';
                btn.title = 'Collapse legend';
            }} else {{
                content.style.display = 'none';
                btn.textContent = '➕';
                btn.title = 'Expand legend';
            }}
        }};

        window.setupViewportNeighborhoods = function(forceReset) {{
            if (forceReset) {{
                mapInitAttempts = 0;
                if (mapInitTimer) clearTimeout(mapInitTimer);
            }}

            var map = getMapInstance();
            if (!map) {{
                mapInitAttempts++;
                if (mapInitAttempts > maxMapInitAttempts) {{
                    var listEl = document.getElementById('viewport-nb-list');
                    if (listEl) {{
                        listEl.innerHTML = '<div style="padding: 16px 10px; text-align: center; color: #475569; font-size: 11px;">' +
                            '<b>Viewport query ready</b><br>' +
                            '<span style="font-size: 10px; color: #64748b;">Click below to load current viewport:</span><br>' +
                            '<button onclick="window.setupViewportNeighborhoods(true)" style="margin-top: 8px; padding: 4px 12px; font-size: 11px; font-weight: bold; background: #54278f; color: white; border: none; border-radius: 4px; cursor: pointer;">🔄 Reload Viewport</button>' +
                            '</div>';
                    }}
                    return;
                }}
                mapInitTimer = setTimeout(function() {{ window.setupViewportNeighborhoods(false); }}, 100);
                return;
            }}

            try {{
                map.off('moveend', window.updateViewportNeighborhoods);
                map.off('zoomend', window.updateViewportNeighborhoods);
            }} catch (e) {{}}

            map.on('moveend', window.updateViewportNeighborhoods);
            map.on('zoomend', window.updateViewportNeighborhoods);
            window.updateViewportNeighborhoods();
        }};

        // Start initialization immediately
        if (typeof requestAnimationFrame !== 'undefined') {{
            requestAnimationFrame(function() {{ window.setupViewportNeighborhoods(false); }});
        }} else {{
            setTimeout(function() {{ window.setupViewportNeighborhoods(false); }}, 10);
        }}
    }})();
    </script>
    """
    m.get_root().html.add_child(Element(toggle_script))

    # Embed Information Legend Banner (Bottom Right with collapse toggle)
    nb_legend_line = f"<b>Discovered Neighborhoods:</b> {len(neighborhood_features):,} natural clusters (15-350 houses)<br>" if neighborhood_features else ""
    legend_html = f"""
    <div id="density-legend-banner" style="
        position: fixed;
        bottom: 25px;
        right: 20px;
        z-index: 1000;
        background: rgba(255, 255, 255, 0.96);
        padding: 12px 16px;
        border-radius: 8px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.25);
        font-family: Arial, sans-serif;
        font-size: 12px;
        max-width: 360px;
        line-height: 1.45;
    ">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 4px;">
            <h4 style="margin: 0; color: #1e3a2f; font-size: 13px; font-weight: bold;">Swiss Private Housing Map</h4>
            <button id="btn-toggle-legend" onclick="toggleLegendBanner()" style="
                background: #f8fafc;
                border: 1px solid #cbd5e1;
                border-radius: 4px;
                cursor: pointer;
                font-size: 11px;
                padding: 2px 6px;
                color: #475569;
                font-weight: bold;
            " title="Collapse / Expand legend">—</button>
        </div>
        <div id="legend-banner-content">
            <b>Selection Criteria:</b> Houses (standalone, dual-family, row)<br>
            <b>Garden:</b> Yes (&ge; 100 m² &bull; &ge; 35% green buffer)<br>
            <b>Walkability:</b> &le; 10 min transit & dining &bull; &le; 20 min gym &bull; Dining & cafés nearby (10m walk)<br>
            <b>Schools & Daycares:</b> Primary school & crèche &le; 20 min (walk or transit &bull; 125 min no-gos excluded)<br>
            <b>Road Safety vs Quietness:</b> Calmed lanes (Zone 30/cul-de-sac) &bull; Setback from highways/airports<br>
            <b>Natural Hazards:</b> 100% strictly excluded (floods, torrents, scree, avalanches)<br>
            <b>Microclimate:</b> Solar exposure & slope aspect (Südhang)<br>
            <b>Municipal Taxes:</b> Municipal & cantonal tax multiplier (Steuerfuss)<br>
            <b>Supermarket:</b> Real grocer (Migros, Coop, Denner, etc. &bull; no tiny shops/gas stations)<br>
            <b>Transit Cadence:</b> &le; 15 min daytime service &bull; <b>Commute:</b> &le; 25 min &bull; <b>Max Hops:</b> &le; 1 (direct or 1 bus + 1 train)<br>
            <b>Viewshed:</b> 360° horizon clearance (Lake View & Alpine Panorama)<br>
            <b>Airport Buffer:</b> &ge; 5 km major hubs &bull; &ge; 2.5 km regional/military<br>
            <b>Total Matching Houses:</b> {len(houses):,}<br>
            {nb_legend_line}
            <b>Garden Enclaves (5-100 houses):</b> {len(enclaves):,} patches<br>
            <div id="legend-density-section" style="margin-top: 8px;">
                <b>Density Ramp (Logarithmic):</b><br>
                <div style="display: flex; align-items: center; margin-top: 4px;">
                    <span style="background: #ffffcc; border: 1px solid #ccc; width: 18px; height: 14px; display: inline-block; margin-right: 6px;"></span> Very Low
                    <span style="background: #a1dab4; border: 1px solid #ccc; width: 18px; height: 14px; display: inline-block; margin: 0 6px 0 6px;"></span> Low
                    <span style="background: #41b6c4; border: 1px solid #ccc; width: 18px; height: 14px; display: inline-block; margin: 0 6px 0 6px;"></span> Med
                    <span style="background: #225ea8; border: 1px solid #ccc; width: 18px; height: 14px; display: inline-block; margin: 0 6px 0 6px;"></span> High
                    <span style="background: #081d58; border: 1px solid #ccc; width: 18px; height: 14px; display: inline-block; margin: 0 6px 0 6px;"></span> Max
                </div>
            </div>
            <div id="legend-price-section" style="display: none; margin-top: 8px;">
                <b>Real Estate Price / m² (Swiss Average):</b><br>
                <div style="display: flex; align-items: center; margin-top: 4px; font-size: 11px;">
                    <span style="background: #1a9850; border: 1px solid #ccc; width: 16px; height: 14px; display: inline-block; margin-right: 4px;"></span> &lt;7k
                    <span style="background: #91cf60; border: 1px solid #ccc; width: 16px; height: 14px; display: inline-block; margin: 0 4px 0 6px;"></span> 7-9.5k
                    <span style="background: #fee08b; border: 1px solid #ccc; width: 16px; height: 14px; display: inline-block; margin: 0 4px 0 6px;"></span> 9.5-12k
                    <span style="background: #fc8d59; border: 1px solid #ccc; width: 16px; height: 14px; display: inline-block; margin: 0 4px 0 6px;"></span> 12-15k
                    <span style="background: #d73027; border: 1px solid #ccc; width: 16px; height: 14px; display: inline-block; margin: 0 4px 0 6px;"></span> &gt;15k CHF
                </div>
            </div>
            <div style="margin-top: 6px;">
                <span style="border: 2px solid #54278f; background: #756bb1; width: 18px; height: 14px; display: inline-block; margin-right: 6px; vertical-align: middle;"></span>
                <b>Purple Outline:</b> Discovered Neighborhood (DBSCAN + Concave Hull)<br>
                <span style="border: 2px solid #e6550d; background: #31a354; width: 18px; height: 14px; display: inline-block; margin-right: 6px; vertical-align: middle; margin-top: 4px;"></span>
                <b>Orange Outline:</b> Small Garden Enclave (5-100 houses)
            </div>
            <div style="margin-top: 8px; font-size: 11px; color: #555;">
                Basemap: <b>Swisstopo Gray</b> (Official Federal WMTS OGD)<br>
                Data: BFS GWR (houses), OSM (gastronomy & supermarkets), ARE ÖV-Güteklassen / BAV Haltestellen, STATPOP, Bauzonen
            </div>
        </div>
    </div>
    """
    m.get_root().html.add_child(Element(legend_html))

    if include_selector:
        folium.LayerControl(position="topright", collapsed=False).add_to(m)

    m.save(str(out_file))
    logger.info("Generated standalone density map: %s", out_file)
    return out_file
