// Live data voor de voorbeeldsite: weer + sneeuw (Open-Meteo, gratis, geen sleutel) en een echte kaart (Leaflet + OpenStreetMap).
// Valt terug op voorbeelddata als een bron niet bereikbaar is.
(() => {
const NS = window.VakantiehuisplatformDesignSystem_2f09bb;
const { WeatherCard, Photo } = NS;
const DAYS = ['zo', 'ma', 'di', 'wo', 'do', 'vr', 'za'];
const icon = c => c === 0 || c === 1 ? 'sun' : c === 2 ? 'cloud-sun' : c === 3 ? 'cloud' : c === 45 || c === 48 ? 'cloud-fog' : (c >= 71 && c <= 77) || c === 85 || c === 86 ? 'cloud-snow' : c >= 95 ? 'cloud-lightning' : (c >= 51 && c <= 67) || (c >= 80 && c <= 82) ? 'cloud-rain' : 'cloud';
const cm = m => Math.round((m || 0) * 100) + ' cm';
// Ligging per site via vhS('weather'); standaard Trattenbach.
const W = () => window.vhS('weather', { lat: 47.2525, lon: 12.0747, elev: 885, tz: 'Europe/Vienna', label: 'Wald im Pinzgau, 885 m', mtn: { lat: 47.2067, lon: 12.1003, elev: 2300, label: '2.300 m' } });
const BASE = () => 'https://api.open-meteo.com/v1/forecast?timezone=' + encodeURIComponent(W().tz || 'auto');
let cache = null;
function loadWeather() {
  if (cache) return cache;
  const w = W();
  const valley = fetch(BASE() + '&latitude=' + w.lat + '&longitude=' + w.lon + (w.elev ? '&elevation=' + w.elev : '') + '&daily=weather_code,temperature_2m_max,temperature_2m_min,snowfall_sum&current=snow_depth&forecast_days=5').then(r => { if (!r.ok) throw new Error(r.status); return r.json(); });
  const mountain = w.mtn ? fetch(BASE() + '&latitude=' + w.mtn.lat + '&longitude=' + w.mtn.lon + '&elevation=' + w.mtn.elev + '&current=snow_depth').then(r => r.ok ? r.json() : null).catch(() => null) : Promise.resolve(null);
  cache = Promise.all([valley, mountain]).then(([v, mt]) => {
    const d = v.daily;
    const fresh = Math.round(d.snowfall_sum[0] || 0);
    const time = (v.current && v.current.time || '').slice(11, 16);
    return X => ({ days: d.time.map((t, i) => ({ day: i === 0 ? X.today : X.days[new Date(t + 'T12:00').getDay()], icon: icon(d.weather_code[i]), max: Math.round(d.temperature_2m_max[i]), min: Math.round(d.temperature_2m_min[i]) })), snow: w.mtn ? { valley: cm(v.current && v.current.snow_depth), mountain: mt && mt.current ? cm(mt.current.snow_depth) + ' (' + w.mtn.label + ')' : X.unknown, fresh: X.fresh(fresh) } : null, updated: 'Live · ' + time });
  });
  cache.catch(() => { cache = null; });
  return cache;
}
function LiveWeather({ empty, style, lang }) {
  const X = window.VH_I18N ? window.VH_I18N.T(lang || 'nl') : null;
  const [w, setW] = React.useState(null);
  const [failed, setFailed] = React.useState(false);
  React.useEffect(() => { let on = true; loadWeather().then(x => on && setW(() => x)).catch(() => on && setFailed(true)); return () => { on = false; }; }, []);
  const loc = W();
  if (w) { const f = w(X); return <WeatherCard location={loc.label} days={f.days} snow={f.snow} updated={f.updated} style={style} />; }
  return <WeatherCard location={loc.label} empty={empty} snow={loc.mtn ? undefined : null} updated={failed ? X.sample : X.loading} style={style} />;
}

// Kaart: Leaflet 1.9.4 van cdnjs, tegels van OpenStreetMap.
const LEAFLET = 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/';
let leafletP = null;
function loadLeaflet() {
  if (window.L) return Promise.resolve(window.L);
  if (leafletP) return leafletP;
  leafletP = new Promise((res, rej) => {
    const css = document.createElement('link'); css.rel = 'stylesheet'; css.href = LEAFLET + 'leaflet.min.css'; document.head.appendChild(css);
    const s = document.createElement('script'); s.src = LEAFLET + 'leaflet.min.js'; s.onload = () => res(window.L); s.onerror = rej; document.head.appendChild(s);
  });
  leafletP.catch(() => { leafletP = null; });
  return leafletP;
}
function LiveMap({ ratio = '16/10', places }) {
  const ref = React.useRef(null);
  const [failed, setFailed] = React.useState(false);
  React.useEffect(() => {
    let map = null, on = true;
    loadLeaflet().then(L => {
      if (!on || !ref.current) return;
      map = L.map(ref.current, { scrollWheelZoom: false, attributionControl: true });
      L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 18, attribution: '© OpenStreetMap' }).addTo(map);
      const accent = getComputedStyle(ref.current).getPropertyValue('--accent').trim() || '#1e5a4c';
      const pin = (color, size) => L.divIcon({ className: '', html: '<span style="display:block;width:' + size + 'px;height:' + size + 'px;border-radius:50%;background:' + color + ';border:3px solid #fff;box-shadow:0 1px 4px rgba(0,0,0,.4)"></span>', iconSize: [size, size], iconAnchor: [size / 2, size / 2] });
      const house = window.vhHouse();
      const pts = [];
      L.marker(house.coords, { icon: pin(accent, 22), title: house.name }).addTo(map).bindPopup('<strong>' + house.name + '</strong><br>' + window.VH_I18N.ui('Ligging bij benadering'));
      pts.push(house.coords);
      (places || []).filter(p => p.coords).forEach(p => {
        const m = L.marker(p.coords, { icon: pin('#444', 14), title: p.name }).addTo(map);
        const div = document.createElement('div'); const b = document.createElement('strong'); b.textContent = p.name; div.appendChild(b); div.appendChild(document.createElement('br')); div.appendChild(document.createTextNode(p.category)); m.bindPopup(div);
        pts.push(p.coords);
      });
      map.fitBounds(pts, { padding: [28, 28], maxZoom: 13 });
    }).catch(() => on && setFailed(true));
    return () => { on = false; if (map) map.remove(); };
  }, [places && places.map(p => p.name).join('|')]);
  if (failed) return <Photo ratio={ratio} label={window.VH_I18N.ui('Kaart kon niet laden')} />;
  return <div ref={ref} role="region" aria-label="Kaart van de omgeving" style={{ aspectRatio: ratio, width: '100%', borderRadius: 'var(--radius-photo, var(--radius-lg))', overflow: 'hidden', background: 'var(--surface-sunken)', zIndex: 0, position: 'relative' }}></div>;
}
Object.assign(window, { VHLiveWeather: LiveWeather, VHLiveMap: LiveMap });
})();
