<?php
$addrParts=[];
if(!empty($client['direccion'])) $addrParts[] = $client['direccion'];
$cpLoc = trim((string)($client['postal_code'] ?? '').' '.(string)($client['localidad'] ?? ''));
if($cpLoc) $addrParts[] = $cpLoc;
if(!empty($client['provincia'])) $addrParts[] = $client['provincia'];
$addr = trim(implode(', ', $addrParts));
?>
<div class="card shadow-sm mt-3">
  <div class="card-body">
    <div class="d-flex justify-content-between align-items-center mb-2">
      <div>
        <h6 class="mb-0">Mapa</h6>
        <div class="text-muted small">OpenStreetMap (búsqueda por dirección).</div>
      </div>
      <?php if($addr !== ''): ?>
        <a class="btn btn-sm btn-outline-primary" target="_blank"
           href="https://www.google.com/maps/search/?api=1&query=<?= urlencode($addr) ?>">
          Abrir en Google Maps
        </a>
      <?php endif; ?>
    </div>
    <div id="map"></div>
    <?php if($addr === ''): ?>
      <div class="text-muted small mt-2">Añade dirección/código postal/localidad/provincia para posicionar el mapa.</div>
    <?php endif; ?>
  </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', async () => {
  const mapEl = document.getElementById('map');
  if (!mapEl) return;
  if (typeof window.L === 'undefined') {
    mapEl.innerHTML = '<div class="text-muted">No se pudo cargar Leaflet (mapa).</div>';
    return;
  }

  const address = <?= json_encode($addr) ?>;

  const map = L.map('map', {scrollWheelZoom: false}).setView([40.4168, -3.7038], 5);
  L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    maxZoom: 19,
    attribution: '&copy; OpenStreetMap'
  }).addTo(map);

  if (!address) return;

  try {
    const url = 'https://nominatim.openstreetmap.org/search?format=json&limit=1&q=' + encodeURIComponent(address);
    const res = await fetch(url, { headers: { 'Accept': 'application/json' }});
    const data = await res.json();
    if (data && data[0]) {
      const lat = parseFloat(data[0].lat);
      const lon = parseFloat(data[0].lon);
      map.setView([lat, lon], 16);
      L.marker([lat, lon]).addTo(map).bindPopup(address).openPopup();
    }
  } catch (e) {
    console.warn('Error geocoding:', e);
  }
});
</script>
