
Private Bootstouren auf dem Comer See.
Eine originale Piantoni Derby Super von 1969, bis zu fünf Gäste und ich am Steuer.
- GruppePrivat, bis zu fünf Personen
- PreisPro Gruppe, nicht pro Person
- InklusiveTreibstoff, Wasser und Prosecco (10,5 % vol.), ab 2 Stunden ohne Limit
- StornierungKostenlos bis 24 Stunden vorher
- An BordEnglisch, Italienisch, Spanisch
Sommer auf dem See,
im Winter gebucht.
Buchen Sie vor dem 31. Dezember, zahlen Sie den vollen Betrag und erhalten Sie -15 % auf jede Tour der Saison 2027 (März bis Oktober). Auch für Hochzeiten und Heiratsanträge.
Ein Boot, eine Gruppe: Wer früh bucht, wählt Tag und Uhrzeit.
Vollständige Zahlung bei der Buchung. Fester Termin in der Saison 2027 (1. März bis 31. Oktober). Nicht erstattbar, außer bei schlechtem Wetter: volle Rückerstattung oder ein neuer Termin, wenn er für uns beide passt. Endet am 31. Dezember 2026 um 23:59 Uhr (italienische Zeit).

Gutscheine · Saison 2027
Ein Tag auf dem See, zum Verschenken.
Verschenken Sie eine meiner Touren, von einer Stunde bis zu einem ganzen Tag auf dem Wasser. Der Gutschein gilt für die ganze Saison 2027: Die Beschenkten wählen den Termin, um den Rest kümmere ich mich.
- Ab 380 € pro Gruppe, bis zu fünf Gäste
- Gültig vom 1. März bis 31. Oktober 2027
- Sie zahlen online und erhalten den Gutschein per E-Mail, fertig zum Verschenken
Touren · Saison 2027
Ein bis sechs Stunden, immer privat.
Prosecco ohne Limit ab zwei Stunden.
Preis pro Gruppe mit bis zu fünf Gästen. Bei jeder Tour inklusive: das Boot, der Kapitän, Treibstoff und Wasser. Auch Prosecco (10,5 % vol.): eine Flasche bei der 1-Stunden-Tour, ohne Limit ab zwei Stunden. Wir starten in Varenna, Bellagio oder Menaggio, wie es Ihnen passt. Sie wohnen woanders am See? Fragen Sie mich.







Der Kapitän
Ich bin Emiliano.
Ich stehe am Steuer.
Seit 2024 nehme ich Gäste mit auf den Comer See. An Bord erzähle ich Ihnen, welche Villa welche ist und wer dort gelebt hat, empfehle Plätze zum Baden oder zum Mittagessen und helfe bei den Fotos, wenn Sie möchten.
Manche Gruppen plaudern die ganze Fahrt, andere genießen lieber in Ruhe den Blick. Beides ist in Ordnung. Sie bestimmen die Stimmung, ich kümmere mich um das Boot und die Zeit.
Stay gold.
Das Boot
Ein Original von 1969:
Piantoni Derby Super.
Keine Replik. Lackiertes Mahagoni, türkisfarbene Sitze, Platz für fünf. Wer sich im Winter um das Boot kümmert, steht im Sommer am Steuer.

Hochzeiten & Anlässe
Das Boot für die Momente dazwischen.
Ankunft und Abfahrt über das Wasser, Fotoshootings, Heiratsanträge. Eine Flasche Moët & Chandon an Bord. Hochzeitsplaner willkommen.

