import { Controller } from "@hotwired/stimulus" export default class extends Controller { static targets = ["modal", "form", "nameInput", "latitudeInput", "longitudeInput", "nearbyList", "loadingSpinner", "tagCheckboxes"] static values = { apiKey: String } connect() { this.setupEventListeners() } setupEventListeners() { document.addEventListener('place:create', (e) => { this.open(e.detail.latitude, e.detail.longitude) }) } async open(latitude, longitude) { this.latitudeInputTarget.value = latitude this.longitudeInputTarget.value = longitude this.modalTarget.classList.add('modal-open') this.nameInputTarget.focus() await this.loadNearbyPlaces(latitude, longitude) } close() { this.modalTarget.classList.remove('modal-open') this.formTarget.reset() this.nearbyListTarget.innerHTML = '' const event = new CustomEvent('place:create:cancelled') document.dispatchEvent(event) } async loadNearbyPlaces(latitude, longitude) { this.loadingSpinnerTarget.classList.remove('hidden') this.nearbyListTarget.innerHTML = '' try { const response = await fetch( `/api/v1/places/nearby?latitude=${latitude}&longitude=${longitude}&limit=5`, { headers: { 'Authorization': `Bearer ${this.apiKeyValue}` } } ) if (!response.ok) throw new Error('Failed to load nearby places') const data = await response.json() this.renderNearbyPlaces(data.places) } catch (error) { console.error('Error loading nearby places:', error) this.nearbyListTarget.innerHTML = '
Failed to load suggestions
' } finally { this.loadingSpinnerTarget.classList.add('hidden') } } renderNearbyPlaces(places) { if (!places || places.length === 0) { this.nearbyListTarget.innerHTML = 'No nearby places found
' return } const html = places.map(place => `${this.escapeHtml(place.street)}
` : ''} ${place.city ? `${this.escapeHtml(place.city)}, ${this.escapeHtml(place.country || '')}
` : ''}