/* ============================================================
BAN YARO — Orte (Hundefreundliche Orte)
Karte + Liste, Eigene Orte anlegen/bearbeiten
============================================================ */
window.Page_places = (() => {
let _container = null;
let _appState = null;
let _map = null;
let _markers = [];
let _data = [];
let _activeTyp = null; // null = alle
let _search = '';
let _userPos = null;
// ----------------------------------------------------------
// Typen-Konfiguration
// ----------------------------------------------------------
const TYPEN = {
restaurant: { icon: '', label: 'Restaurant & Café', color: '#F97316' },
freilauf: { icon: '', label: 'Freilauffläche', color: '#22C55E' },
shop: { icon: '', label: 'Shop', color: '#3B82F6' },
kotbeutel: { icon: '', label: 'Kotbeutel-Station', color: '#84A98C' },
tierarzt: { icon: '', label: 'Tierarzt', color: '#EF4444' },
hundeschule: { icon: '', label: 'Hundeschule', color: '#8B5CF6' },
};
// _esc ersetzt durch UI.escape()
// ----------------------------------------------------------
// INIT
// ----------------------------------------------------------
async function init(container, appState) {
_container = container;
_appState = appState;
_render();
_loadData();
try { _userPos = await API.getLocation(); } catch {}
}
function refresh() { _loadData(); }
function onDogChange() {}
// ----------------------------------------------------------
// RENDER — Grundstruktur
// ----------------------------------------------------------
function _render() {
_container.innerHTML = `
`;
// Events
document.getElementById('places-filter').addEventListener('click', e => {
const btn = e.target.closest('.places-filter-btn');
if (!btn) return;
document.querySelectorAll('.places-filter-btn').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
_activeTyp = btn.dataset.typ || null;
_applyFilter();
});
document.getElementById('places-add-btn').addEventListener('click', () => {
if (!_appState.user) {
UI.toast.warning('Bitte zuerst anmelden.');
App.navigate('settings');
return;
}
_showForm(null);
});
// Suche mit Debounce
let _searchTimer = null;
document.getElementById('places-search')?.addEventListener('input', e => {
clearTimeout(_searchTimer);
_searchTimer = setTimeout(() => {
_search = e.target.value.trim().toLowerCase();
_applyFilter();
}, 300);
});
UI.loadLeaflet().then(_initMap);
}
// ----------------------------------------------------------
// Karte initialisieren
// ----------------------------------------------------------
function _initMap() {
const el = document.getElementById('places-map');
if (!el || !window.L || _map) return;
const center = _userPos ? [_userPos.lat, _userPos.lon] : [51.1657, 10.4515];
const zoom = _userPos ? 13 : 6;
_map = L.map('places-map', { zoomControl: true, attributionControl: false })
.setView(center, zoom);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 19 })
.addTo(_map);
// GPS-Locate-Button
L.Control.Locate = L.Control.extend({
onAdd() {
const btn = L.DomUtil.create('button', 'places-locate-btn');
btn.innerHTML = '';
btn.title = 'Meinen Standort';
btn.onclick = async () => {
try {
const pos = await API.getLocation({ enableHighAccuracy: true });
_userPos = pos;
_map.setView([pos.lat, pos.lon], 14);
} catch { UI.toast.error('Standort konnte nicht ermittelt werden.'); }
};
return btn;
},
onRemove() {},
});
new L.Control.Locate({ position: 'bottomright' }).addTo(_map);
_renderMarkers();
}
// ----------------------------------------------------------
// Daten laden
// ----------------------------------------------------------
async function _loadData() {
try {
_data = await API.places.list();
_renderList();
_renderMarkers();
} catch (err) {
UI.toast.error(err.message || 'Fehler beim Laden der Orte.');
}
}
// ----------------------------------------------------------
// Filter anwenden
// ----------------------------------------------------------
function _filtered() {
let list = _activeTyp ? _data.filter(p => p.typ === _activeTyp) : _data;
if (_search) {
const q = _search;
list = list.filter(p =>
(p.name || '').toLowerCase().includes(q) ||
(p.adresse|| '').toLowerCase().includes(q) ||
(p.typ || '').toLowerCase().includes(q)
);
}
return list;
}
function _applyFilter() {
_renderList();
_renderMarkers();
}
// ----------------------------------------------------------
// Marker rendern
// ----------------------------------------------------------
function _renderMarkers() {
if (!_map || !window.L) return;
_markers.forEach(m => m.remove());
_markers = [];
_filtered().forEach(place => {
const t = TYPEN[place.typ] || { icon: '', color: '#6B7280' };
const marker = UI.leafletMarker({ lat: place.lat, lon: place.lon, color: t.color, icon: t.icon, size: 34 })
.addTo(_map)
.on('click', () => _openDetail(place));
_markers.push(marker);
});
}
// ----------------------------------------------------------
// Liste rendern
// ----------------------------------------------------------
function _renderList() {
const list = document.getElementById('places-list');
if (!list) return;
const items = _filtered();
if (!items.length) {
const msg = _search
? `Keine Orte gefunden für „${UI.escape(_search)}".`
: (_activeTyp ? 'Keine Orte in dieser Kategorie.' : 'Noch keine Orte eingetragen.');
list.innerHTML = `
`;
return;
}
list.innerHTML = `
${items.map(p => _cardHTML(p)).join('')}
`;
list.querySelectorAll('.places-card').forEach(card => {
const id = parseInt(card.dataset.id);
const place = _data.find(p => p.id === id);
if (place) card.addEventListener('click', () => _openDetail(place));
});
}
function _cardHTML(p) {
const t = TYPEN[p.typ] || { icon: '', label: p.typ, color: '#6B7280' };
const flags = [
p.hund_rein === true ? `${UI.icon('dog')} Hund rein` : null,
p.leine_pflicht === true ? `${UI.icon('tag')} Leinenpflicht` : null,
p.wasser_fuer_hunde === true ? `${UI.icon('drop')} Wasser` : null,
].filter(Boolean);
return `
${t.icon}
${UI.escape(p.name)}
${t.label}
${p.adresse ? `· ${UI.escape(p.adresse)}` : ''}
${flags.length ? `
${flags.map(f => `${f}`).join('')}
` : ''}
${UI.icon('arrow-right')}
`;
}
// ----------------------------------------------------------
// Detail-Modal
// ----------------------------------------------------------
function _openDetail(place) {
const t = TYPEN[place.typ] || { icon: '', label: place.typ, color: '#6B7280' };
const isOwn = _appState.user?.id === place.user_id;
const flags = [
place.hund_rein === true ? `${UI.icon('dog')} Hund erlaubt` : (place.hund_rein === false ? `${UI.icon('x')} Kein Hund` : null),
place.leine_pflicht === true ? `${UI.icon('tag')} Leinenpflicht` : (place.leine_pflicht === false ? `${UI.icon('check')} Leine optional` : null),
place.wasser_fuer_hunde === true ? `${UI.icon('drop')} Wasser vorhanden`: null,
].filter(Boolean);
const body = `
${t.icon}
${UI.escape(place.name)}
${t.label}
${place.adresse ? `${UI.icon('map-pin')} ${UI.escape(place.adresse)}
` : ''}
${place.telefon ? `${UI.icon('phone')} ${UI.escape(place.telefon)}
` : ''}
${place.website ? `${UI.icon('arrow-square-out')} ${UI.escape(place.website)}
` : ''}
${flags.length ? `${flags.map(f => `${f}`).join('')}
` : ''}
Eingetragen von ${UI.escape(place.user_name || 'Unbekannt')}
`;
const footer = isOwn ? `
` : `
`;
UI.modal.open({ title: `${t.icon} ${UI.escape(place.name)}`, body, footer });
UI.ratingStars({
containerId: `place-rating-${place.id}`,
targetType: 'place',
targetId: place.id,
isLoggedIn: !!_appState.user,
});
document.getElementById('place-detail-close')?.addEventListener('click', UI.modal.close);
document.getElementById('place-detail-edit')?.addEventListener('click', () => {
UI.modal.close();
_showForm(place);
});
// Auf Karte zentrieren
if (_map) _map.setView([place.lat, place.lon], 15);
}
// ----------------------------------------------------------
// Formular — Ort anlegen / bearbeiten
// ----------------------------------------------------------
function _showForm(place) {
const isEdit = !!place;
const typOpts = Object.entries(TYPEN)
.map(([k, t]) => ``)
.join('');
const body = `
`;
const footer = `
${isEdit ? `` : ''}
`;
UI.modal.open({ title: isEdit ? `${UI.escape(place.name)} bearbeiten` : ' Neuer Ort', body, footer });
document.getElementById('place-form-cancel')?.addEventListener('click', UI.modal.close);
document.getElementById('place-form-delete')?.addEventListener('click', async () => {
const ok = await UI.modal.confirm({
title: 'Ort löschen?', message: `„${place.name}" wird dauerhaft entfernt.`, confirmText: 'Löschen', danger: true,
});
if (!ok) return;
try {
await API.places.delete(place.id);
_data = _data.filter(p => p.id !== place.id);
UI.modal.close();
_renderList();
_renderMarkers();
UI.toast.success('Ort gelöscht.');
} catch (err) { UI.toast.error(err.message || 'Fehler.'); }
});
// Location-Picker initialisieren
const _picker = UI.locationPicker({ containerId: 'pf-location-picker' });
if (place?.lat && place?.lon) {
_picker.setValue(place.lat, place.lon, null);
}
document.getElementById('place-form')?.addEventListener('submit', async e => {
e.preventDefault();
const btn = document.querySelector('[form="place-form"][type="submit"]') || e.target.querySelector('[type="submit"]');
const fd = UI.formData(e.target);
const loc = _picker.getValue();
if (!loc.lat || !loc.lon) {
UI.toast.warning('Bitte GPS-Position ermitteln.');
return;
}
await UI.asyncButton(btn, async () => {
const payload = {
name: fd.name?.trim(),
typ: fd.typ,
lat: loc.lat,
lon: loc.lon,
adresse: fd.adresse || null,
website: fd.website || null,
telefon: fd.telefon || null,
hund_rein: 'hund_rein' in fd,
leine_pflicht: 'leine_pflicht' in fd,
wasser_fuer_hunde: 'wasser_fuer_hunde' in fd,
};
if (isEdit) {
const updated = await API.places.update(place.id, payload);
const idx = _data.findIndex(p => p.id === place.id);
if (idx !== -1) _data[idx] = updated;
UI.toast.success('Gespeichert.');
} else {
const created = await API.places.create(payload);
_data.unshift(created);
UI.toast.success('Ort hinzugefügt!');
}
UI.modal.close();
_renderList();
_renderMarkers();
});
});
}
return { init, refresh, onDogChange };
})();