Auf der Karte planen
Schon einen Ort
im Sinn??
Erkunden Sie die Karte und fügen Sie die Orte hinzu, die Sie sehen möchten. Sie zeigt Ihnen eine geschätzte Route und Dauer; ich prüfe, was machbar ist, bevor Sie buchen.
Möchten Sie die Planung lieber mir überlassen? Wählen Sie Ihre Stunden und sagen Sie mir, was Ihnen gefällt.
Wissen Sie schon, welche Tour? Termine prüfen →
Was Gäste sagen
In ihren eigenen Worten.
Written after the tour by guests who booked and came on board. Nothing edited except where a quote is cut.
GetYourGuide · all my tours
Tripadvisor
This was the highlight of our trip! … He was incredibly accommodating and even had blankets for when the sun went behind the clouds.
Jessica · Vereinigtes Königreich · Mai 2025 Our driver Emiliano was so friendly and polite! The communication was super smooth and he made us feel relaxed. He brought us to see some of the villas and helped us get some good photos on this beautiful 1960’s boat.
Julius · Finnland · April 2026 Amazing tour with Emiliano – he was very informative and took us to some beautiful locations. Boat was very comfortable and served prosecco in proper glasses.
Louise · Vereinigtes Königreich · September 2026 Emiliano was great! He brought us to Nesso where we swam and jumped off a bridge. He is very kind and easy to talk to! Would definitely book his private tour again.
Lauren · USA · Juni 2024 What a fantastic boat ride! Emiliano was so kind, knowledgeable, and we loved having the Prosecco and option to swim.
Amanda · Kanada · September 2024 Emiliano is an amazing tour guide and showed us everything what was planned and even more!
Daniel · Schweiz · August 2024
Quotes from verified bookings on GetYourGuide, word for word; “…” marks a cut. GetYourGuide: 123 reviews across my four tour listings, same boat and same captain (weighted average 4.7). Tripadvisor: 22 reviews. Figures as of November 2026.
Termine prüfen →Online buchen
Wählen Sie Ihren Tag auf dem See.
Wählen Sie ein Erlebnis und prüfen Sie die freien Termine. Eine Gruppe mit bis zu fünf Personen, ich am Steuer; Treibstoff, Wasser und Prosecco inklusive (eine Flasche bei der einstündigen Tour, ab zwei Stunden ohne Limit). Sie zahlen online, um zu bestätigen. Kostenlose Stornierung bis 24 Stunden vor Abfahrt, und wenn das Wetter die Fahrt unsicher macht, biete ich Ihnen einen neuen Termin oder die volle Rückerstattung an.
Sie wissen nicht, welche Tour?
Sagen Sie mir, wo Sie wohnen und was Sie vorhaben. Den Rest planen wir zusammen.
(function(){
var root=document.getElementById('tv-home'); if(!root) return;
root.classList.add('js');
var nav=document.getElementById('tvnav'), btn=document.getElementById('tvmenubtn'), menu=document.getElementById('tvmenu');
function onScroll(){ nav.classList.toggle('scrolled', window.scrollY>40); }
window.addEventListener('scroll', onScroll, {passive:true}); onScroll();
if(btn){ btn.addEventListener('click', function(){ var o=nav.classList.toggle('open'); btn.setAttribute('aria-expanded', o?'true':'false'); btn.textContent=o?'Close':'Menu'; }); }
if(menu){ menu.addEventListener('click', function(e){ if(e.target.tagName==='A'){ nav.classList.remove('open'); if(btn){btn.setAttribute('aria-expanded','false'); btn.textContent='Menu';} } }); }
/* reduced motion respected via CSS; reveal on scroll */
var els=document.querySelectorAll('.tv .rv:not(.in)');
if('IntersectionObserver' in window){
var io=new IntersectionObserver(function(entries){ entries.forEach(function(en){ if(en.isIntersecting){ en.target.classList.add('in'); io.unobserve(en.target); } }); },{rootMargin:'0px 0px -8% 0px',threshold:.08});
els.forEach(function(el){ io.observe(el); });
} else { els.forEach(function(el){ el.classList.add('in'); }); }
setTimeout(function(){ var missed=false; document.querySelectorAll('.tv .rv:not(.in)').forEach(function(el){ var r=el.getBoundingClientRect(); if(r.top<window.innerHeight*1.1){ missed=true; } }); if(missed){ root.classList.remove('js'); } }, 2500);
document.querySelectorAll('.tv a[href^="#"]').forEach(function(a){ a.addEventListener('click', function(e){ var id=a.getAttribute('href').slice(1); var t=document.getElementById(id); if(t){ e.preventDefault(); t.scrollIntoView({behavior:'smooth', block:'start'}); } }); });
/* live line: what the lake is doing right now, Europe/Rome */
try{
var live=document.getElementById('tvlive'), lh=document.getElementById('tvlivehand');
var parts=new Intl.DateTimeFormat('en-GB',{timeZone:'Europe/Rome',hour:'2-digit',minute:'2-digit',hour12:false}).formatToParts(new Date());
var hh=+parts.find(function(p){return p.type==='hour'}).value, mm=parts.find(function(p){return p.type==='minute'}).value;
var t=hh+':'+mm, msg, hand;
if(hh>=6&&hh<9){msg="It's "+t+" on Lake Como."; hand="coffee first";}
else if(hh>=9&&hh<12){msg="It's "+t+" on Lake Como."; hand="a good time to plan";}
else if(hh>=12&&hh<15){msg="It's "+t+" on Lake Como."; hand="lunch hour in Italy";}
else if(hh>=15&&hh<17){msg="It's "+t+" on Lake Como."; hand="afternoon on the lake";}
else if(hh>=17&&hh<20){msg="It's "+t+" on Lake Como."; hand="aperitivo hour";}
else {msg="It's "+t+" on Lake Como."; hand="the boat is asleep";}
if(live){live.textContent=msg;} if(lh){lh.textContent=hand;}
}catch(e){}
var pickEl=document.getElementById('tvpick');
function setForm(dur,label){
var sel=null; document.querySelectorAll('.wp-block-jetpack-contact-form select').forEach(function(s){ var lab=s.closest('.jetpack-field, .grunion-field-wrap, .contact-form-field, div'); var txt=lab?lab.textContent:''; if(/how long/i.test(txt)||!sel){ sel=s; } });
if(sel&&dur){ for(var i=0;i<sel.options.length;i++){ if(sel.options[i].value.indexOf(dur)===0||sel.options[i].text.indexOf(dur)===0){ sel.selectedIndex=i; break; } } }
if(pickEl){ pickEl.textContent=label||''; }
}
window.tvSetForm=setForm;
/* experience cards and buttons hand their choice to the map builder, then scroll to it */
document.querySelectorAll('.tv a[data-hours]').forEach(function(c){ c.addEventListener('click', function(){ var h=parseInt(c.getAttribute('data-hours'),10); if(window.tvBuilder&&h){ window.tvBuilder.quick(h); } }); });
document.querySelectorAll('.tv a[data-bmode]').forEach(function(c){ c.addEventListener('click', function(){ if(window.tvBuilder){ window.tvBuilder.mode(c.getAttribute('data-bmode')); } }); });
})();
(function(){
"use strict";
/* ============================================================
CONFIGURACIÓN — edita estos valores (Emi)
============================================================ */
const CONFIG = {
businessName: "The View by Emiliano",
whatsapp: "393762380974", // WhatsApp Business de Emiliano (prefijo internacional, sin "+")
email: "hello@theviewbyemiliano.com", // correo donde recibes los itinerarios
currencyCode: "EUR",
showPrices: true, // precios aprobados por Emiliano el 22/10/2026
priceTable: {1: 380, 2: 650, 3: 950, 4: 1200, 6: 1550}, // € por grupo (hasta 5) según horas; las medias horas se interpolan
extraHourPrice: 250, // € por cada hora por encima de 6
maxHours: 10,
homeUrl: "/", // página de inicio (el formulario de contacto está en /#plan)
minimumHours: 1, // mínimo facturable en horas
billingBlockMinutes: 30, // el total se redondea hacia arriba a bloques de X minutos
boatSpeedKmh: 28, // velocidad media de crucero (28 km/h ≈ 15 nudos)
dockingMinutes: 4, // minutos de maniobra/atraque que se suman en cada traslado
maxGuests: 5, // capacidad máxima: 5 pasajeros
defaultStartTime: "10:00",
defaultGuests: 2,
defaultLanguage: "en", // "en" | "es" | "it"
returnToMeetingPoint: true,
quickDurations: [2, 3, 4, 6], // horas que se ofrecen como botones en el modo "Solo elijo las horas"
quickDefaultHours: 4
};
/* ============================================================
EXTRAS A BORDO — price 0 sin ask = siempre a bordo; ask:true = bajo pedido (se pide, no se cobra online); price > 0 = se suma al total
============================================================ */
const EXTRAS = [
{id:"prosecco", price:0, name:{en:"Prosecco (one bottle on 1 h, bottomless from 2 h)", es:"Prosecco (una botella en 1 h, ilimitado desde 2 h)", it:"Prosecco (una bottiglia in 1 ora, illimitato da 2 ore)"}},
{id:"water", price:0, name:{en:"Water", es:"Agua", it:"Acqua"}},
{id:"beer", price:0, ask:true, name:{en:"Beer instead of prosecco", es:"Cerveza en lugar de prosecco", it:"Birra al posto del prosecco"}},
{id:"soft", price:0, ask:true, name:{en:"Soft drinks instead of prosecco", es:"Bebidas sin alcohol en lugar de prosecco", it:"Analcolici al posto del prosecco"}}
];
/* Textos de la interfaz en tres idiomas */
const I18N = {
en: {
eyebrow:"The View by Emiliano · Lake Como", title:"Design your <em>day on the lake</em>.",
intro:"Add the places you'd like to see and the map estimates the time, or just pick the hours and tell me what you enjoy.",
s1:"Where do we meet?", s2:"What would you like to see?", s2hint:"Tap a dot on the map or add places from the list. Each stop has a suggested time you can change.",
s3:"Your itinerary", s4:"Your details",
date:"Date", departure:"Departure time", guests:"Guests (up to 5)", name:"Your name", contact:"Phone or email", notes:"Notes (occasion, kids, extras, allergies…)",
all:"All", meeting:"Meeting point", town:"Villages", villa:"Villas", restaurant:"Restaurants", bar:"Bars & lidos", swim:"Swimming",
catOne:{town:"Village", villa:"Villa", restaurant:"Restaurant", bar:"Bar & lido", swim:"Swimming spot", meeting:"Meeting point"},
add:"Add", added:"Added ✓", remove:"Remove", meetHere:"Meet here", meetingSet:"Meeting point ✓", stay:"Stay", min:"min", boat:"by boat", fromWater:"Seen from the water",
depart:"Depart from", returnTo:"Return to", returnHome:"Return to the meeting point at the end", orderByRoute:"Order by route",
empty:"Your tour is empty. Add places from the list or tap a marker on the map.",
onWater:"Time on the water", atStops:"Time at the stops", total:"Total duration", billedAs:"Price based on", minHours:"minimum", estPrice:"Estimated price", perHour:"per hour", extras:"Extras",
priceNote:"Per group of up to five. Boat, skipper, fuel, water and prosecco included (one bottle for 1 hour, bottomless from 2 hours); entrance tickets and meals ashore are paid on site. Times are estimates and the route depends on the weather. The price follows the final duration, in half-hour steps. Want it confirmed now? Book the duration online, then send me the route.", bookNow:"Book it now", beyond:"beyond 6 h",
sendWa:"Open in WhatsApp", sendMail:"Open in email", copy:"Copy itinerary", copied:"Itinerary copied", viewItinerary:"View itinerary",
needMeeting:"Choose a meeting point first", needStops:"Add at least one stop", noWa:"WhatsApp is not set up yet. The itinerary was copied instead.",
stops:"stops", stop:"stop", hours:"h", footNote:"Availability is confirmed when I reply.", or:"or write to",
msgTitle:"TOUR REQUEST", itinerary:"Itinerary", meetingPt:"Meeting point", summary:"Summary", regions:{all:"Whole lake", como:"Ramo di Como", centro:"Centro Lago", lecco:"Lecco", alto:"Alto Lario"},
editorHint:"Editor: tap the map to read coordinates",
modeRoute:"I'll build my route", modeRouteSub:"Pick the places you want to see", modeTime:"Just choose the hours", modeTimeSub:"Pick the hours, and I'll suggest the route",
dropoff:"Drop-off", samePlace:"Same as meeting point", duration:"Duration", arrival:"Arrival",
transferNote:"{a} → {b} takes about {t} by boat; the rest is free time for stops along the way.", tooShort:"This transfer needs at least {t}. Add more time.",
timeHint:"Not sure what to see? Write what you enjoy in the notes (swimming, villas, a long lunch) and I'll suggest a route.",
sExtras:"Extras on board", included:"Included on board", addons:"Ask for", extrasTotal:"Extras on board", switchHint:"Switch to \"I'll build my route\" to add this stop.",
priceLbl:"Estimated price", quote:"on request", onRequest:"on request", sendForm:"Continue to enquiry", formHint:"This copies your plan into the contact form below. Nothing is sent until you press Send enquiry there. I'll reply with availability and the price for your group.", planSent:"Your itinerary has been added below. Complete the form and press “Send enquiry” to send it to me.", hand:"tap a dot to see what it is.", backHome:"← Back to the lake", footLinks:"Home", priceNoteOff:"Boat and skipper included. I'll reply with the price for your group. Times are estimates."
},
es: {
eyebrow:"The View by Emiliano · Lago di Como", title:"Diseña tu <em>día en el lago</em>.",
intro:"Elige dónde nos encontramos, añade las villas, pueblos, restaurantes y lugares para nadar que quieras, y te cotizamos tu itinerario exacto.",
s1:"¿Dónde nos encontramos?", s2:"¿Qué te gustaría ver?", s2hint:"Toca un punto en el mapa o añade lugares desde la lista. Cada parada tiene un tiempo sugerido que puedes ajustar.",
s3:"Tu itinerario", s4:"Envía tu solicitud",
date:"Fecha", departure:"Hora de salida", guests:"Personas (máx. 5)", name:"Tu nombre", contact:"Teléfono o email", notes:"Notas (celebraciones, niños, extras, alergias…)",
all:"Todo", meeting:"Punto de encuentro", town:"Pueblos", villa:"Villas", restaurant:"Restaurantes", bar:"Bares y lidos", swim:"Baño",
catOne:{town:"Pueblo", villa:"Villa", restaurant:"Restaurante", bar:"Bar y lido", swim:"Lugar para nadar", meeting:"Punto de encuentro"},
add:"Añadir", added:"Añadido ✓", remove:"Quitar", meetHere:"Encontrarnos aquí", meetingSet:"Punto de encuentro ✓", stay:"Parada", min:"min", boat:"en barco", fromWater:"Se ve desde el agua",
depart:"Salida desde", returnTo:"Regreso a", returnHome:"Volver al punto de encuentro al final", orderByRoute:"Ordenar por ruta",
empty:"Tu tour está vacío. Añade lugares desde la lista o toca un punto en el mapa.",
onWater:"Tiempo de navegación", atStops:"Tiempo en las paradas", total:"Duración total", billedAs:"Precio según", minHours:"mínimo", estPrice:"Precio estimado", perHour:"por hora", extras:"Extras",
priceNote:"Por grupo de hasta cinco. Incluye barco, capitán, combustible, agua y prosecco (una botella en 1 hora, ilimitado desde 2 horas); entradas y comidas en tierra se pagan en el lugar. Los tiempos son estimados; el precio sigue la duración final, en pasos de media hora. ¿Lo quieres confirmado ya? Reserva la duración online y luego envíame la ruta.", bookNow:"Reservar ahora", beyond:"a partir de 6 h",
sendWa:"Enviar por WhatsApp", sendMail:"Enviar por email", copy:"Copiar itinerario", copied:"Itinerario copiado", viewItinerary:"Ver itinerario",
needMeeting:"Elige primero un punto de encuentro", needStops:"Añade al menos una parada", noWa:"WhatsApp aún no está configurado. Se copió el itinerario.",
stops:"paradas", stop:"parada", hours:"h", footNote:"La disponibilidad la confirma Emiliano.", or:"o escribe a",
msgTitle:"SOLICITUD DE TOUR", itinerary:"Itinerario", meetingPt:"Punto de encuentro", summary:"Resumen", regions:{all:"Todo el lago", como:"Ramo di Como", centro:"Centro Lago", lecco:"Lecco", alto:"Alto Lario"},
editorHint:"Editor: toca el mapa para leer coordenadas",
modeRoute:"Armo mi ruta", modeRouteSub:"Elige los lugares que quieres ver", modeTime:"Solo elijo las horas", modeTimeSub:"Dinos dónde y cuánto tiempo; el capitán planifica el resto",
dropoff:"Punto de llegada", samePlace:"El mismo punto de encuentro", duration:"Duración", arrival:"Llegada",
transferNote:"De {a} a {b} se tarda unos {t} en barco; el resto es tiempo libre para paradas por el camino.", tooShort:"Este trayecto necesita al menos {t}. Añade más tiempo.",
timeHint:"¿No sabes qué ver? Cuéntanos qué te gusta en las notas (nadar, villas, almuerzo sobre el agua) y diseñamos la ruta por ti.",
sExtras:"Extras a bordo", included:"Incluido a bordo", addons:"Bajo pedido", extrasTotal:"Extras a bordo", switchHint:"Cambia a \"Armo mi ruta\" para añadir esta parada.",
priceLbl:"Precio estimado", quote:"a consultar", onRequest:"bajo pedido", sendForm:"Continuar a la consulta", formHint:"Esto copia tu plan en el formulario de contacto de abajo. No se envía nada hasta que pulses Send enquiry. Te respondo con disponibilidad y precio para tu grupo.", planSent:"Tu itinerario está en el formulario de abajo. Complétalo y pulsa “Send enquiry” para enviármelo.", hand:"no hay respuestas incorrectas. mueve el mapa, toca los puntos.", backHome:"← Volver al lago", footLinks:"Inicio", priceNoteOff:"Barco y capitán incluidos. Te respondo con el precio para tu grupo. Los tiempos son estimados."
},
it: {
eyebrow:"The View by Emiliano · Lago di Como", title:"Disegna la tua <em>giornata sul lago</em>.",
intro:"Scegli dove ci incontriamo, aggiungi ville, paesi, ristoranti e punti per il bagno, e ti prepariamo il preventivo per il tuo itinerario.",
s1:"Dove ci incontriamo?", s2:"Cosa vorresti vedere?", s2hint:"Tocca un punto sulla mappa o aggiungi luoghi dalla lista. Ogni tappa ha un tempo consigliato che puoi modificare.",
s3:"Il tuo itinerario", s4:"Invia la richiesta",
date:"Data", departure:"Ora di partenza", guests:"Persone (max 5)", name:"Il tuo nome", contact:"Telefono o email", notes:"Note (festeggiamenti, bambini, extra, allergie…)",
all:"Tutto", meeting:"Punto d'incontro", town:"Paesi", villa:"Ville", restaurant:"Ristoranti", bar:"Bar e lidi", swim:"Bagno",
catOne:{town:"Paese", villa:"Villa", restaurant:"Ristorante", bar:"Bar e lido", swim:"Punto per il bagno", meeting:"Punto d'incontro"},
add:"Aggiungi", added:"Aggiunto ✓", remove:"Togli", meetHere:"Incontriamoci qui", meetingSet:"Punto d'incontro ✓", stay:"Sosta", min:"min", boat:"in barca", fromWater:"Si vede dall'acqua",
depart:"Partenza da", returnTo:"Ritorno a", returnHome:"Ritorno al punto d'incontro alla fine", orderByRoute:"Ordina per rotta",
empty:"Il tuo tour è vuoto. Aggiungi luoghi dalla lista o tocca un punto sulla mappa.",
onWater:"Tempo di navigazione", atStops:"Tempo alle tappe", total:"Durata totale", billedAs:"Prezzo in base a", minHours:"minimo", estPrice:"Prezzo stimato", perHour:"all'ora", extras:"Extra",
priceNote:"Per gruppo fino a cinque. Barca, skipper, carburante, acqua e prosecco inclusi (una bottiglia per 1 ora, illimitato da 2 ore); biglietti d'ingresso e pasti a terra si pagano sul posto. I tempi sono indicativi; il prezzo segue la durata finale, a passi di mezz'ora. Vuoi la conferma subito? Prenota la durata online e poi mandami il percorso.", bookNow:"Prenota ora", beyond:"oltre le 6 h",
sendWa:"Invia su WhatsApp", sendMail:"Invia via email", copy:"Copia itinerario", copied:"Itinerario copiato", viewItinerary:"Vedi itinerario",
needMeeting:"Scegli prima un punto d'incontro", needStops:"Aggiungi almeno una tappa", noWa:"WhatsApp non è ancora configurato. L'itinerario è stato copiato.",
stops:"tappe", stop:"tappa", hours:"h", footNote:"La disponibilità viene confermata da Emiliano.", or:"oppure scrivi a",
msgTitle:"RICHIESTA TOUR", itinerary:"Itinerario", meetingPt:"Punto d'incontro", summary:"Riepilogo", regions:{all:"Tutto il lago", como:"Ramo di Como", centro:"Centro Lago", lecco:"Lecco", alto:"Alto Lario"},
editorHint:"Editor: tocca la mappa per leggere le coordinate",
modeRoute:"Creo il mio percorso", modeRouteSub:"Scegli i luoghi da vedere", modeTime:"Scelgo solo le ore", modeTimeSub:"Dicci dove e per quanto; lo skipper pianifica il resto",
dropoff:"Punto di arrivo", samePlace:"Lo stesso punto d'incontro", duration:"Durata", arrival:"Arrivo",
transferNote:"Da {a} a {b} ci vogliono circa {t} in barca; il resto è tempo libero per le soste lungo il percorso.", tooShort:"Questo trasferimento richiede almeno {t}. Aggiungi più tempo.",
timeHint:"Non sai cosa vedere? Scrivici cosa ti piace nelle note (bagno, ville, pranzo sull'acqua) e disegniamo noi il percorso.",
sExtras:"Extra a bordo", included:"Incluso a bordo", addons:"Su richiesta", extrasTotal:"Extra a bordo", switchHint:"Passa a \"Creo il mio percorso\" per aggiungere questa tappa.",
priceLbl:"Prezzo stimato", quote:"su richiesta", onRequest:"su richiesta", sendForm:"Continua con la richiesta", formHint:"Questo copia il tuo piano nel modulo di contatto qui sotto. Non viene inviato nulla finché non premi Send enquiry. Ti rispondo con disponibilità e prezzo per il tuo gruppo.", planSent:"Il tuo itinerario è nel modulo qui sotto. Completalo e premi “Send enquiry” per inviarmelo.", hand:"nessuna risposta sbagliata. muovi la mappa, tocca i punti.", backHome:"← Torna al lago", footLinks:"Home", priceNoteOff:"Barca e skipper inclusi. Ti rispondo con il prezzo per il tuo gruppo. I tempi sono indicativi."
}
};
/* ============================================================
LUGARES — añade, quita o edita libremente
cat: "town" | "villa" | "restaurant" | "bar" | "swim"
pickup: {en,es,it} descripción del muelle → convierte el lugar en punto de encuentro posible
stay: minutos sugeridos en la parada · extra: importe fijo opcional que se suma al precio
lab: "l" pone la etiqueta a la izquierda del punto (útil en la orilla oeste)
Para obtener coordenadas nuevas: abre la página con #editor al final de la dirección y toca el mapa.
============================================================ */
const PLACES = [
// — Pueblos. Los que tienen "pickup" aparecen como puntos de encuentro (el texto describe el muelle).
{id:"varenna", cat:"town", name:"Varenna", lat:46.0103, lng:9.2884, stay:75, pickup:{en:"Pier by the old fishermen's harbour", es:"Muelle junto al antiguo puerto de pescadores", it:"Pontile vicino al vecchio porto dei pescatori"}, desc:{en:"Pastel houses, the lakeside Lovers' Walk and gardens over the water.", es:"Casas pastel, el Paseo de los Enamorados y jardines sobre el agua.", it:"Case color pastello, la Passeggiata degli Innamorati e giardini sull'acqua."}},
{id:"bellagio", cat:"town", name:"Bellagio", lat:45.9844, lng:9.2628, stay:90, pickup:{en:"Punta Spartivento pier", es:"Muelle bajo el casco antiguo", it:"Pontile sotto il borgo"}, desc:{en:"The pearl of the lake: stepped lanes, boutiques and the Spartivento point.", es:"La perla del lago: callejuelas con escaleras, boutiques y la punta Spartivento.", it:"La perla del lago: vicoli a gradini, botteghe e la punta Spartivento."}},
{id:"menaggio", cat:"town", name:"Menaggio", lat:46.0244, lng:9.243, stay:60, lab:"l", pickup:{en:"Main pier by the promenade", es:"Muelle principal junto al paseo", it:"Pontile principale sul lungolago"}, desc:{en:"Lively promenade with cafés and views of the Grigne mountains.", es:"Paseo animado con cafés y vistas a las montañas Grigne.", it:"Lungolago vivace con caffè e vista sulle Grigne."}},
{id:"tremezzo", cat:"town", name:"Tremezzo", lat:45.9799, lng:9.2238, stay:45, lab:"l", pickup:{en:"Pier on the Belle Époque lakefront", es:"Muelle en el paseo Belle Époque", it:"Pontile sul lungolago Belle Époque"}, desc:{en:"Belle Époque lakefront between Villa Carlotta and the Grand Hotel.", es:"Paseo Belle Époque entre Villa Carlotta y el Grand Hotel.", it:"Lungolago Belle Époque tra Villa Carlotta e il Grand Hotel."}},
{id:"lenno", cat:"town", name:"Lenno", lat:45.9643, lng:9.1885, stay:45, lab:"l", desc:{en:"Quiet bay with a beach, below Villa del Balbianello.", es:"Bahía tranquila con playa, bajo Villa del Balbianello.", it:"Baia tranquilla con spiaggia, sotto Villa del Balbianello."}},
{id:"cernobbio", cat:"town", name:"Cernobbio", lat:45.837, lng:9.0807, stay:45, desc:{en:"Elegant square on the water, home of Villa d'Este.", es:"Plaza elegante sobre el agua, hogar de Villa d'Este.", it:"Piazza elegante sull'acqua, casa di Villa d'Este."}},
{id:"nesso", cat:"town", name:"Nesso", lat:45.912, lng:9.1562, stay:30, desc:{en:"Medieval stone bridge and a waterfall gorge, best seen from the water.", es:"Puente medieval de piedra y una cascada, mejor vista desde el agua.", it:"Ponte medievale in pietra e un orrido con cascata, da vedere dall'acqua."}},
{id:"argegno", cat:"town", name:"Argegno", lat:45.9429, lng:9.1334, stay:30, lab:"l", desc:{en:"Small harbour village with a cable car up to Pigra.", es:"Pueblo con puerto pequeño y teleférico hasta Pigra.", it:"Borgo con porticciolo e funivia per Pigra."}},
{id:"torno", cat:"town", name:"Torno", lat:45.8575, lng:9.1190, stay:30, desc:{en:"Fishing village with a tiny harbour and a Romanesque church.", es:"Pueblo de pescadores con un puerto diminuto e iglesia románica.", it:"Borgo di pescatori con un piccolo porto e una chiesa romanica."}},
{id:"bellano", cat:"town", name:"Bellano", lat:46.0418, lng:9.3072, stay:45, desc:{en:"The Orrido gorge walkway and a lively old town.", es:"La pasarela del Orrido y un casco antiguo animado.", it:"La passerella dell'Orrido e un centro storico vivace."}},
{id:"sala", cat:"town", name:"Sala Comacina", lat:45.9595, lng:9.1666, stay:30, lab:"l", desc:{en:"Village facing Isola Comacina, with a small marina.", es:"Pueblo frente a Isola Comacina, con un pequeño puerto.", it:"Paese di fronte all'Isola Comacina, con un piccolo porto."}},
{id:"laglio", cat:"town", name:"Laglio", lat:45.8755, lng:9.1376, stay:15, lab:"l", desc:{en:"Tiny village with famous neighbours; admired from the boat.", es:"Pueblo diminuto con vecinos famosos; se admira desde el barco.", it:"Paesino con vicini famosi; da ammirare dalla barca."}},
// — Villas (la mayoría se admiran desde el agua; las que se visitan tienen entrada aparte)
{id:"balbianello", cat:"villa", name:"Villa del Balbianello", lat:45.9644, lng:9.2031, stay:75, desc:{en:"Terraced gardens on the Lavedo point; a Star Wars and James Bond location. Entrance ticket on site.", es:"Jardines en terrazas en la punta Lavedo; escenario de Star Wars y James Bond. Entrada aparte.", it:"Giardini a terrazze sulla punta di Lavedo; set di Star Wars e James Bond. Biglietto in loco."}},
{id:"carlotta", cat:"villa", name:"Villa Carlotta", lat:45.9827, lng:9.2318, stay:75, lab:"l", desc:{en:"Botanical garden and museum famous for its azaleas. Entrance ticket on site.", es:"Jardín botánico y museo famoso por sus azaleas. Entrada aparte.", it:"Giardino botanico e museo famoso per le azalee. Biglietto in loco."}},
{id:"melzi", cat:"villa", name:"Villa Melzi", lat:45.9790, lng:9.2540, stay:60, desc:{en:"Neoclassical villa with an English-style lakeside park. Entrance ticket on site.", es:"Villa neoclásica con un parque inglés a orillas del lago. Entrada aparte.", it:"Villa neoclassica con parco all'inglese sul lago. Biglietto in loco."}},
{id:"monastero", cat:"villa", name:"Villa Monastero", lat:46.0081, lng:9.2899, stay:60, desc:{en:"Former monastery with a 2 km garden walk along the shore. Entrance ticket on site.", es:"Antiguo monasterio con un jardín de 2 km a lo largo de la orilla. Entrada aparte.", it:"Ex monastero con un giardino di 2 km lungo la riva. Biglietto in loco."}},
{id:"serbelloni", cat:"villa", name:"Villa Serbelloni", lat:45.9880, lng:9.2645, stay:15, fromWater:true, desc:{en:"Grand hotel on the Bellagio promontory, seen from the boat.", es:"Gran hotel en el promontorio de Bellagio, visto desde el barco.", it:"Grand hotel sul promontorio di Bellagio, visto dalla barca."}},
{id:"deste", cat:"villa", name:"Villa d'Este", lat:45.8424, lng:9.084, stay:15, fromWater:true, desc:{en:"The lake's legendary hotel and its floating pool.", es:"El hotel legendario del lago y su piscina flotante.", it:"L'albergo leggendario del lago e la sua piscina galleggiante."}},
{id:"oleandra", cat:"villa", name:"Villa Oleandra", lat:45.8699, lng:9.1302, stay:15, lab:"l", fromWater:true, desc:{en:"George Clooney's villa in Laglio, admired from the water.", es:"La villa de George Clooney en Laglio, vista desde el agua.", it:"La villa di George Clooney a Laglio, vista dall'acqua."}},
{id:"cassinella", cat:"villa", name:"Villa La Cassinella", lat:45.9703, lng:9.2015, stay:15, lab:"l", fromWater:true, desc:{en:"Private estate reachable only by water, next to Lenno.", es:"Finca privada accesible solo por agua, junto a Lenno.", it:"Tenuta privata raggiungibile solo dall'acqua, accanto a Lenno."}},
{id:"pliniana", cat:"villa", name:"Villa Pliniana", lat:45.8625, lng:9.1200, stay:15, fromWater:true, desc:{en:"16th-century villa with an intermittent spring described by Pliny.", es:"Villa del siglo XVI con una fuente intermitente descrita por Plinio.", it:"Villa del Cinquecento con la fonte intermittente descritta da Plinio."}},
{id:"balbiano", cat:"villa", name:"Villa Balbiano", lat:45.9639, lng:9.1773, stay:15, lab:"l", fromWater:true, desc:{en:"Lavish 16th-century villa and gardens in Ossuccio, a film location.", es:"Suntuosa villa del siglo XVI con jardines en Ossuccio, escenario de cine.", it:"Sontuosa villa cinquecentesca con giardini a Ossuccio, set cinematografico."}},
{id:"erba", cat:"villa", name:"Villa Erba", lat:45.835, lng:9.0796, stay:15, fromWater:true, desc:{en:"Luchino Visconti's family villa on the Cernobbio shore.", es:"La villa de la familia de Luchino Visconti en Cernobbio.", it:"La villa della famiglia di Luchino Visconti a Cernobbio."}},
{id:"gaeta", cat:"villa", name:"Villa La Gaeta", lat:46.0593, lng:9.2692, stay:15, lab:"l", fromWater:true, desc:{en:"Fairytale villa from the finale of Casino Royale.", es:"Villa de cuento del final de Casino Royale.", it:"Villa da fiaba del finale di Casino Royale."}},
{id:"comacina", cat:"villa", name:"Isola Comacina", lat:45.9638, lng:9.1733, stay:45, lab:"l", desc:{en:"The lake's only island: church ruins, olive trees and a short walk.", es:"La única isla del lago: ruinas, olivos y un paseo corto.", it:"L'unica isola del lago: rovine, ulivi e una breve passeggiata."}},
// — Lugares para nadar
{id:"sw-comacina", cat:"swim", name:"Isola Comacina bay", lat:45.9618, lng:9.1753, stay:30, lab:"l", desc:{en:"Calm, clear water between the island and Ossuccio.", es:"Agua tranquila y clara entre la isla y Ossuccio.", it:"Acqua calma e limpida tra l'isola e Ossuccio."}},
{id:"sw-nesso", cat:"swim", name:"Nesso waterfall", lat:45.9109, lng:9.1533, stay:30, desc:{en:"Swim beneath the medieval bridge and the Orrido waterfall.", es:"Nada bajo el puente medieval y la cascada del Orrido.", it:"Bagno sotto il ponte medievale e la cascata dell'Orrido."}},
{id:"sw-bulberi", cat:"swim", name:"Grotta dei Bulberi", lat:45.9480, lng:9.1930, stay:30, desc:{en:"Sea-green cave on the Lezzeno shore, reachable only by boat.", es:"Gruta de agua verde en la orilla de Lezzeno, solo accesible en barco.", it:"Grotta dall'acqua verde sulla riva di Lezzeno, raggiungibile solo in barca."}},
{id:"sw-lenno", cat:"swim", name:"Lido di Lenno", lat:45.9625, lng:9.1866, stay:45, lab:"l", desc:{en:"Sandy beach club with loungers and a bar.", es:"Playa con club, tumbonas y bar.", it:"Spiaggia attrezzata con lettini e bar."}},
{id:"sw-lavedo", cat:"swim", name:"Lavedo cove", lat:45.9627, lng:9.1999, stay:30, lab:"l", desc:{en:"Sheltered cove beneath Villa del Balbianello.", es:"Cala resguardada bajo Villa del Balbianello.", it:"Insenatura riparata sotto Villa del Balbianello."}},
{id:"sw-spartivento", cat:"swim", name:"Punta Spartivento", lat:45.9915, lng:9.2615, stay:30, desc:{en:"Where the three branches meet; deep water and the widest view.", es:"Donde se unen los tres brazos; agua profunda y la vista más amplia.", it:"Dove si incontrano i tre rami; acqua profonda e la vista più ampia."}},
{id:"sw-menaggio", cat:"swim", name:"Lido di Menaggio", lat:46.0249, lng:9.2439, stay:45, lab:"l", desc:{en:"Pool, lawn and lake beach north of the town.", es:"Piscina, césped y playa al norte del pueblo.", it:"Piscina, prato e spiaggia a nord del paese."}},
// — Restaurantes (ejemplos conocidos; sustitúyelos por tus colaboradores)
{id:"r-locanda", cat:"restaurant", name:"Locanda dell'Isola Comacina", lat:45.9634, lng:9.1726, stay:120, lab:"l", desc:{en:"Historic fixed menu served the same way since 1947, ending with the flaming coffee ritual.", es:"Menú fijo histórico servido igual desde 1947, con el ritual del café flambeado.", it:"Menu fisso storico servito allo stesso modo dal 1947, con il rito del caffè alla fiamma."}},
{id:"r-platani", cat:"restaurant", name:"Crotto dei Platani", lat:45.9087, lng:9.1337, stay:120, lab:"l", desc:{en:"Refined lakeside crotto in Brienno with its own jetty.", es:"Crotto refinado a orillas del lago en Brienno con muelle propio.", it:"Crotto raffinato sul lago a Brienno con pontile privato."}},
{id:"r-darsena", cat:"restaurant", name:"La Darsena", lat:45.9793, lng:9.2212, stay:90, lab:"l", desc:{en:"Lakefront terrace in Tremezzo, right by the water.", es:"Terraza a orillas del lago en Tremezzo.", it:"Terrazza sul lago a Tremezzo, a pelo d'acqua."}},
{id:"r-bilacus", cat:"restaurant", name:"Bilacus", lat:45.9852, lng:9.2636, stay:90, desc:{en:"Terrace under a pergola in Bellagio's old town.", es:"Terraza bajo una pérgola en el casco antiguo de Bellagio.", it:"Terrazza sotto il pergolato nel centro di Bellagio."}},
{id:"r-punta", cat:"restaurant", name:"La Punta", lat:45.988, lng:9.2664, stay:90, desc:{en:"At Punta Spartivento, with the widest view on the lake.", es:"En Punta Spartivento, con la vista más amplia del lago.", it:"A Punta Spartivento, con la vista più ampia del lago."}},
{id:"r-harrys", cat:"restaurant", name:"Harry's Bar Cernobbio", lat:45.8379, lng:9.0812, stay:90, desc:{en:"Classic lunch on Cernobbio's lakeside square.", es:"Almuerzo clásico en la plaza de Cernobbio sobre el lago.", it:"Pranzo classico sulla piazza di Cernobbio, sul lago."}},
{id:"r-vecchia", cat:"restaurant", name:"Vecchia Varenna", lat:46.0106, lng:9.2885, stay:90, desc:{en:"Lake fish by Varenna's old harbour.", es:"Pescado del lago junto al antiguo puerto de Varenna.", it:"Pesce di lago accanto al vecchio porto di Varenna."}},
{id:"r-cavatappi", cat:"restaurant", name:"Il Cavatappi", lat:46.0096, lng:9.2884, stay:90, desc:{en:"Six tables in a Varenna alley; booking essential.", es:"Seis mesas en un callejón de Varenna; reserva imprescindible.", it:"Sei tavoli in un vicolo di Varenna; prenotazione indispensabile."}},
// — Bares y lidos para el aperitivo
{id:"b-lenno", cat:"bar", name:"Lido di Lenno beach bar", lat:45.9643, lng:9.1888, stay:60, lab:"l", desc:{en:"Aperitivo on the sand with Balbianello in view.", es:"Aperitivo en la arena con vistas a Balbianello.", it:"Aperitivo sulla sabbia con vista su Balbianello."}},
{id:"b-bellagio", cat:"bar", name:"Lido di Bellagio", lat:45.9883, lng:9.2666, stay:60, desc:{en:"Beach club by Punta Spartivento, for an evening drink.", es:"Beach club junto a Punta Spartivento, para una copa por la tarde.", it:"Beach club vicino a Punta Spartivento, per un drink la sera."}},
{id:"b-molo", cat:"bar", name:"Bar Il Molo", lat:46.0097, lng:9.2883, stay:45, desc:{en:"Aperitivo on Varenna's pier.", es:"Aperitivo en el muelle de Varenna.", it:"Aperitivo sul molo di Varenna."}}
];
/* ============================================================
GEOMETRÍA DEL LAGO (no hace falta tocar)
============================================================ */
const LAKE_SHORE = [
[46.1682,9.3826],[46.167,9.363],[46.158,9.3443],[46.148,9.3388],[46.145,9.3084],[46.1355,9.3061],[46.1322,9.295],[46.1194,9.2819],[46.1116,9.2789],[46.107,9.2812],[46.0954,9.2793],[46.0891,9.2835],[46.0774,9.2802],[46.0697,9.2819],[46.0546,9.2642],[46.0388,9.2544],[46.037,9.2472],[46.0311,9.2398],[46.0272,9.2402],[46.0217,9.2462],[46.016,9.2406],[46.008,9.2383],[45.9903,9.2428],[45.981,9.2296],[45.9756,9.2061],[45.9702,9.2019],[45.9646,9.2032],[45.9635,9.1734],[45.9553,9.1606],[45.9441,9.134],[45.9353,9.1314],[45.9055,9.1344],[45.8911,9.1476],[45.8858,9.1477],[45.872,9.1347],[45.8529,9.0967],[45.845,9.0915],[45.8423,9.0843],[45.822,9.0718],[45.8135,9.0739],[45.8124,9.0808],[45.8144,9.0855],[45.8197,9.0802],[45.8228,9.0809],[45.8293,9.0963],[45.8497,9.115],[45.8565,9.1173],[45.8561,9.1402],[45.8672,9.1588],[45.9152,9.1556],[45.9232,9.151],[45.9314,9.1518],[45.9369,9.1597],[45.9419,9.1762],[45.9487,9.212],[45.9692,9.239],[45.9784,9.2576],[45.9894,9.2679],[45.9878,9.273],[45.979,9.2696],[45.9663,9.2754],[45.9604,9.2734],[45.9484,9.2854],[45.924,9.2934],[45.9111,9.3028],[45.8865,9.3348],[45.876,9.3667],[45.8674,9.3763],[45.8614,9.3791],[45.853,9.3917],[45.8534,9.3982],[45.8762,9.3866],[45.8817,9.3748],[45.8936,9.3618],[45.8952,9.3545],[45.8939,9.344],[45.9074,9.3349],[45.9132,9.3216],[45.9195,9.3189],[45.9377,9.3206],[45.9514,9.3071],[45.9681,9.3077],[45.9905,9.2951],[46.0015,9.2969],[46.0094,9.288],[46.0249,9.289],[46.0348,9.3043],[46.0475,9.309],[46.0521,9.314],[46.064,9.314],[46.0731,9.3007],[46.0832,9.3116],[46.1039,9.3219],[46.1152,9.314],[46.1182,9.3168],[46.1232,9.3334],[46.1221,9.3378],[46.1155,9.334],[46.1166,9.347],[46.1222,9.349],[46.1258,9.342],[46.1349,9.3537],[46.1353,9.3701],[46.1378,9.3751],[46.1452,9.3807],[46.1537,9.3804],[46.1583,9.3847]
];
const ISLANDS = [[45.9640,9.1735,0.0018,0.0050,35]]; // lat, lng, radio lat, radio lng, rotación
const ARMS = {
como: [[45.996,9.258],[45.9886,9.2485],[45.9812,9.2389],[45.9738,9.2294],[45.9678,9.2168],[45.9561,9.2026],[45.9534,9.1791],[45.9453,9.1595],[45.9328,9.1416],[45.9102,9.1449],[45.8894,9.1525],[45.8742,9.149],[45.8558,9.1114],[45.8391,9.0935],[45.8256,9.0801],[45.8148,9.0811]],
lecco: [[45.996,9.258],[45.9971,9.2725],[45.9897,9.284],[45.9527,9.2955],[45.9353,9.3052],[45.9104,9.3147],[45.8906,9.3403],[45.8748,9.377],[45.8578,9.3874]],
nord: [[45.996,9.258],[46.0152,9.2658],[46.0366,9.2778],[46.0538,9.2896],[46.0731,9.2926],[46.0928,9.2966],[46.1083,9.3006],[46.1253,9.3073],[46.1389,9.3376],[46.149,9.3619],[46.1624,9.3757]]
};
const BRANCH_LABELS = [
{t:"Ramo di Como", lat:45.9039, lng:9.1472, rot:85.5},
{t:"Ramo di Lecco", lat:45.924, lng:9.3095, rot:75.2},
{t:"Alto Lario", lat:46.0895, lng:9.2959, rot:-82.0}
];
const REGIONS = {
all: null,
como: {lat:[45.80,45.93], lng:[9.03,9.19]},
centro:{lat:[45.94,46.04], lng:[9.15,9.31]},
lecco: {lat:[45.84,45.97], lng:[9.25,9.42]},
alto: {lat:[46.03,46.18], lng:[9.22,9.42]}
};
/* ---------- Projection & geometry ---------- */
const K = 1000, COSLAT = Math.cos(46 * Math.PI / 180), LNG0 = 9.045, LAT1 = 46.185, KM_PER_UNIT = 0.11119;
const xy = (lat, lng) => [(lng - LNG0) * COSLAT * K, (LAT1 - lat) * K];
const dist = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1]);
const shoreXY = LAKE_SHORE.map(p => xy(p[0], p[1]));
const xs = shoreXY.map(p => p[0]), ys = shoreXY.map(p => p[1]);
const PAD_L = 70, PAD_R = 26, PAD_B = 40, PAD_TOP = 44; // room for labels on the west shore, the scale bar and the region chips
const VB = {x: Math.min(...xs) - PAD_L, y: Math.min(...ys) - PAD_TOP, w: Math.max(...xs) - Math.min(...xs) + PAD_L + PAD_R, h: Math.max(...ys) - Math.min(...ys) + PAD_B + PAD_TOP};
function buildArm(pts){ const p = pts.map(q => xy(q[0], q[1])); const cum = [0]; for (let i = 1; i < p.length; i++) cum[i] = cum[i - 1] + dist(p[i - 1], p[i]); return {p, cum, len: cum[cum.length - 1]}; }
const ARM = Object.fromEntries(Object.entries(ARMS).map(([k, v]) => [k, buildArm(v)]));
function projectOnArm(arm, q){
let best = null;
for (let i = 0; i < arm.p.length - 1; i++){
const a = arm.p[i], b = arm.p[i + 1]; const dx = b[0] - a[0], dy = b[1] - a[1]; const L2 = dx * dx + dy * dy;
let t = ((q[0] - a[0]) * dx + (q[1] - a[1]) * dy) / L2; t = Math.max(0, Math.min(1, t));
const foot = [a[0] + t * dx, a[1] + t * dy]; const d = dist(q, foot);
if (!best || d < best.d){ const L = Math.sqrt(L2); const cross = (dx * (q[1] - a[1]) - dy * (q[0] - a[0])) / L; best = {d, s: arm.cum[i] + t * L, l: cross, foot}; }
}
return best;
}
function pointAt(arm, s){ s = Math.max(0, Math.min(arm.len, s)); for (let i = 1; i < arm.cum.length; i++){ if (s <= arm.cum[i]){ const t = (s - arm.cum[i - 1]) / (arm.cum[i] - arm.cum[i - 1]); const a = arm.p[i - 1], b = arm.p[i]; return [a[0] + t * (b[0] - a[0]), a[1] + t * (b[1] - a[1])]; } } return arm.p[arm.p.length - 1]; }
function armSlice(arm, s1, s2){ const out = [pointAt(arm, s1)]; if (s1 < s2){ for (let i = 0; i < arm.cum.length; i++) if (arm.cum[i] > s1 && arm.cum[i] < s2) out.push(arm.p[i]); } else { for (let i = arm.cum.length - 1; i >= 0; i--) if (arm.cum[i] < s1 && arm.cum[i] > s2) out.push(arm.p[i]); } out.push(pointAt(arm, s2)); return out; }
PLACES.forEach(p => {
p.xy = xy(p.lat, p.lng);
let best = null;
for (const [name, arm] of Object.entries(ARM)){ const r = projectOnArm(arm, p.xy); if (!best || r.d < best.d) best = {...r, arm: name}; }
p.route = best;
});
const byId = Object.fromEntries(PLACES.map(p => [p.id, p]));
function boatKm(A, B){
if (A.id === B.id) return 0;
const a = A.route, b = B.route; let u;
if (a.arm === b.arm) u = Math.hypot(a.s - b.s, a.l - b.l);
else u = a.s + b.s + 0.6 * (Math.abs(a.l) + Math.abs(b.l));
return u * KM_PER_UNIT;
}
function legMinutes(A, B){ const km = boatKm(A, B); if (km < 0.25) return 0; return Math.round(km / CONFIG.boatSpeedKmh * 60) + CONFIG.dockingMinutes; }
function routePoints(A, B){
const a = A.route, b = B.route; const pts = [A.xy];
if (a.arm === b.arm){ pts.push(...armSlice(ARM[a.arm], a.s, b.s)); }
else { pts.push(...armSlice(ARM[a.arm], a.s, 0)); pts.push(...armSlice(ARM[b.arm], 0, b.s)); }
pts.push(B.xy); return pts;
}
function smoothPath(pts, closed){
const n = pts.length; if (n < 2) return ""; const P = i => pts[closed ? (i + n) % n : Math.max(0, Math.min(n - 1, i))];
let d = `M${pts[0][0].toFixed(2)} ${pts[0][1].toFixed(2)}`;
const end = closed ? n : n - 1;
for (let i = 0; i < end; i++){ const p0 = P(i - 1), p1 = P(i), p2 = P(i + 1), p3 = P(i + 2);
const c1 = [p1[0] + (p2[0] - p0[0]) / 6, p1[1] + (p2[1] - p0[1]) / 6], c2 = [p2[0] - (p3[0] - p1[0]) / 6, p2[1] - (p3[1] - p1[1]) / 6];
d += ` C${c1[0].toFixed(2)} ${c1[1].toFixed(2)} ${c2[0].toFixed(2)} ${c2[1].toFixed(2)} ${p2[0].toFixed(2)} ${p2[1].toFixed(2)}`; }
return closed ? d + " Z" : d;
}
/* ---------- State ---------- */
let lang = CONFIG.defaultLanguage;
const state = {mode: "route", meeting: null, dropoff: null, duration: CONFIG.quickDefaultHours * 60, extras: {}, stops: [], returnHome: CONFIG.returnToMeetingPoint, start: CONFIG.defaultStartTime, date: "", guests: CONFIG.defaultGuests, name: "", contact: "", notes: ""};
let filter = "all", activeId = null;
try { const l = localStorage.getItem("tv-lang"); if (l && I18N[l]) lang = l; const d = JSON.parse(localStorage.getItem("tv-draft") || "null"); if (d && typeof d === "object"){ Object.assign(state, d); state.stops = (d.stops || []).filter(s => byId[s.id]); if (state.meeting && !byId[state.meeting]) state.meeting = null; if (state.dropoff && !byId[state.dropoff]) state.dropoff = null; if (!state.extras || typeof state.extras !== "object") state.extras = {}; if (state.mode !== "time") state.mode = "route"; if (!(state.duration > 0)) state.duration = CONFIG.quickDefaultHours * 60; state.duration = Math.min(CONFIG.maxHours * 60, state.duration); state.guests = Math.max(1, Math.min(CONFIG.maxGuests, Number(state.guests) || CONFIG.defaultGuests)); } } catch (e) {}
const EXTRA_BY_ID = Object.fromEntries(EXTRAS.map(x => [x.id, x]));
const extrasTotal = () => EXTRAS.reduce((s, x) => s + (x.price || 0) * (state.extras[x.id] || 0), 0);
const exName = x => (x.name && (x.name[lang] || x.name.en)) || x.id;
function saveDraft(){ try { localStorage.setItem("tv-draft", JSON.stringify(state)); localStorage.setItem("tv-lang", lang); } catch (e) {} }
const T = () => I18N[lang];
const $ = s => document.querySelector(s);
const EDITOR = location.hash === "#editor";
const nameOf = p => p.name;
const descOf = p => (p.desc && (p.desc[lang] || p.desc.en)) || "";
const pierOf = p => (p.pickup && (p.pickup[lang] || p.pickup.en)) || "";
const fmtMin = m => { m = Math.round(m); if (m < 60) return `${m} ${T().min}`; const h = Math.floor(m / 60), r = m % 60; return r ? `${h}h ${String(r).padStart(2, "0")}` : `${h}h`; };
const fmtClock = m => { m = ((Math.round(m) % 1440) + 1440) % 1440; return `${String(Math.floor(m / 60)).padStart(2, "0")}:${String(m % 60).padStart(2, "0")}`; };
const LOC = {en: "en-GB", es: "es-ES", it: "it-IT"};
const fmtMoney = v => new Intl.NumberFormat(LOC[lang], {style: "currency", currency: CONFIG.currencyCode, maximumFractionDigits: 0}).format(v);
/* Precio por duración facturada: tabla por horas, medias horas interpoladas, > 6 h a extraHourPrice por hora */
function priceFor(minutes){
const h = minutes / 60; const keys = Object.keys(CONFIG.priceTable).map(Number).sort((a, b) => a - b); const top = keys[keys.length - 1];
let p;
if (h <= keys[0]) p = CONFIG.priceTable[keys[0]];
else if (h >= top) p = CONFIG.priceTable[top] + (h - top) * CONFIG.extraHourPrice;
else { let a = keys[0], b = keys[1]; for (let i = 0; i < keys.length - 1; i++){ if (h >= keys[i]) { a = keys[i]; b = keys[i + 1]; } } p = CONFIG.priceTable[a] + (h - a) / (b - a) * (CONFIG.priceTable[b] - CONFIG.priceTable[a]); }
return Math.round(p / 5) * 5;
}
const ladderText = () => Object.keys(CONFIG.priceTable).map(Number).sort((a, b) => a - b).map(k => `${k} ${T().hours} ${fmtMoney(CONFIG.priceTable[k])}`).join(" · ") + ` · +${fmtMoney(CONFIG.extraHourPrice)} ${T().perHour} ${T().beyond}`;
const toMin = t => { const [h, m] = (t || "10:00").split(":").map(Number); return h * 60 + (m || 0); };
/* ---------- Itinerary computation ---------- */
function computeItinerary(){
const M = state.meeting ? byId[state.meeting] : null;
const items = []; let t = toMin(state.start), travel = 0, stay = 0, extras = 0;
let prev = M;
if (M) items.push({type: "depart", place: M, time: t});
state.stops.forEach((s, i) => {
const P = byId[s.id]; const leg = prev ? legMinutes(prev, P) : 0;
travel += leg; t += leg; const arrive = t; t += s.stay; stay += s.stay; extras += P.extra || 0;
items.push({type: "stop", place: P, idx: i, leg, arrive, stay: s.stay, depart: t}); prev = P;
});
if (M && state.returnHome && state.stops.length){ const leg = legMinutes(prev, M); travel += leg; t += leg; items.push({type: "return", place: M, leg, time: t}); }
const total = travel + stay; const block = CONFIG.billingBlockMinutes || 1;
const billed = state.stops.length ? Math.max(CONFIG.minimumHours * 60, Math.ceil(total / block) * block) : 0;
const onboard = state.stops.length ? extrasTotal() : 0;
const price = (billed ? priceFor(billed) : 0) + extras + onboard;
return {items, travel, stay, total, billed, extras, onboard, price, end: t};
}
/* Modo "Solo elijo las horas": punto de encuentro → punto de llegada + duración */
function computeQuick(){
const M = state.meeting ? byId[state.meeting] : null;
const D = (state.dropoff && byId[state.dropoff] && state.dropoff !== state.meeting) ? byId[state.dropoff] : M;
const transfer = M && D && M.id !== D.id ? legMinutes(M, D) : 0;
const dur = state.duration; const block = CONFIG.billingBlockMinutes || 1;
const billed = M ? Math.max(CONFIG.minimumHours * 60, Math.ceil(dur / block) * block) : 0;
const onboard = M ? extrasTotal() : 0; const start = toMin(state.start);
return {M, D, same: !!(M && D && M.id === D.id), transfer, dur, billed, tooShort: transfer > dur, onboard, price: (billed ? priceFor(billed) : 0) + onboard, start, end: start + dur};
}
const isTime = () => state.mode === "time";
/* ---------- Map ---------- */
const svg = $("#map"); const NS = "http://www.w3.org/2000/svg";
const el = (tag, attrs = {}, parent) => { const e = document.createElementNS(NS, tag); for (const [k, v] of Object.entries(attrs)) e.setAttribute(k, v); if (parent) parent.appendChild(e); return e; };
const view = {cx: VB.x + VB.w / 2, cy: VB.y + VB.h / 2, z: 1};
let upp = 1; // viewBox units per CSS pixel
const markers = {};
function buildMap(){
svg.innerHTML = "";
const defs = el("defs", {}, svg);
const g = el("linearGradient", {id: "lakeFill", x1: "0", y1: "0", x2: "1", y2: "1"}, defs);
el("stop", {offset: "0", "stop-color": "var(--lake)"}, g); el("stop", {offset: "1", "stop-color": "var(--lake-deep)"}, g);
const root = el("g", {id: "root"}, svg);
const d = smoothPath(shoreXY, true);
el("path", {d, class: "lake-halo"}, root);
el("path", {d, class: "lake"}, root);
ISLANDS.forEach(([la, ln, rla, rln, rot]) => { const c = xy(la, ln); el("ellipse", {cx: c[0], cy: c[1], rx: rln * COSLAT * K, ry: rla * K, transform: `rotate(${rot} ${c[0]} ${c[1]})`, class: "island"}, root); });
BRANCH_LABELS.forEach(b => { const c = xy(b.lat, b.lng); const t = el("text", {x: c[0], y: c[1], class: "branch", "text-anchor": "middle", transform: `rotate(${b.rot} ${c[0]} ${c[1]})`}, root); t.textContent = b.t; });
el("path", {id: "routeUnder", class: "route-under", d: ""}, root);
el("path", {id: "route", class: "route", d: ""}, root);
const mg = el("g", {id: "markers"}, root);
const ICON = {
meeting: '<path class="ico f" d="M0 5.5C-3.2 1.6 -4.6 -0.2 -4.6 -2.4a4.6 4.6 0 0 1 9.2 0C4.6 -0.2 3.2 1.6 0 5.5Z"/><circle cx="0" cy="-2.4" r="1.6" fill="var(--accent)"/>',
town: '<path class="ico f" d="M-3.6 0.4 0 -3.4 3.6 0.4 V3.6 H-3.6Z"/>',
villa: '<path class="ico" d="M-4 -1.6 H4 M-4 3.4 H4 M-2.6 -1.6 V3.4 M0 -1.6 V3.4 M2.6 -1.6 V3.4 M-4.2 -1.6 L0 -4.2 L4.2 -1.6"/>',
restaurant: '<path class="ico" d="M-2.4 -4 V4 M-3.6 -4 V-1.2 A1.2 1.2 0 0 0 -1.2 -1.2 V-4 M2.2 4 V-4 C3.8 -4 4.2 -1.4 4.2 0 H2.2"/>',
bar: '<path class="ico" d="M-3.6 -3.6 H3.6 L0 0.6 Z M0 0.6 V3.8 M-2 3.8 H2"/>',
swim: '<path class="ico" d="M-4.4 -0.6 C-3.2 -2.6 -1.2 -2.6 0 -0.6 C1.2 1.4 3.2 1.4 4.4 -0.6 M-4.4 2.6 C-3.2 0.6 -1.2 0.6 0 2.6 C1.2 4.6 3.2 4.6 4.4 2.6"/>'
};
const order = {town: 1, villa: 2, restaurant: 3, bar: 4, swim: 5};
[...PLACES].sort((a, b) => (order[b.cat] || 9) - (order[a.cat] || 9)).forEach(p => {
const mk = el("g", {class: `mk cat-${p.cat}${p.cat === "town" ? "" : " minor"}${p.pickup ? " pickup" : ""}`, "data-id": p.id, role: "button", tabindex: "0"}, mg);
const r = 7;
const body = el("g", {class: "body"}, mk);
el("circle", {class: "ring", r: r + 3.5}, body);
el("circle", {class: "dot", r}, body);
const ig = el("g", {class: "house"}, body); ig.innerHTML = ICON[p.cat];
if (p.pickup){ const pg = el("g", {class: "pin", transform: "translate(0 -0.5)"}, body); pg.innerHTML = ICON.meeting; }
const side = p.lab === "l" ? -1 : 1;
const lbl = el("text", {class: "lbl", x: side * (r + 4), y: 4, "text-anchor": side < 0 ? "end" : "start"}, mk); lbl.textContent = nameOf(p);
const num = el("g", {class: "num", transform: `translate(${r + 1} ${-r - 1})`}, body); el("circle", {r: 6.5}, num); const nt = el("text", {}, num); nt.textContent = "";
const title = el("title", {}, mk); title.textContent = nameOf(p);
markers[p.id] = mk;
mk.addEventListener("click", ev => { if (dragMoved) return; openCard(p.id); });
mk.addEventListener("keydown", ev => { if (ev.key === "Enter" || ev.key === " "){ ev.preventDefault(); openCard(p.id); } });
});
applyView();
}
function applyView(){
const rect = svg.getBoundingClientRect(); const pw = rect.width || 360, ph = rect.height || 480;
// fit base viewBox into the element, then zoom
const scale = Math.max(VB.w / pw, VB.h / ph) / view.z; upp = scale;
const w = pw * scale, h = ph * scale;
svg.setAttribute("viewBox", `${(view.cx - w / 2).toFixed(2)} ${(view.cy - h / 2).toFixed(2)} ${w.toFixed(2)} ${h.toFixed(2)}`);
const s = upp.toFixed(4);
for (const p of PLACES){ markers[p.id].setAttribute("transform", `translate(${p.xy[0].toFixed(2)} ${p.xy[1].toFixed(2)}) scale(${s})`); }
svg.classList.toggle("z-low", view.z < 1.7);
svg.classList.toggle("z-mid", view.z < 2.8);
svg.classList.toggle("grab", view.z > 1.04);
// scale bar: pick a round km length that renders between 45 and 110 px
const pxPerKm = 1 / (upp * KM_PER_UNIT);
const km = [0.5, 1, 2, 5, 10, 20].find(k => k * pxPerKm >= 45) || 20;
$("#scalebar span").textContent = km < 1 ? `${km * 1000} m` : `${km} km`; $("#scalebar i").style.width = `${(km * pxPerKm).toFixed(0)}px`;
clampView();
}
function clampView(){
const rect = svg.getBoundingClientRect(); const w = (rect.width || 360) * upp, h = (rect.height || 480) * upp;
const minX = VB.x - VB.w * 0.3, maxX = VB.x + VB.w * 1.3, minY = VB.y - VB.h * 0.2, maxY = VB.y + VB.h * 1.2;
view.cx = Math.max(minX + w / 2 - VB.w * 0.3, Math.min(maxX - w / 2 + VB.w * 0.3, view.cx));
view.cy = Math.max(minY + h / 2 - VB.h * 0.2, Math.min(maxY - h / 2 + VB.h * 0.2, view.cy));
}
function zoomAt(factor, px, py){
const rect = svg.getBoundingClientRect(); const z0 = view.z; const z1 = Math.max(1, Math.min(9, z0 * factor)); if (z1 === z0) return;
if (px != null){ const u0 = upp; const wx = view.cx + (px - rect.width / 2) * u0, wy = view.cy + (py - rect.height / 2) * u0; const u1 = u0 * z0 / z1; view.cx = wx - (px - rect.width / 2) * u1; view.cy = wy - (py - rect.height / 2) * u1; }
view.z = z1; if (z1 === 1){ view.cx = VB.x + VB.w / 2; view.cy = VB.y + VB.h / 2; } applyView();
setRegionPressed(null);
}
function fitBounds(latR, lngR){
if (!latR){ view.z = 1; view.cx = VB.x + VB.w / 2; view.cy = VB.y + VB.h / 2; applyView(); return; }
const a = xy(latR[1], lngR[0]), b = xy(latR[0], lngR[1]); const w = b[0] - a[0], h = b[1] - a[1];
const rect = svg.getBoundingClientRect(); const base = Math.max(VB.w / rect.width, VB.h / rect.height);
view.z = Math.min(9, Math.max(1, Math.min(rect.width * base / w, rect.height * base / h) * 0.92)); view.cx = a[0] + w / 2; view.cy = a[1] + h / 2; applyView();
}
function focusPlace(id, zoomTo){ const p = byId[id]; if (zoomTo){ view.z = Math.max(view.z, 3.2); view.cx = p.xy[0]; view.cy = p.xy[1]; applyView(); setRegionPressed(null); } Object.values(markers).forEach(m => m.classList.remove("active")); markers[id].classList.add("active"); activeId = id; }
/* pan / pinch / wheel */
let drag = null, dragMoved = false, pinch = null; const pointers = new Map();
svg.addEventListener("pointerdown", e => { pointers.set(e.pointerId, {x: e.clientX, y: e.clientY}); if (pointers.size === 1){ drag = {x: e.clientX, y: e.clientY, cx: view.cx, cy: view.cy}; dragMoved = false; } else if (pointers.size === 2){ const [a, b] = [...pointers.values()]; pinch = {d: Math.hypot(a.x - b.x, a.y - b.y), z: view.z}; drag = null; } if (e.pointerType === "mouse") svg.setPointerCapture(e.pointerId); });
svg.addEventListener("pointermove", e => { if (!pointers.has(e.pointerId)) return; pointers.set(e.pointerId, {x: e.clientX, y: e.clientY });
if (pointers.size === 2 && pinch){ const [a, b] = [...pointers.values()]; const d = Math.hypot(a.x - b.x, a.y - b.y); const rect = svg.getBoundingClientRect(); const mx = (a.x + b.x) / 2 - rect.left, my = (a.y + b.y) / 2 - rect.top; const target = Math.max(1, Math.min(9, pinch.z * d / pinch.d)); zoomAt(target / view.z, mx, my); dragMoved = true; return; }
if (drag && (e.pointerType === "mouse" ? e.buttons === 1 : true)){ const dx = e.clientX - drag.x, dy = e.clientY - drag.y; if (Math.hypot(dx, dy) > 4) dragMoved = true; if (dragMoved && view.z > 1.04){ svg.classList.add("grabbing"); view.cx = drag.cx - dx * upp; view.cy = drag.cy - dy * upp; applyView(); } } });
const endPtr = e => { pointers.delete(e.pointerId); if (pointers.size < 2) pinch = null; if (pointers.size === 0){ drag = null; svg.classList.remove("grabbing"); setTimeout(() => { dragMoved = false; }, 0); } };
svg.addEventListener("pointerup", endPtr); svg.addEventListener("pointercancel", endPtr); svg.addEventListener("pointerleave", e => { if (e.pointerType === "mouse") endPtr(e); });
svg.addEventListener("wheel", e => { e.preventDefault(); const rect = svg.getBoundingClientRect(); zoomAt(e.deltaY < 0 ? 1.18 : 1 / 1.18, e.clientX - rect.left, e.clientY - rect.top); }, {passive: false});
svg.addEventListener("click", e => { if (EDITOR && !dragMoved && e.target === svg || (EDITOR && !dragMoved && !e.target.closest(".mk"))){ const rect = svg.getBoundingClientRect(); const ux = view.cx + (e.clientX - rect.left - rect.width / 2) * upp, uy = view.cy + (e.clientY - rect.top - rect.height / 2) * upp; const lng = ux / (COSLAT * K) + LNG0, lat = LAT1 - uy / K; const box = $("#coordBox"); box.hidden = false; box.innerHTML = `<span>${T().editorHint}</span><code>lat: ${lat.toFixed(4)}, lng: ${lng.toFixed(4)}</code>`; } });
$("#zin").addEventListener("click", () => zoomAt(1.5)); $("#zout").addEventListener("click", () => zoomAt(1 / 1.5)); $("#zfit").addEventListener("click", () => { fitBounds(null); setRegionPressed("all"); });
window.addEventListener("resize", () => applyView());
function setRegionPressed(k){ document.querySelectorAll("#regions button").forEach(b => b.setAttribute("aria-pressed", String(b.dataset.r === k))); }
function renderRegions(){ const box = $("#regions"); box.innerHTML = ""; Object.keys(REGIONS).forEach(k => { const b = document.createElement("button"); b.type = "button"; b.dataset.r = k; b.textContent = T().regions[k]; b.setAttribute("aria-pressed", String(k === "all" && view.z === 1)); b.addEventListener("click", () => { const r = REGIONS[k]; fitBounds(r && r.lat, r && r.lng); setRegionPressed(k); }); box.appendChild(b); }); }
function renderLegend(){ const L = $("#legend"); L.innerHTML = ["meeting", "town", "villa", "restaurant", "bar", "swim"].map(c => `<span><b style="background:var(--${c === "meeting" ? "accent" : "c-" + c})"></b>${T()[c]}</span>`).join(""); }
function drawRoute(){
const M = state.meeting ? byId[state.meeting] : null; const seq = []; const q = computeQuick();
if (isTime()){ if (q.M && !q.same) seq.push(q.M, q.D); }
else { if (M) seq.push(M); state.stops.forEach(s => seq.push(byId[s.id])); if (M && state.returnHome && state.stops.length) seq.push(M); }
let d = ""; for (let i = 0; i < seq.length - 1; i++){ if (seq[i].id === seq[i + 1].id) continue; const pts = routePoints(seq[i], seq[i + 1]); d += smoothPath(pts, false) + " "; }
$("#route").setAttribute("d", d); $("#routeUnder").setAttribute("d", d);
const sel = new Set(state.stops.map(s => s.id));
PLACES.forEach(p => { const mk = markers[p.id]; const i = isTime() ? -1 : state.stops.findIndex(s => s.id === p.id); mk.classList.toggle("sel", i >= 0); mk.querySelector(".num text").textContent = i >= 0 ? String(i + 1) : ""; mk.classList.toggle("meet-on", p.id === state.meeting); mk.classList.toggle("drop-on", isTime() && !q.same && !!q.D && p.id === q.D.id); mk.classList.toggle("dim", !isTime() && filter !== "all" && p.cat !== filter && p.id !== state.meeting && !sel.has(p.id)); });
}
/* ---------- Marker card ---------- */
function openCard(id){
const p = byId[id]; focusPlace(id, false); const card = $("#mkCard"); const t = T();
const inTour = state.stops.some(s => s.id === id), isMeet = state.meeting === id; const q = computeQuick(); const isDrop = isTime() && !q.same && !!q.D && q.D.id === id;
let actions = `<button type="button" class="btn sm ${inTour ? "" : "primary"}" data-act="toggle">${inTour ? t.remove : t.add}</button>`;
if (isTime()) actions = p.pickup ? `<button type="button" class="btn sm ${isDrop ? "" : "primary"}" data-act="drop">${t.dropoff}${isDrop ? " ✓" : ""}</button>` : `<span class="hint">${t.switchHint}</span>`;
if (p.pickup) actions = `<button type="button" class="btn sm ${isMeet ? "" : "dark"}" data-act="meet">${isMeet ? t.meetingSet : t.meetHere}</button>` + actions;
const meta = `<span>${t.stay}: <b>${p.stay} ${t.min}</b></span>${p.fromWater ? `<span>${t.fromWater}</span>` : ""}${p.extra ? `<span>+ ${fmtMoney(p.extra)}</span>` : ""}${p.pickup ? `<span>${t.meeting}: ${p.pickup[lang] || p.pickup.en}</span>` : ""}`;
card.innerHTML = `<span class="cat" style="color:var(--c-${p.cat})">${t.catOne[p.cat]}</span><button type="button" class="xclose" aria-label="Close">×</button><h3>${nameOf(p)}</h3><p>${descOf(p)}</p><div class="meta">${meta}</div><div class="act">${actions}</div>`;
card.hidden = false;
card.querySelector(".xclose").addEventListener("click", () => { card.hidden = true; markers[id].classList.remove("active"); activeId = null; });
card.querySelectorAll("[data-act]").forEach(act => act.addEventListener("click", () => { if (act.dataset.act === "meet") setMeeting(id); else if (act.dataset.act === "drop") setDropoff(id); else toggleStop(id); openCard(id); }));
}
/* ---------- Builder actions ---------- */
function setMeeting(id){ state.meeting = id; if (state.dropoff === id) state.dropoff = null; update(); }
function setDropoff(id){ state.dropoff = (id === state.meeting) ? null : id; update(); }
function setDuration(min){ state.duration = Math.max(60, Math.min(CONFIG.maxHours * 60, min)); update(); }
function setMode(m){ state.mode = m === "time" ? "time" : "route"; applyMode(); update(); }
function applyMode(){
document.querySelectorAll("#modes button").forEach(b => b.setAttribute("aria-selected", String(b.dataset.mode === state.mode)));
document.querySelectorAll("[data-mode]").forEach(e => { if (e.closest("#modes")) return; e.hidden = e.dataset.mode !== state.mode; });
let n = 0; document.querySelectorAll(".build-col .step").forEach(s => { if (s.hidden) return; n++; const el = s.querySelector(".n"); if (el) el.textContent = String(n); });
}
function toggleStop(id){ const i = state.stops.findIndex(s => s.id === id); if (i >= 0) state.stops.splice(i, 1); else state.stops.push({id, stay: byId[id].stay || 30}); update(); }
function moveStop(i, dir){ const j = i + dir; if (j < 0 || j >= state.stops.length) return; [state.stops[i], state.stops[j]] = [state.stops[j], state.stops[i]]; update(); }
function changeStay(i, delta){ const s = state.stops[i]; s.stay = Math.max(5, Math.min(480, s.stay + delta)); update(); }
function orderByRoute(){ const M = state.meeting ? byId[state.meeting] : (state.stops[0] && byId[state.stops[0].id]); if (!M) return; const left = [...state.stops]; const out = []; let cur = M; while (left.length){ let bi = 0, bd = Infinity; left.forEach((s, i) => { const d = boatKm(cur, byId[s.id]); if (d < bd){ bd = d; bi = i; } }); const s = left.splice(bi, 1)[0]; out.push(s); cur = byId[s.id]; } state.stops = out; update(); }
/* ---------- Rendering ---------- */
function renderStatic(){
const t = T();
document.querySelectorAll("[data-i18n]").forEach(e => { e.textContent = t[e.dataset.i18n]; });
const h1 = $("#h1"); if (h1) h1.innerHTML = t.title;
document.querySelectorAll(".lang button").forEach(b => b.setAttribute("aria-pressed", String(b.dataset.lang === lang)));
const fb = $("#footBrand"); if (fb) fb.textContent = CONFIG.businessName;
$("#contactLine").innerHTML = `<span>${t.or}</span>${waOk() ? `<code>+${CONFIG.whatsapp}</code>` : ""}<code>${CONFIG.email}</code>`;
$("#btnWa").hidden = !waOk();
document.querySelectorAll("[data-href-home]").forEach(a => { a.href = CONFIG.homeUrl + (a.dataset.hrefHome || ""); });
renderRegions(); renderLegend(); renderFilters();
document.documentElement.lang = lang;
}
function renderFilters(){ const t = T(); const box = $("#filters"); box.innerHTML = ""; ["all", "town", "villa", "restaurant", "bar", "swim"].forEach(c => { const b = document.createElement("button"); b.type = "button"; b.innerHTML = (c === "all" ? "" : `<b style="background:var(--c-${c})"></b>`) + t[c]; b.setAttribute("aria-pressed", String(filter === c)); b.addEventListener("click", () => { filter = c; renderFilters(); renderList(); drawRoute(); }); box.appendChild(b); }); }
function renderMeeting(){ const box = $("#meetChips"); box.innerHTML = ""; PLACES.filter(p => p.pickup).forEach(p => { const b = document.createElement("button"); b.type = "button"; b.className = "chip"; b.innerHTML = `<b></b>${nameOf(p)}`; b.setAttribute("aria-pressed", String(state.meeting === p.id)); b.addEventListener("click", () => { setMeeting(p.id); focusPlace(p.id, false); }); box.appendChild(b); }); }
function renderList(){
const t = T(); const ul = $("#placeList"); ul.innerHTML = "";
PLACES.filter(p => filter === "all" || p.cat === filter).forEach(p => {
const li = document.createElement("li"); const i = state.stops.findIndex(s => s.id === p.id); if (i >= 0) li.classList.add("sel");
li.innerHTML = `<span class="sw" style="background:var(--c-${p.cat})"></span><div class="t"><button type="button" data-focus="${p.id}">${nameOf(p)}</button><small>${t.catOne[p.cat]} · <span class="min">${p.stay} ${t.min}</span>${p.fromWater ? ` · ${t.fromWater}` : ""}${p.extra ? ` · +${fmtMoney(p.extra)}` : ""}</small></div><button type="button" class="add" aria-pressed="${i >= 0}">${i >= 0 ? t.added : t.add}</button>`;
li.querySelector("[data-focus]").addEventListener("click", () => { focusPlace(p.id, true); openCard(p.id); if (window.innerWidth < 960) $("#mapWrap").scrollIntoView({behavior: "smooth", block: "start"}); });
li.querySelector(".add").addEventListener("click", () => toggleStop(p.id));
ul.appendChild(li);
});
}
function renderTimeline(it){
const t = T(); const ol = $("#timeline"); ol.innerHTML = "";
if (!state.stops.length){ ol.innerHTML = `<li class="empty">${state.meeting ? t.empty : t.needMeeting + ". " + t.empty}</li>`; return; }
const boat = `<svg viewBox="0 0 16 16" aria-hidden="true"><path d="M2 10h12l-1.5 3h-9z M4 10V5h5l3 5" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linejoin="round"/></svg>`;
it.items.forEach(item => {
const li = document.createElement("li");
if (item.type === "depart"){ li.className = "tl"; li.innerHTML = `<span class="time">${fmtClock(item.time)}</span><span class="rail"><i></i></span><div class="card end"><h4><b style="background:var(--accent)"></b><span>${t.depart} ${nameOf(item.place)}</span></h4><div class="sub">${pierOf(item.place)}</div></div>`; }
else if (item.type === "stop"){
const p = item.place, n = state.stops.length, i = item.idx;
if (item.leg || i > 0 || state.meeting){ const leg = document.createElement("li"); leg.className = "tl leg"; leg.innerHTML = `<span class="time"></span><span class="rail"></span><div class="body">${boat}<span>${item.leg ? `${fmtMin(item.leg)} ${t.boat}` : "—"}</span></div>`; ol.appendChild(leg); }
li.className = "tl"; li.innerHTML = `<span class="time">${fmtClock(item.arrive)}</span><span class="rail"><i></i></span><div class="card"><h4><b style="background:var(--c-${p.cat})"></b><span style="min-width:0">${nameOf(p)}</span></h4><div class="sub">${t.catOne[p.cat]} · ${fmtClock(item.arrive)}–${fmtClock(item.depart)}</div><div class="ctl"><span class="stay"><button type="button" data-d="-5" aria-label="−5 min">−</button><span>${fmtMin(item.stay)}</span><button type="button" data-d="5" aria-label="+5 min">+</button></span><button type="button" data-mv="-1" aria-label="Up" ${i === 0 ? "disabled" : ""}>↑</button><button type="button" data-mv="1" aria-label="Down" ${i === n - 1 ? "disabled" : ""}>↓</button><button type="button" data-rm aria-label="${t.remove}">×</button></div></div>`;
li.querySelectorAll("[data-d]").forEach(b => b.addEventListener("click", () => changeStay(i, Number(b.dataset.d))));
li.querySelectorAll("[data-mv]").forEach(b => b.addEventListener("click", () => moveStop(i, Number(b.dataset.mv))));
li.querySelector("[data-rm]").addEventListener("click", () => toggleStop(p.id));
} else { const leg = document.createElement("li"); leg.className = "tl leg"; leg.innerHTML = `<span class="time"></span><span class="rail"></span><div class="body">${boat}<span>${item.leg ? `${fmtMin(item.leg)} ${t.boat}` : "—"}</span></div>`; ol.appendChild(leg);
li.className = "tl"; li.innerHTML = `<span class="time">${fmtClock(item.time)}</span><span class="rail"><i></i></span><div class="card end"><h4><b style="background:var(--accent)"></b><span>${t.returnTo} ${nameOf(item.place)}</span></h4></div>`; }
ol.appendChild(li);
});
}
function renderTotals(it){
const t = T(); const empty = `<div class="r muted"><span>${t.priceLbl}</span><span>—</span></div><div class="note">${CONFIG.showPrices ? t.priceNote : t.priceNoteOff}</div>`;
const tail = (billed, onboard, price) => CONFIG.showPrices
? `<div class="r muted"><span>${t.billedAs} (${t.minHours} ${CONFIG.minimumHours} ${t.hours})</span><span>${fmtMin(billed)}</span></div>${onboard ? `<div class="r muted"><span>${t.extrasTotal}</span><span>${fmtMoney(onboard)}</span></div>` : ""}<div class="price"><span>${t.priceLbl}</span><strong>${fmtMoney(price)}</strong></div><div class="note">${ladderText()}. ${t.priceNote}</div>`
: `<div class="r muted"><span>${t.billedAs} (${t.minHours} ${CONFIG.minimumHours} ${t.hours})</span><span>${fmtMin(billed)}</span></div><div class="price"><span>${t.priceLbl}</span><strong class="hand">${t.quote}</strong></div><div class="note">${t.priceNoteOff}</div>`;
if (isTime()){ const q = computeQuick(); const box = $("#totalsQuick"); box.innerHTML = !q.M ? empty : `<div class="r"><span>${t.duration}</span><span>${fmtMin(q.dur)}</span></div>${!q.same ? `<div class="r muted"><span>${nameOf(q.M)} → ${nameOf(q.D)}</span><span>${fmtMin(q.transfer)} ${t.boat}</span></div>` : ""}` + tail(q.billed, q.onboard, q.price); return; }
const box = $("#totals");
if (!state.stops.length){ box.innerHTML = empty; return; }
box.innerHTML = `<div class="r"><span>${t.onWater}</span><span>${fmtMin(it.travel)}</span></div><div class="r"><span>${t.atStops}</span><span>${fmtMin(it.stay)}</span></div><div class="r"><span>${t.total}</span><span>${fmtMin(it.total)}</span></div>${it.extras ? `<div class="r muted"><span>${t.extras}</span><span>${fmtMoney(it.extras)}</span></div>` : ""}` + tail(it.billed, it.onboard, it.price);
}
function renderQuick(){
const t = T(); const q = computeQuick();
const dc = $("#dropChips"); dc.innerHTML = "";
const chip = (parent, label, pressed, fn) => { const b = document.createElement("button"); b.type = "button"; b.className = "chip"; b.innerHTML = label; b.setAttribute("aria-pressed", String(pressed)); b.addEventListener("click", fn); parent.appendChild(b); };
chip(dc, `<b></b>${t.samePlace}`, q.same || !state.meeting, () => { state.dropoff = null; update(); });
PLACES.filter(p => p.pickup && p.id !== state.meeting).forEach(p => chip(dc, `<b></b>${nameOf(p)}`, !q.same && !!q.D && q.D.id === p.id, () => setDropoff(p.id)));
const dch = $("#durChips"); dch.innerHTML = "";
(CONFIG.quickDurations || [2, 3, 4, 6]).forEach(h => chip(dch, `${h} ${t.hours}`, state.duration === h * 60, () => setDuration(h * 60)));
$("#durVal").textContent = fmtMin(state.duration);
const box = $("#quickSummary");
if (!q.M){ box.innerHTML = `<div class="empty">${t.needMeeting}</div>`; return; }
const note = q.same ? "" : `<div class="${q.tooShort ? "warn" : "note"}">${(q.tooShort ? t.tooShort : t.transferNote).replace("{a}", nameOf(q.M)).replace("{b}", nameOf(q.D)).replace("{t}", fmtMin(q.transfer))}</div>`;
box.innerHTML = `<div class="quick"><div class="row2"><span><strong>${fmtClock(q.start)}</strong> · ${t.depart} ${nameOf(q.M)}</span><small>${pierOf(q.M)}</small></div><div class="row2"><span><strong>${fmtClock(q.end)}</strong> · ${q.same ? t.returnTo : t.arrival} ${nameOf(q.D)}</span><small>${pierOf(q.D)}</small></div>${note}</div>`;
}
function renderExtras(){
const t = T(); const box = $("#extrasBox"); const inc = EXTRAS.filter(x => !x.price && !x.ask), add = EXTRAS.filter(x => x.price || x.ask);
box.innerHTML = `${inc.length ? `<span class="lbl-s">${t.included}</span><div class="inc">${inc.map(x => `<span>${exName(x)}</span>`).join("")}</div>` : ""}${add.length ? `<span class="lbl-s">${t.addons}</span>` : ""}`;
add.forEach(x => { const n = state.extras[x.id] || 0; const row = document.createElement("div"); row.className = "addon" + (n ? " on" : "");
row.innerHTML = `<span class="nm">${exName(x)}</span><span class="pr">${n > 1 ? `${n} × ` : ""}${x.price ? fmtMoney(x.price) : t.onRequest}</span><span class="qty"><button type="button" data-d="-1" aria-label="−1">−</button><span>${n}</span><button type="button" data-d="1" aria-label="+1">+</button></span>`;
row.querySelectorAll("button").forEach(b => b.addEventListener("click", () => { const v = Math.max(0, Math.min(x.max || 20, (state.extras[x.id] || 0) + Number(b.dataset.d))); if (v) state.extras[x.id] = v; else delete state.extras[x.id]; update(); }));
box.appendChild(row); });
}
function renderSumbar(it){ const t = T();
if (isTime()){ const q = computeQuick(); $("#sbSmall").textContent = q.M ? `${fmtMin(q.dur)} · ${nameOf(q.M)} → ${nameOf(q.D)}` : t.needMeeting; $("#sbPrice").textContent = q.M ? (CONFIG.showPrices ? fmtMoney(q.price) : fmtMin(q.billed)) : "—"; return; }
const n = state.stops.length; $("#sbSmall").textContent = n ? `${n} ${n === 1 ? t.stop : t.stops} · ${fmtMin(it.total)}` : t.empty.split(".")[0]; $("#sbPrice").textContent = n ? (CONFIG.showPrices ? fmtMoney(it.price) : fmtMin(it.billed)) : "—"; }
function update(){ const it = computeItinerary(); renderMeeting(); if (!isTime()){ renderList(); renderTimeline(it); } renderQuick(); renderExtras(); renderTotals(it); renderSumbar(it); drawRoute(); refreshLinks(); saveDraft(); if (activeId && !$("#mkCard").hidden) openCard(activeId); }
/* ---------- Message & sending ---------- */
function buildMessage(){
const t = T(); const M = state.meeting ? byId[state.meeting] : null;
const L = [];
L.push(`${t.msgTitle} – ${CONFIG.businessName}`);
L.push(`${t.name}: ${state.name || "-"}`); L.push(`${t.contact}: ${state.contact || "-"}`);
L.push(`${t.date}: ${state.date || "-"} · ${t.departure}: ${state.start} · ${t.guests}: ${state.guests}`);
L.push(`${t.meetingPt}: ${M ? nameOf(M) + (pierOf(M) ? " – " + pierOf(M) : "") : "-"}`);
const chosen = EXTRAS.filter(x => (x.price || x.ask) && state.extras[x.id]);
const extrasLines = () => { if (!chosen.length) return; L.push(""); L.push(t.sExtras.toUpperCase()); chosen.forEach(x => L.push(`${exName(x)} × ${state.extras[x.id]}${x.price ? ` · ${fmtMoney(x.price * state.extras[x.id])}` : ""}`)); };
if (isTime()){
const q = computeQuick();
L.push(`${t.dropoff}: ${q.same ? t.samePlace : nameOf(q.D) + (pierOf(q.D) ? " – " + pierOf(q.D) : "")}`);
L.push(`${t.duration}: ${fmtMin(q.dur)} (${fmtClock(q.start)}–${fmtClock(q.end)})${!q.same ? ` · ${nameOf(q.M)} → ${nameOf(q.D)} ${fmtMin(q.transfer)} ${t.boat}` : ""}`);
extrasLines();
L.push(""); L.push(t.summary.toUpperCase());
L.push(CONFIG.showPrices ? `${t.billedAs}: ${fmtMin(q.billed)} · ${t.priceLbl}: ${fmtMoney(q.price)}${q.onboard ? ` (${t.extrasTotal} ${fmtMoney(q.onboard)})` : ""}` : `${t.billedAs}: ${fmtMin(q.billed)} · ${t.priceLbl}: ${t.quote}`);
} else {
const it = computeItinerary();
L.push(""); L.push(t.itinerary.toUpperCase());
it.items.forEach(item => {
if (item.type === "depart") L.push(`${fmtClock(item.time)} ${t.depart} ${nameOf(item.place)}`);
else if (item.type === "stop") L.push(`${fmtClock(item.arrive)} ${nameOf(item.place)} (${t.catOne[item.place.cat]}) · ${fmtMin(item.stay)}${item.leg ? ` · ${fmtMin(item.leg)} ${t.boat}` : ""}`);
else L.push(`${fmtClock(item.time)} ${t.returnTo} ${nameOf(item.place)}${item.leg ? ` · ${fmtMin(item.leg)} ${t.boat}` : ""}`);
});
extrasLines();
L.push(""); L.push(t.summary.toUpperCase());
L.push(`${t.onWater}: ${fmtMin(it.travel)} · ${t.atStops}: ${fmtMin(it.stay)} · ${t.total}: ${fmtMin(it.total)}`);
L.push(CONFIG.showPrices ? `${t.billedAs}: ${fmtMin(it.billed)} · ${t.priceLbl}: ${fmtMoney(it.price)}${it.extras ? ` (+ ${t.extras} ${fmtMoney(it.extras)})` : ""}${it.onboard ? ` (${t.extrasTotal} ${fmtMoney(it.onboard)})` : ""}` : `${t.billedAs}: ${fmtMin(it.billed)} · ${t.priceLbl}: ${t.quote}`);
}
if (state.notes) { L.push(""); L.push(`${t.notes.split(" (")[0]}: ${state.notes}`); }
return L.join("\n");
}
let toastTimer;
function toast(msg){ let e = $(".toast"); if (!e){ e = document.createElement("div"); e.className = "toast"; document.getElementById("tvb").appendChild(e); } e.textContent = msg; clearTimeout(toastTimer); toastTimer = setTimeout(() => e.remove(), 2600); }
function ready(){ const t = T(); if (!state.meeting){ toast(t.needMeeting); return false; } if (isTime()){ const q = computeQuick(); if (q.tooShort){ toast(t.tooShort.replace("{t}", fmtMin(q.transfer))); return false; } return true; } if (!state.stops.length){ toast(t.needStops); return false; } return true; }
async function copyText(txt){ try { await navigator.clipboard.writeText(txt); return true; } catch (e) { try { const ta = document.createElement("textarea"); ta.value = txt; ta.style.position = "fixed"; ta.style.opacity = "0"; document.body.appendChild(ta); ta.select(); const ok = document.execCommand("copy"); ta.remove(); return ok; } catch (e2) { return false; } } }
const waOk = () => /^\d{8,15}$/.test(CONFIG.whatsapp);
function refreshLinks(){
const ok = state.meeting && (isTime() ? !computeQuick().tooShort : state.stops.length); const msg = ok ? buildMessage() : "";
$("#btnWa").href = ok && waOk() ? `https://wa.me/${CONFIG.whatsapp}?text=${encodeURIComponent(msg)}` : "#";
const subj = `${T().msgTitle} – ${state.name || ""} ${state.date || ""}`.trim();
$("#btnMail").href = ok ? `mailto:${CONFIG.email}?subject=${encodeURIComponent(subj)}&body=${encodeURIComponent(msg)}` : "#";
}
$("#btnCopy").addEventListener("click", async () => { if (!ready()) return; if (await copyText(buildMessage())) toast(T().copied); });
$("#btnForm").addEventListener("click", async () => {
if (!ready()) return;
const msg = buildMessage(); const billed = isTime() ? computeQuick().billed : computeItinerary().billed; const hrs = Math.round(billed / 60);
const ta = document.querySelector(".wp-block-jetpack-contact-form textarea");
if (ta){
ta.value = msg;
if (window.tvSetForm) window.tvSetForm(hrs ? hrs + " hours" : "", "your plan from the map is in the form below");
const t = document.getElementById("plan"); if (t) t.scrollIntoView({behavior: "smooth", block: "start"});
toast(T().planSent);
} else { let stored = false; try { localStorage.setItem("tv-plan", msg); stored = true; } catch (e) {} if (!stored) await copyText(msg); location.href = CONFIG.homeUrl + "#plan"; }
});
/* API for the rest of the page (experience cards, buttons) */
window.tvBuilder = { quick: h => { state.mode = "time"; state.duration = Math.max(60, Math.min(CONFIG.maxHours * 60, h * 60)); applyMode(); update(); }, mode: m => setMode(m) };
/* sticky summary bar only while the builder is on screen (phones) */
try { const sb = $("#sumbar"); const target = $("#tvbapp"); if (sb && target && "IntersectionObserver" in window){ new IntersectionObserver(es => es.forEach(e => sb.classList.toggle("on", e.isIntersecting)), {threshold: 0.02}).observe(target); } } catch (e) {}
$("#btnWa").addEventListener("click", async e => { if (!ready()){ e.preventDefault(); return; } if (!waOk()){ e.preventDefault(); await copyText(buildMessage()); toast(T().noWa); } });
$("#btnMail").addEventListener("click", async e => { if (!ready()){ e.preventDefault(); return; } copyText(buildMessage()).then(ok => { if (ok) toast(T().copied); }); });
$("#sbBtn").addEventListener("click", () => $(isTime() ? "#quick" : "#itin").scrollIntoView({behavior: "smooth", block: "start"}));
$("#btnOrder").addEventListener("click", orderByRoute);
document.querySelectorAll("#modes button").forEach(b => b.addEventListener("click", () => setMode(b.dataset.mode)));
$("#durMinus").addEventListener("click", () => setDuration(state.duration - 30)); $("#durPlus").addEventListener("click", () => setDuration(state.duration + 30));
/* ---------- Form bindings ---------- */
const bind = (sel, key, parse = v => v, light) => { const e = $(sel); e.addEventListener("input", () => { state[key] = parse(e.value); if (light){ refreshLinks(); saveDraft(); } else update(); }); return e; };
const fDate = bind("#fDate", "date", v => v, true), fStart = bind("#fStart", "start", v => v || CONFIG.defaultStartTime), fGuests = bind("#fGuests", "guests", v => Math.max(1, Math.min(CONFIG.maxGuests, Number(v) || 1)), true);
fGuests.max = String(CONFIG.maxGuests);
bind("#fName", "name", v => v, true); bind("#fContact", "contact", v => v, true); bind("#fNotes", "notes", v => v, true);
$("#fReturn").addEventListener("change", e => { state.returnHome = e.target.checked; update(); });
function fillForm(){ fDate.value = state.date || ""; fStart.value = state.start || CONFIG.defaultStartTime; fGuests.value = state.guests; $("#fName").value = state.name || ""; $("#fContact").value = state.contact || ""; $("#fNotes").value = state.notes || ""; $("#fReturn").checked = !!state.returnHome; }
document.querySelectorAll(".lang button").forEach(b => b.addEventListener("click", () => { lang = b.dataset.lang; renderStatic(); update(); }));
/* ---------- Boot ---------- */
/* Enlaces desde la home: /design-your-day/?mode=time&hours=4 */
try { const q = new URLSearchParams(location.search); if (q.get("mode") === "time" || q.get("mode") === "route") state.mode = q.get("mode"); const h = parseFloat(q.get("hours")); if (h >= 1 && h <= 8){ state.duration = h * 60; state.mode = "time"; } const l = q.get("lang"); if (l && I18N[l]) lang = l; } catch (e) {}
buildMap(); renderStatic(); fillForm(); applyMode(); update();
if (EDITOR){ const box = $("#coordBox"); box.hidden = false; box.innerHTML = `<span>${T().editorHint}</span>`; }
requestAnimationFrame(() => applyView());
})();
WhatsApp