@using phronCare.UIBlazor.Shared.Services
@inject IJSRuntime JS


<div class="card mt-2">
    <div class="card-header d-flex justify-content-between align-items-center">
        <span><i class="fas fa-map-marker-alt me-2"></i>Mapa de Ubicación</span>
        <div class="d-flex gap-2">
            @if (EnableAddressSearch)
            {
                <input @bind="SearchAddress"
                @bind:event="oninput"
                class="form-control form-control-sm"
                placeholder="Buscar dirección..."
                style="width: 250px;" />
                <button class="btn btn-sm btn-outline-primary" @onclick="CenterByAddress" title="Buscar">
                    <i class="fas fa-search-location"></i>
                </button>
            }
            <button class="btn btn-sm btn-outline-secondary" @onclick="OpenGoogleMaps" title="Abrir en Google Maps">
                <i class="fab fa-google me-1"></i>Ver en Google Maps
            </button>
        </div>
    </div>
    <div class="card-body p-0" style="height: 400px;">
        <div id="@MapDivId" style="height: 100%; width: 100%;"></div>
    </div>
</div>

@code {
    private string MapDivId = $"map_{Guid.NewGuid()}";
    public static PhMap? CurrentInstance { get; private set; }

    private double _latitude = -34.6037;
    private double _longitude = -58.3816;

    [Parameter]
    public double Latitude
    {
        get => _latitude;
        set => _latitude = value;
    }
    [Parameter]
    public double Longitude
    {
        get => _longitude;
        set => _longitude = value;
    }
    [Parameter] public int Zoom { get; set; } = 13;
    [Parameter] public bool EnableAddressSearch { get; set; } = true;
    [Parameter] public EventCallback<(double lat, double lng)> OnLocationChanged { get; set; }

    private string SearchAddress { get; set; } = string.Empty;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            MapInterop.RegisterInstance(this); // ✅ esto conecta con MapInterop.cs
            await Task.Delay(100);
            await JS.InvokeVoidAsync("phMap.initMap", MapDivId, Latitude, Longitude, Zoom);
        }
    }
    private async Task CenterByAddress()
    {
        if (!string.IsNullOrWhiteSpace(SearchAddress)) await JS.InvokeVoidAsync("phMap.searchAddress", MapDivId, SearchAddress);
    }
    private void OpenGoogleMaps()
    {
        var url = $"https://www.google.com/maps?q={_latitude.ToString(System.Globalization.CultureInfo.InvariantCulture)},{_longitude.ToString(System.Globalization.CultureInfo.InvariantCulture)}";
        JS.InvokeVoidAsync("window.open", url, "_blank");
    }
}
