import { Controller } from "@hotwired/stimulus" export default class extends Controller { connect() { this.setupVoteButtons() } setupVoteButtons() { document.querySelectorAll('.vote-btn').forEach(button => { button.addEventListener('click', this.handleVote.bind(this)) }) } async handleVote(event) { const button = event.currentTarget const votableType = button.dataset.votableType const votableId = button.dataset.votableId const action = button.dataset.action try { const response = await fetch('/votes', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]').content }, body: JSON.stringify({ votable_type: votableType, votable_id: votableId, vote_type: action }) }) const data = await response.json() if (data.success) { this.updateVoteCounts(data) } else { alert(data.message) } } catch (error) { console.error('Vote error:', error) } } updateVoteCounts(data) { document.getElementById('upvotes-count').textContent = data.upvotes document.getElementById('downvotes-count').textContent = data.downvotes } }