fallbackCopy(text));
} else { fallbackCopy(text); }
}
function fallbackCopy(text) {
const el = document.createElement('textarea');
el.value = text; el.style.position = 'fixed'; el.style.opacity = '0';
document.body.appendChild(el); el.select();
document.execCommand('copy'); document.body.removeChild(el);
}
async function openSavedRoutes() {
const modal = document.getElementById('saved-routes-modal');
modal.style.display = 'flex';
await renderSavedRoutesList();
}
async function renderSavedRoutesList() {
const listEl = document.getElementById('saved-routes-list');
listEl.innerHTML = '
Cargando...
';
if (!currentUser) return;
const { data, error } = await sbClient.from('rutas').select('*').eq('user_id', currentUser.id).order('created_at', { ascending: false });
if (error || !data || data.length === 0) {
listEl.innerHTML = '
Aún no tienes rutas guardadas.
Genera una ruta y se guardará automáticamente.
';
return;
}
listEl.innerHTML = data.map(r => `
${r.origen ? '📍 ' + r.origen + (r.destino ? ' → ' + r.destino : '') + '' : ''}
🗓️ ${new Date(r.created_at).toLocaleDateString('es-ES', {day:'numeric',month:'short',year:'numeric'})}
`).join('');
}
function startRename(id, currentTitle) {
document.getElementById('route-rename-' + id).style.display = 'block';
document.getElementById('route-title-' + id).style.display = 'none';
const input = document.getElementById('rename-input-' + id);
input.focus();
input.select();
}
function cancelRename(id) {
document.getElementById('route-rename-' + id).style.display = 'none';
document.getElementById('route-title-' + id).style.display = 'block';
}
async function saveRename(id) {
const newTitle = document.getElementById('rename-input-' + id).value.trim();
if (!newTitle) return;
try {
const { error } = await sbClient.from('rutas').update({ titulo: newTitle }).eq('id', id).eq('user_id', currentUser.id);
if (error) throw error;
document.getElementById('route-title-' + id).textContent = newTitle;
cancelRename(id);
showToast('Ruta renombrada', '✦');
} catch(e) {
showToast('Error al renombrar', '⚠️');
}
}
function confirmDeleteRoute(id, title) {
const modal = document.getElementById('delete-route-modal');
document.getElementById('delete-route-name').textContent = '"' + title + '" se eliminará permanentemente. Esta acción no se puede deshacer.';
modal.style.display = 'flex';
document.getElementById('delete-route-confirm-btn').onclick = async () => {
closeDeleteRouteModal();
try {
const { error } = await sbClient.from('rutas').delete().eq('id', id).eq('user_id', currentUser.id);
if (error) throw error;
await renderSavedRoutesList();
showToast('Ruta eliminada', '🗑️');
} catch(e) {
showToast('Error al eliminar la ruta', '⚠️');
}
};
}
function closeDeleteRouteModal() {
document.getElementById('delete-route-modal').style.display = 'none';
}
async function duplicateRoute(id, datos, title) {
try {
const { error } = await sbClient.from('rutas').insert({
user_id: currentUser.id,
titulo: title + ' (copia)',
origen: datos.origen || '',
destino: datos.destino || '',
datos: datos
});
if (error) throw error;
await renderSavedRoutesList();
showToast('Ruta duplicada', '✦');
} catch(e) {
showToast('Error al duplicar la ruta', '⚠️');
}
}
function closeSavedRoutes() {
document.getElementById('saved-routes-modal').style.display = 'none';
}
function loadSavedRoute(routeData) {
closeSavedRoutes();
lastRouteData = routeData;
allParadasData = routeData.paradas || [];
visibleCount = allParadasData.length;
// GA4: view_saved_route
const _createdAt = routeData.created_at ? new Date(routeData.created_at).getTime() : null;
const _daysSince = _createdAt ? Math.floor((Date.now() - _createdAt) / 86400000) : null;
if (typeof gtag !== 'undefined') gtag('event', 'view_saved_route', {
route_id: routeData.id || null,
days_since_creation: _daysSince,
stops_count: allParadasData.length,
user_registered: !!currentUser
});
isCircularGlobal = false;
currentModoDemo = 'roadtrip';
const result = document.getElementById('result');
result.innerHTML = `
${routeData.titulo}
📍 ${routeData.origen || ''} ${routeData.destino ? '→ ' + routeData.destino : ''}
${routeData.km_totales ? '🚗 ' + routeData.km_totales + ' km' : ''}
⏱️ ${routeData.tiempo_total_conduccion || ''}
${routeData.descripcion || ''}
`;
renderStopsList(allParadasData);
result.classList.add('visible');
const sc = document.getElementById('stops-control');
sc.classList.add('visible');
document.getElementById('stops-total').textContent = allParadasData.length;
document.getElementById('stops-showing').textContent = allParadasData.length;
document.getElementById('stops-count').textContent = visibleCount;
document.getElementById('stops-minus').disabled = visibleCount <= 1;
document.getElementById('stops-plus').disabled = true;
document.getElementById('stops-actions').classList.remove('visible');
document.getElementById('result-action-btns').style.display = 'flex';
document.getElementById('view-toggle').style.display = 'flex';
document.getElementById('map-container').style.display = 'block';
document.getElementById('result').style.display = 'none';
document.getElementById('btn-view-map').classList.add('active');
document.getElementById('btn-view-list').classList.remove('active');
setTimeout(() => initMap(allParadasData), 150);
window.scrollTo({ top: 0, behavior: 'smooth' });
}
document.addEventListener('click', function(e) {
const srModal = document.getElementById('saved-routes-modal');
if (srModal && srModal.style.display === 'flex' && e.target === srModal) closeSavedRoutes();
});
// Init tags
document.querySelectorAll('.tag').forEach(tag => {
tag.addEventListener('click', () => tag.classList.toggle('active'));
});
// ─────────────────────────────────────────────────────────────────────────