"""
Yoro Widget — interactive map picker for Django forms.

Renders a text input with an embedded Leaflet map. Click on the map to
encode a location, or type a Yoro code to decode and display it.

Works in Django admin and regular forms with zero configuration.

Usage::

    from yoro.django.widgets import YoroWidget

    class MyForm(forms.Form):
        address = forms.CharField(widget=YoroWidget(domain="CI"))
"""

from __future__ import annotations

from django import forms


class YoroWidget(forms.TextInput):
    """A text input with an embedded Leaflet map for Yoro code picking.

    The widget renders:

    - A monospace text input for the Yoro code
    - A Leaflet map (click to encode, auto-decode on input)
    - Resolution and coordinate info

    All encoding/decoding happens client-side via the JavaScript codec.
    No server round-trips needed.

    Args:
        domain: ISO country code (default ``"CI"``).
        precision: Hilbert order (default ``12``).
        map_height: Height of the map in pixels (default ``300``).
        tile_url: Tile provider URL template.
        tile_attribution: Tile attribution text.
    """

    template_name = "yoro/widgets/yoro_widget.html"

    def __init__(
        self,
        domain: str = "CI",
        precision: int = 12,
        map_height: int = 300,
        tile_url: str = "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
        tile_attribution: str = "&copy; OpenStreetMap contributors",
        attrs: dict | None = None,
    ):
        self.domain = domain
        self.precision = precision
        self.map_height = map_height
        self.tile_url = tile_url
        self.tile_attribution = tile_attribution
        super().__init__(attrs=attrs)

    class Media:
        css = {
            "all": (
                "https://unpkg.com/leaflet@1.9.4/dist/leaflet.css",
                "yoro/css/yoro-widget.css",
            ),
        }
        js = (
            "https://unpkg.com/leaflet@1.9.4/dist/leaflet.js",
            "yoro/js/yoro-codec.min.js",
            "yoro/js/yoro-widget.js",
        )

    def get_context(self, name: str, value, attrs: dict) -> dict:
        context = super().get_context(name, value, attrs)
        context["widget"].update({
            "domain": self.domain,
            "precision": self.precision,
            "map_height": self.map_height,
            "tile_url": self.tile_url,
            "tile_attribution": self.tile_attribution,
        })
        return context
