/* Benzina Abruzzo — front-end. Nessuna dipendenza oltre Leaflet. */
(function () {
'use strict';
var $ = function (s) { return document.querySelector(s); };
var $$ = function (s) { return Array.prototype.slice.call(document.querySelectorAll(s)); };
var S = {
fuel: 'Benzina',
self: 0,
prov: '',
band: '',
comune: '',
sort: 'value',
pos: null,
rows: [],
meta: null,
sel: null,
vehicle: { type: 'car', cons: 5.8, unit: 'l100', tank: 50, mode: 0 }
};
// Consumi dichiarati (ciclo combinato WLTP, arrotondati) per i modelli piu diffusi.
var MODELS = {
car: [
['Fiat Panda 1.0 Hybrid', 5.2, 38], ['Fiat 500 1.0 Hybrid', 5.2, 38],
['Toyota Yaris Hybrid', 4.2, 36], ['Renault Clio TCe 90', 5.4, 42],
['Volkswagen Polo 1.0 TSI', 5.6, 40], ['Ford Fiesta 1.0 EcoBoost', 5.6, 42],
['Peugeot 208 1.2 PureTech', 5.5, 44], ['Citroen C3 1.2', 5.6, 45],
['Opel Corsa 1.2', 5.5, 44], ['Lancia Ypsilon 1.0', 5.3, 40],
['Fiat Tipo 1.5 Hybrid', 5.4, 50], ['Volkswagen Golf 1.5 TSI', 5.9, 50],
['Toyota Corolla Hybrid', 4.5, 43], ['Ford Focus 1.0', 5.9, 52],
['Skoda Octavia 1.5 TSI', 5.9, 55], ['Audi A3 30 TFSI', 5.9, 50],
['BMW Serie 1 116i', 6.2, 50], ['Mercedes Classe A 180', 6.2, 51],
['Fiat 500X 1.5 Hybrid', 6.0, 48], ['Jeep Renegade 1.5', 6.3, 48],
['Fiat Panda 1.3 Multijet', 4.6, 37], ['Volkswagen Golf 2.0 TDI', 4.9, 50],
['Audi A4 2.0 TDI', 5.2, 54], ['BMW Serie 3 320d', 5.1, 59],
['Fiat Ducato 2.3 (camper)', 9.5, 90],
['Fiat Panda 1.2 GPL', 7.1, 30], ['Dacia Sandero 1.0 GPL', 6.9, 40],
['Fiat Panda 0.9 Metano', 4.2, 12], ['Volkswagen Polo 1.0 Metano', 4.0, 13]
],
moto: [
['Honda SH 125', 2.7, 7.5], ['Honda SH 150', 2.9, 7.5],
['Piaggio Beverly 300', 3.4, 12], ['Yamaha XMAX 300', 3.3, 13],
['Honda NC750X', 3.6, 14], ['Yamaha MT-07', 4.3, 14],
['Kawasaki Versys 650', 4.5, 21], ['Benelli TRK 502', 4.2, 20],
['Piaggio Liberty 125', 2.6, 6], ['Vespa GTS 300', 3.4, 8.5],
['Ducati Monster 937', 5.6, 14], ['BMW R 1250 GS', 4.8, 20]
],
van: [
['Fiat Ducato 2.3 140cv', 8.8, 90], ['Ford Transit Custom', 7.6, 70],
['Volkswagen Transporter T6.1', 7.4, 70], ['Renault Trafic', 7.2, 66],
['Iveco Daily 35S', 10.5, 100], ['Peugeot Boxer', 8.6, 90],
['Citroen Jumper', 8.6, 90], ['Mercedes Sprinter 314', 9.2, 93]
]
};
var LS_VEH = 'benzina.vehicle.v1';
var LS_PREF = 'benzina.pref.v1';
// ---------- helpers ----------
function eur(n) { return n.toFixed(3).replace('.', ','); }
function eur0(n) { return n.toFixed(2).replace('.', ','); }
function km(n) { return n == null ? '—' : n.toFixed(n < 10 ? 1 : 0).replace('.', ',') + ' km'; }
function toast(msg, ms) {
var t = $('#toast'); t.textContent = msg; t.classList.add('show');
clearTimeout(toast._t); toast._t = setTimeout(function () { t.classList.remove('show'); }, ms || 2600);
}
function parseNum(v) { return parseFloat(String(v).replace(',', '.')) || 0; }
function consPer100() {
var v = S.vehicle;
if (v.unit === 'kml') return v.cons > 0 ? 100 / v.cons : 0;
return v.cons;
}
function fmtCons() {
var v = S.vehicle;
return v.cons.toFixed(1).replace('.', ',') + (v.unit === 'kml' ? ' km/L' : ' L/100km');
}
// ---------- persistence ----------
function loadPrefs() {
try {
var v = JSON.parse(localStorage.getItem(LS_VEH) || 'null');
if (v) S.vehicle = Object.assign(S.vehicle, v);
var p = JSON.parse(localStorage.getItem(LS_PREF) || 'null');
if (p) {
S.fuel = p.fuel || S.fuel; S.self = p.self || 0; S.sort = p.sort || S.sort;
S.band = p.band || ''; S.prov = p.prov || ''; S.comune = p.comune || '';
}
} catch (e) { /* localStorage può essere bloccato */ }
}
function savePrefs() {
try {
localStorage.setItem(LS_VEH, JSON.stringify(S.vehicle));
localStorage.setItem(LS_PREF, JSON.stringify({
fuel: S.fuel, self: S.self, sort: S.sort, band: S.band, prov: S.prov, comune: S.comune
}));
} catch (e) {}
}
// ---------- map ----------
var map, markers = {}, meMarker = null, mapReady = false;
function initMap() {
map = L.map('map', {
zoomControl: false, attributionControl: true,
scrollWheelZoom: false, tap: true, preferCanvas: true,
zoomSnap: 1, fadeAnimation: false, zoomAnimation: false,
markerZoomAnimation: false, inertia: true, inertiaDeceleration: 2600,
maxBoundsViscosity: 0.5, zoomControl: false, attributionControl: true
}).setView([42.35, 13.85], 8);
// --- Protomaps: vettoriale, tiles self-hosted (una sola richiesta range) ---
var flavor = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
try {
var layer = protomapsL.leafletLayer({
url: '/static/tiles/abruzzo.pmtiles',
flavor: flavor,
lang: 'it',
maxDataZoom: 13,
maxZoom: 17,
attribution: '© Protomaps · © OpenStreetMap',
// opzioni GridLayer: non ridisegnare durante pinch/pan, un solo
// buffer di tile. Sono la differenza fra scatti e scorrimento fluido.
updateWhenIdle: true,
updateWhenZooming: false,
keepBuffer: 1,
tileDelay: 1
});
layer.addTo(map);
S.basemap = layer;
} catch (e) {
// fallback: raster OSM, ma solo se il renderer vettoriale non parte
L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 18, attribution: '© OpenStreetMap'
}).addTo(map);
}
mapReady = true;
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', function (ev) {
if (!S.basemap) return;
try {
map.removeLayer(S.basemap);
S.basemap = protomapsL.leafletLayer({
url: '/static/tiles/abruzzo.pmtiles',
flavor: ev.matches ? 'dark' : 'light', lang: 'it',
maxDataZoom: 13, maxZoom: 17, tileDelay: 1,
updateWhenIdle: true, updateWhenZooming: false, keepBuffer: 1,
attribution: '© Protomaps · © OpenStreetMap'
});
S.basemap.addTo(map);
} catch (e) {}
});
}
// cheap / mid / pricey: usati sia dalle righe della lista sia dai pin,
// cosi il colore racconta la stessa cosa in entrambi i posti.
function priceClass(p, min, max) {
var t = (p - min) / Math.max(max - min, 1e-9);
return t < 0.34 ? 'cheap' : t < 0.67 ? 'mid' : 'pricey';
}
var MAX_PINS = 25; // solo i migliori: il resto non si disegna
function drawMarkers(rows) {
if (!mapReady) return;
Object.keys(markers).forEach(function (k) { map.removeLayer(markers[k]); });
markers = {};
if (!rows.length) return;
var ps = rows.map(function (r) { return r.prezzo; });
var min = Math.min.apply(null, ps), max = Math.max.apply(null, ps);
var pins = rows.slice(0, MAX_PINS), pts = [];
pins.forEach(function (r, i) {
if (!r.lat || !r.lon) return;
var cls = priceClass(r.prezzo, min, max);
var html = '
' + (i + 1) + '
';
var icon = L.divIcon({ html: html, className: '', iconSize: [30, 30], iconAnchor: [15, 15] });
var m = L.marker([r.lat, r.lon], { icon: icon, title: r.bandiera || r.gestore, riseOnHover: true })
.on('click', function () { openDetail(r); });
m.addTo(map);
markers[r.id] = m;
pts.push([r.lat, r.lon]);
});
if (pts.length) map.fitBounds(L.latLngBounds(pts).pad(0.22), { animate: false });
}
function drawMe(pos) {
if (!mapReady) return;
if (meMarker) map.removeLayer(meMarker);
var icon = L.divIcon({ html: '', className: '', iconSize: [16, 16], iconAnchor: [8, 8] });
meMarker = L.marker([pos.lat, pos.lon], { icon: icon, zIndexOffset: 1000 }).addTo(map);
}
// ---------- list ----------
var listEl, sheet;
function openSheet() {
sheet.classList.add('open');
document.querySelector('.app').classList.add('sheet-open');
sheet.setAttribute('aria-hidden', 'false');
renderChunk();
}
function closeSheet() {
sheet.classList.remove('open');
document.querySelector('.app').classList.remove('sheet-open');
sheet.setAttribute('aria-hidden', 'true');
}
function toggleSheet() {
if (sheet.classList.contains('open')) closeSheet(); else openSheet();
}
function badge(r) {
var out = [];
out.push('' + (r.self ? 'self' : 'servito') + '');
if (r.km != null) out.push('' + km(r.km) + '');
return out.join('');
}
var PAGE_SIZE = 24, rendered = 0, io = null;
var loading = false, pending = false;
function cardHTML(r, i, min, max) {
var cls = priceClass(r.prezzo, min, max) || 'mid';
var sub = r.comune;
if (r.km != null) sub = '' + km(r.km) + ' · ' + sub;
else if (r.indirizzo) sub += ' · ' + r.indirizzo.slice(0, 30);
return '' +
'
' +
'
' + (r.bandiera || r.gestore || 'Impianto') + '
' +
'
' + sub + '
' +
'
' + eur(r.prezzo) + '
' +
'
' + (r.self ? 'self' : 'servito') + '
' +
'
';
}
function renderChunk() {
if (rendered >= S.rows.length) return;
var ps = S.rows.map(function (r) { return r.prezzo; });
var min = Math.min.apply(null, ps), max = Math.max.apply(null, ps);
var end = Math.min(rendered + PAGE_SIZE, S.rows.length);
var frag = document.createDocumentFragment();
var tmp = document.createElement('div');
var html = '';
for (var i = rendered; i < end; i++) html += cardHTML(S.rows[i], i, min, max);
tmp.innerHTML = html;
while (tmp.firstChild) frag.appendChild(tmp.firstChild);
if (sentinelEl && sentinelEl.parentNode === listEl) listEl.insertBefore(frag, sentinelEl);
else listEl.appendChild(frag);
rendered = end;
}
function render() {
var rows = S.rows;
listEl.classList.remove('empty');
listEl.innerHTML = '';
rendered = 0;
if (!rows.length) {
listEl.classList.add('empty');
listEl.textContent = 'Nessun impianto trovato con questi filtri.';
return;
}
renderChunk();
renderChunk();
ensureSentinel();
}
var sentinelEl = null;
function bindInfiniteList() {
if (io) { io.disconnect(); io = null; }
io = new IntersectionObserver(function (entries) {
if (entries[0].isIntersecting) renderChunk();
}, { root: listEl, rootMargin: '400px' });
}
function ensureSentinel() {
if (!sentinelEl) {
sentinelEl = document.createElement('div');
sentinelEl.id = 'lsentinel';
sentinelEl.style.height = '1px';
}
listEl.appendChild(sentinelEl);
if (io) { io.disconnect(); io.observe(sentinelEl); }
}
function listHint() {
var n = S.rows.length;
var t = $('#listtitle');
if (S.sort === 'dist' && S.pos) t.textContent = 'Piu vicini';
else if (S.sort === 'value' && S.pos) t.textContent = 'Miglior scelta';
else t.textContent = 'Piu economici';
var hint = n + (n === 1 ? ' impianto' : ' impianti');
var lb = $('#listbtn-label');
$('#listhint').textContent = hint;
if (lb) lb.textContent = 'Impianti';
}
function apiUrl() {
var q = ['carburante=' + encodeURIComponent(S.fuel), 'self=' + S.self, 'sort=' + S.sort];
if (S.prov) q.push('provincia=' + S.prov);
if (S.band) q.push('bandiera=' + encodeURIComponent(S.band));
if (S.pos) q.push('lat=' + S.pos.lat.toFixed(5), 'lon=' + S.pos.lon.toFixed(5));
q.push('tank=' + S.vehicle.tank, 'cons=' + consPer100().toFixed(2));
return '/api/data?' + q.join('&');
}
var LS_DATA = 'benzina.data.v1';
var DATA_TTL = 2 * 60 * 60 * 1000; // due ore
function snapKey() {
return [S.fuel, S.self, S.sort, S.prov, S.band, S.comune,
S.vehicle.tank, consPer100().toFixed(2)].join('|');
}
function readSnap() {
try {
var raw = localStorage.getItem(LS_DATA);
if (!raw) return null;
var o = JSON.parse(raw);
if (!o || o.k !== snapKey()) return null;
if (Date.now() - o.t > DATA_TTL) return null;
return o;
} catch (e) { return null; }
}
function writeSnap(d, etag) {
try {
localStorage.setItem(LS_DATA, JSON.stringify({
t: Date.now(), k: snapKey(), e: etag || (d && d.__etag) || '',
rows: d.cheapest || [], meta: d.meta, summary: d.summary || []
}));
} catch (e) {}
}
function paint(d, fromCache) {
S.rows = d.cheapest || d.rows || [];
if (S.comune) {
var qq = S.comune.trim().toLowerCase();
S.rows = S.rows.filter(function (r) { return (r.comune || '').toLowerCase().indexOf(qq) === 0; });
}
S.meta = d.meta;
S.summary = d.summary || [];
listHint(); render();
drawMarkers(S.rows);
if (S.pos) drawMe(S.pos);
var m = d.meta || {};
$('#foot').textContent = 'MIMIT ' + (m.fonte || '—') + ' · ' + (m.impianti || 0) + ' impianti';
if (fromCache) document.body.classList.add('from-cache');
else document.body.classList.remove('from-cache');
if (window.__paintMark === undefined) window.__paintMark = Math.round(performance.now());
}
function load(force) {
if (loading) { if (force) pending = true; return; }
loading = true;
// 1) se abbiamo uno snapshot fresco lo disegniamo subito: zero attesa
if (!force) {
var snap = readSnap();
if (snap) {
paint(snap, true);
// in sottofondo: richiesta condizionale. Se i prezzi non sono cambiati
// il server risponde 304 e non scarichiamo nulla.
var hd = {};
if (snap.e) hd['If-None-Match'] = snap.e;
fetch(apiUrl(), { headers: hd }).then(function (r) {
if (r.status === 304) return null;
var et = r.headers.get('ETag');
return r.json().then(function (d) { return { d: d, e: et }; });
}).then(function (res) {
if (!res) return;
writeSnap(res.d, res.e);
paint(res.d, false);
}).catch(function () {}).then(function () { loading = false; });
return;
}
}
slotSkeletons();
fetch(apiUrl()).then(function (r) {
var et = r.headers.get('ETag');
return r.json().then(function (d) { return { d: d, e: et }; });
}).then(function (res) {
writeSnap(res.d, res.e);
paint(res.d, false);
}).catch(function () {
var snap2 = readSnap();
if (snap2) { paint(snap2, true); toast('Offline — prezzi salvati', 3000); }
else {
listEl.classList.add('empty');
listEl.textContent = 'Dati non disponibili: sei offline?';
toast('Connessione assente');
}
}).then(function () {
loading = false;
if (pending) { pending = false; load(); }
});
}
function slotSkeletons() {
listEl.classList.remove('empty');
listEl.innerHTML = new Array(7).join('');
}
// ---------- detail ----------
var current = null;
function navUrl(r) {
var isIOS = /iphone|ipad|ipod/i.test(navigator.userAgent);
if (isIOS) return 'https://maps.apple.com/?daddr=' + r.lat + ',' + r.lon + '&dirflg=d';
return 'https://www.google.com/maps/dir/?api=1&destination=' + r.lat + ',' + r.lon + '&travelmode=driving';
}
function openDetail(r) {
current = r;
S.sel = r.id;
render();
$('#d-name').textContent = r.bandiera || r.gestore || 'Impianto';
var addr = [r.indirizzo, r.comune + ' (' + r.provincia + ')'].filter(Boolean).join(' — ');
$('#d-addr').textContent = addr.replace(/\s*-\s*-$/, '');
// tabella carburanti: prima il carburante che stai guardando, poi gli altri
var cur = fuelLabel();
$('#d-fuels').innerHTML = '' +
'' + cur + '' +
'' + eur(r.prezzo) + '
' +
'' +
'Carico altri carburanti…—
';
$('#d-nav').href = navUrl(r);
openModal('#detail');
var hid = r.id;
fetch('/api/station?id=' + hid)
.then(function (x) { return x.json(); })
.then(function (d) {
if (!current || current.id !== hid || !d || !d.fuels) return;
var html = '';
var others = d.fuels.filter(function (f) { return f.carburante !== cur; });
var main = d.fuels.filter(function (f) { return f.carburante === cur; })[0];
var rowFor = function (f, cls) {
var self = f['self'] != null ? eur(f['self']) : '—';
var serv = f.servito != null ? eur(f.servito) : '—';
return '' +
'' + f.carburante + '' +
'' + self + '' +
'' + serv + '
';
};
if (main) html += rowFor(main, ' main');
html += others.map(function (f) { return rowFor(f); }).join('');
$('#d-fuels').innerHTML = html;
// provenienza dei dati: sta sotto, in piccolo
var self = main && main['self'] != null ? main['self'] : null;
var serv = main && main.servito != null ? main.servito : null;
var when = (main && main.dt) || d.collected || '';
$('#d-note').textContent = 'Prezzi MIMIT' + (when ? ' del ' + when : '') +
' · self ' + (self != null ? eur(self) : 'n.d.') +
' · servito ' + (serv != null ? eur(serv) : 'n.d.') +
(d.tipo ? ' · ' + d.tipo.toLowerCase() : '');
})
.catch(function () {});
// il costo del pieno: l'unica riga che serve davvero
var tank = S.vehicle.tank, cons = consPer100();
var pieno = r.prezzo * tank;
var bits = ['' + eur0(pieno) + ' € per ' + tank + ' L'];
if (r.km != null) {
var viaggio = r.km * 2 * cons / 100 * r.prezzo;
bits.push('' + eur0(viaggio) + ' € di viaggio (' + km(r.km) + ' a/r)');
}
var avg = provAvg(r);
if (avg) {
var diff = (avg - r.prezzo) * tank;
if (Math.abs(diff) >= 0.5) {
bits.push((diff > 0 ? 'risparmi ' : 'paghi ') + eur0(Math.abs(diff)) + ' € sulla media ' + r.provincia);
}
}
$('#d-meta').innerHTML = bits.join(' · ');
$('#d-note').textContent = 'Prezzi comunicati al MIMIT il ' + (r.dt || 'n.d.') + '.';
$('#d-histlabel').textContent = 'Andamento ' + cur;
drawHistory(null);
fetch('/api/history?id=' + r.id + '&carburante=' + encodeURIComponent(S.fuel))
.then(function (x) { return x.json(); })
.then(function (rows) { if (current && current.id === hid) drawHistory(rows); })
.catch(function () {});
}
function fuelLabel() { return S.fuel || 'Benzina'; }
function provAvg(r) {
if (!S.summary) return null;
var hit = S.summary.filter(function (s) { return s.provincia === r.provincia; })[0];
return hit ? hit.media : null;
}
function drawHistory(rows) {
var svg = $('#d-hist'), n = $('#d-histn'), wrap = $('#d-histwrap');
if (!svg) return;
// con meno di 3 rilevazioni una linea non dice niente: meglio niente
var thin = !rows || rows.length < 3;
if (wrap) wrap.style.display = thin ? 'none' : '';
if (thin) { svg.innerHTML = ''; n.textContent = ''; return; }
var vals = rows.map(function (r) { return r.p; });
var mn = Math.min.apply(null, vals), mx = Math.max.apply(null, vals);
var span = Math.max(mx - mn, 0.005);
var pad = 4, W = 300, H = 54;
var pts = rows.map(function (r, i) {
var x = rows.length === 1 ? W / 2 : pad + i * (W - pad * 2) / (rows.length - 1);
var y = H - pad - ((r.p - mn) / span) * (H - pad * 2);
return [x, y];
});
var line = pts.map(function (p) { return p[0].toFixed(1) + ',' + p[1].toFixed(1); }).join(' ');
var area = '0,' + H + ' ' + line + ' ' + W + ',' + H;
svg.innerHTML = '' +
pts.map(function (p) { return ''; }).join('') +
'' + eur(mn) + '' +
'' + eur(mx) + '';
n.textContent = rows.length === 1 ? '(1 rilevazione)' : '(' + rows.length + ' rilevazioni)';
}
function closeDetail() {
closeModal('#detail');
S.sel = null;
render();
}
// ---------- geo ----------
// --- stato del prompt posizione ---
function row(k, v) {
return '' + k + '' + v + '';
}
var geoCurrent = null;
function geoState(state, extra) {
geoCurrent = state;
var st = $('#geo-state'), ti = $('#geo-title'),
bo = $('#geo-body'), ste = $('#geo-steps'), btn = $('#geo-on'),
lab = $('#geo-on-label'), alt = $('#geo-manual'), skip = $('#geo-skip'),
note = $('#geo-note');
if (!st) return;
var status = st.parentNode;
status.className = 'shd-status';
ste.innerHTML = '';
btn.disabled = false;
btn.style.display = 'flex';
alt.style.display = 'block';
alt.textContent = 'Scegli un comune';
note.textContent = extra || '';
if (state === 'idle') {
st.textContent = 'Posizione non attiva';
ti.textContent = 'Dove ti trovi?';
bo.innerHTML = 'Serve per mettere in cima i distributori piu vicini e calcolare quanto costa arrivarci.';
lab.textContent = 'Consenti la posizione';
skip.textContent = 'Non ora';
ste.innerHTML = row('1', 'Distanza reale da ogni impianto') +
row('2', 'Costo del viaggio, non solo il prezzo al litro') +
row('3', 'Resta sul telefono, non viene salvata');
} else if (state === 'asking') {
status.className = 'shd-status wait';
st.textContent = 'In attesa del permesso';
ti.textContent = 'Conferma nel browser';
bo.innerHTML = 'Rispondi Consenti alla richiesta appena comparsa. Se non la vedi, controlla le impostazioni del sito.';
lab.textContent = 'Riprova';
skip.textContent = 'Annulla';
btn.disabled = true;
} else if (state === 'ok') {
status.className = 'shd-status ok';
st.textContent = 'Posizione attiva';
ti.textContent = 'Ci siamo';
bo.innerHTML = 'Lista ordinata per distanza. Tocca un impianto per aprirlo nella mappa.';
lab.textContent = 'Aggiorna';
skip.textContent = 'Chiudi';
} else if (state === 'inapp') {
status.className = 'shd-status bad';
st.textContent = 'Browser non supportato';
ti.textContent = 'Aprilo in Chrome o Safari';
bo.innerHTML = 'Stai usando il browser dentro un\'altra app (Telegram, Instagram, Facebook): qui la posizione e bloccata e la richiesta non puo comparire.';
lab.textContent = 'Copia il link';
alt.style.display = 'none';
skip.textContent = 'Continua senza posizione';
ste.innerHTML = row('1', 'Copia l\'indirizzo') +
row('2', 'Incollalo in Chrome o Safari') +
row('3', 'Concedi la posizione');
} else if (state === 'denied') {
status.className = 'shd-status bad';
st.textContent = 'Permesso negato';
ti.textContent = 'Riattiva la posizione';
bo.innerHTML = 'Il browser ha un blocco salvato per questo sito e non mostra piu la richiesta. Si toglie dalle impostazioni, poi ricarica.';
ste.innerHTML = geoDeniedSteps();
lab.textContent = 'Ho sistemato, ricarica';
alt.style.display = 'block';
$('#geo-manual').textContent = 'Intanto scegli un comune';
skip.textContent = 'Continua senza posizione';
} else if (state === 'blocked') {
status.className = 'shd-status bad';
st.textContent = 'Richiesta soppressa';
ti.textContent = 'Questa pagina non puo chiedere la posizione';
bo.innerHTML = 'Il browser non ha nemmeno mostrato la richiesta. Succede nei browser dentro le app (Telegram, Instagram) e in alcune versioni di iOS: li la posizione e bloccata a monte.';
lab.textContent = 'Copia il link';
alt.style.display = 'block';
$('#geo-manual').textContent = 'Scegli un comune';
skip.textContent = 'Continua senza posizione';
ste.innerHTML = row('1', 'Copia l\'indirizzo con il pulsante qui sopra') +
row('2', 'Incollalo in Chrome o Safari, non dentro l\'app') +
row('3', 'Tocca di nuovo Consenti la posizione');
}
}
function geoDeniedSteps() {
var p = platform();
if (p === 'ios') {
return row('1', 'Tocca aA a sinistra dell\'indirizzo') +
row('2', 'Impostazioni sito → Posizione') +
row('3', 'Scegli Consenti e ricarica');
}
if (p === 'android') {
return row('1', 'Tocca il lucchetto accanto all\'indirizzo') +
row('2', 'Autorizzazioni → Posizione') +
row('3', 'Scegli Consenti e ricarica');
}
return row('1', 'Clicca il lucchetto nella barra degli indirizzi') +
row('2', 'Posizione → Consenti') +
row('3', 'Ricarica la pagina');
}
var locWatch = null, locAnswered = false;
function locate(cb) {
if (!navigator.geolocation) {
toast('Questo browser non supporta la geolocalizzazione');
geoState('denied', 'Browser senza supporto GPS.');
return;
}
var inapp = inAppBrowser();
if (inapp) {
geoState('idle', (inapp === 'telegram'
? 'Sembra che tu stia usando il browser dentro Telegram: la posizione spesso è bloccata. Apri il link in Chrome o Safari. '
: 'Sembra un browser dentro un\'altra app: la posizione può essere bloccata. Apri il link in Chrome o Safari. '));
}
geoState('asking');
locAnswered = false;
clearTimeout(locWatch);
// se il browser non risponde (capita nei webview), non lasciare l'utente in attesa
locWatch = setTimeout(function () {
if (locAnswered) return;
var btn = $('#geo-on');
if (btn) btn.disabled = false;
var st = $('#geo-state');
if (st && st.textContent === 'In attesa del permesso') {
geoState('idle', 'Il browser non ha risposto alla richiesta. Se non vedi nessun avviso, controlla le impostazioni del sito o apri la pagina in Chrome/Safari.');
}
}, 22000);
navigator.geolocation.getCurrentPosition(onPos, onErr,
{ enableHighAccuracy: true, timeout: 12000, maximumAge: 30000 });
function onPos(p) {
locAnswered = true; clearTimeout(locWatch);
S.pos = { lat: p.coords.latitude, lon: p.coords.longitude };
S.posLabel = 'la tua posizione';
drawMe(S.pos);
if (mapReady) map.setView([S.pos.lat, S.pos.lon], 11);
$('#locbtn').classList.add('on');
geoState('ok');
try { localStorage.setItem('benzina.geoask', '1'); } catch (e) {}
load(true);
if (cb) cb();
setTimeout(function () {
var st = $('#geo-state');
if (st && st.textContent === 'Posizione attiva') closeModal('#geoprompt');
}, 1100);
}
function onErr(e) {
locAnswered = true; clearTimeout(locWatch);
$('#locbtn').classList.remove('on');
if (e.code === 1) {
geoDenied(e);
return;
}
if (e.code === 3) {
// timeout: riprovo senza alta precisione, che su desktop e lento
geoState('asking', 'Riprovo con precisione minore…');
navigator.geolocation.getCurrentPosition(onPos, function (e2) {
locAnswered = true;
if (e2.code === 1) { geoState('denied', 'Permesso negato (codice 1).'); return; }
geoState('idle', 'Non riesco a localizzarti (codice ' + e2.code + '). Scegli un comune: è immediato.');
}, { enableHighAccuracy: false, timeout: 15000, maximumAge: 300000 });
return;
}
geoState('idle', 'Posizione non disponibile (codice ' + e.code + '). Scegli un comune.');
}
}
// codici: 1 PERMISSION_DENIED, 2 POSITION_UNAVAILABLE, 3 TIMEOUT.
// Distinguere "l'utente ha negato" da "l'ambiente non lascia nemmeno
// chiedere" e' la differenza tra mandarlo nelle impostazioni e mandarlo
// in un altro browser.
function geoDenied(e) {
var detail = 'codice ' + e.code + (e.message ? ' (' + e.message + ')' : '');
var finish = function (perm) {
if (perm === 'denied') {
geoState('denied', detail + ' · permesso memorizzato: negato');
} else {
geoState('blocked', detail + ' · permesso memorizzato: ' + perm);
}
try { localStorage.setItem('benzina.geoask', '1'); } catch (err) {}
};
if (navigator.permissions && navigator.permissions.query) {
navigator.permissions.query({ name: 'geolocation' })
.then(function (s) { finish(s.state); })
.catch(function () { finish('non leggibile'); });
} else {
finish('non leggibile');
}
}
function showGeoNote(txt) {
var n = $('#geo-note');
if (n) n.textContent = txt || '';
}
function openModal(sel) { var m = $(sel); if (m) m.classList.add('open'); }
function closeModal(sel) { var m = $(sel); if (m) m.classList.remove('open'); }
// ---------- setup ----------
function fillModels() {
var sel = $('#vmodel');
if (!sel) return;
var list = MODELS[S.vehicle.type] || [];
sel.innerHTML = '' +
list.map(function (m, i) {
return '';
}).join('');
}
function openSetup() {
var v = S.vehicle;
fillModels();
$$('#vtype button').forEach(function (b) { b.setAttribute('aria-pressed', String(b.dataset.v === v.type)); });
$$('#vunit button').forEach(function (b) { b.setAttribute('aria-pressed', String(b.dataset.u === v.unit)); });
$$('#vmode button').forEach(function (b) { b.setAttribute('aria-pressed', String(+b.dataset.m === S.self)); });
$('#vcons').value = String(v.cons).replace('.', ',');
$('#vtank').value = String(v.tank);
$('#setup').classList.add('open');
}
function bindSetup() {
$('#setupclose').onclick = function () { $('#setup').classList.remove('open'); };
$$('#vtype button').forEach(function (b) {
b.onclick = function () {
$$('#vtype button').forEach(function (x) { x.setAttribute('aria-pressed', 'false'); });
b.setAttribute('aria-pressed', 'true');
S.vehicle.type = b.dataset.v;
// valori tipici di partenza
if (b.dataset.v === 'moto') { S.vehicle.cons = 4.0; S.vehicle.tank = 15; }
else if (b.dataset.v === 'van') { S.vehicle.cons = 8.5; S.vehicle.tank = 70; }
else { S.vehicle.cons = 5.8; S.vehicle.tank = 50; }
$('#vcons').value = String(S.vehicle.cons).replace('.', ',');
$('#vtank').value = String(S.vehicle.tank);
fillModels();
};
});
$$('#vunit button').forEach(function (b) {
b.onclick = function () {
$$('#vunit button').forEach(function (x) { x.setAttribute('aria-pressed', 'false'); });
b.setAttribute('aria-pressed', 'true');
S.vehicle.unit = b.dataset.u;
};
});
$$('#vmode button').forEach(function (b) {
b.onclick = function () {
$$('#vmode button').forEach(function (x) { x.setAttribute('aria-pressed', 'false'); });
b.setAttribute('aria-pressed', 'true');
S.self = +b.dataset.m;
};
});
var msel = $('#vmodel');
if (msel) msel.onchange = function () {
var idx = msel.value;
if (idx === '') return;
var m = (MODELS[S.vehicle.type] || [])[+idx];
if (!m) return;
S.vehicle.cons = m[1]; S.vehicle.tank = m[2]; S.vehicle.unit = 'l100';
$$('#vunit button').forEach(function (x) {
x.setAttribute('aria-pressed', String(x.dataset.u === 'l100'));
});
$('#vcons').value = String(m[1]).replace('.', ',');
$('#vtank').value = String(m[2]);
toast(m[0] + ': ' + String(m[1]).replace('.', ',') + ' L/100km, serbatoio ' + m[2] + ' L');
};
$('#vsave').onclick = function () {
S.vehicle.cons = parseNum($('#vcons').value) || S.vehicle.cons;
S.vehicle.tank = parseNum($('#vtank').value) || S.vehicle.tank;
savePrefs();
$('#setup').classList.remove('open');
toast('Veicolo salvato: ' + fmtCons() + ', ' + S.vehicle.tank + ' L');
load();
};
}
// ---------- filters ----------
function bindChips() {
$$('.chip[data-sort]').forEach(function (c) {
c.onclick = function () {
$$('.chip[data-sort]').forEach(function (x) { x.setAttribute('aria-pressed', 'false'); });
c.setAttribute('aria-pressed', 'true');
S.sort = c.dataset.sort;
if (S.sort !== 'price' && !S.pos) { locate(); }
savePrefs(); load();
};
});
$('#locbtn').onclick = function () { askPosition(); };
$('#listbtn').onclick = toggleSheet;
$('#sheetclose').onclick = closeSheet;
$('#grab').onclick = closeSheet;
listEl.addEventListener('click', function (e) {
var card = e.target.closest('.card');
if (!card) return;
var r = S.rows.filter(function (x) { return String(x.id) === card.dataset.id; })[0];
if (r) openDetail(r);
});
$('#detail').addEventListener('click', function (e) {
if (e.target.id === 'detail') closeDetail();
});
$('#d-close').onclick = closeDetail;
$('#d-vehicle').onclick = function () { closeDetail(); openSetup(); };
$('#d-share').onclick = function () {
if (!current) return;
var r = current;
var txt = (r.bandiera || r.gestore) + ' — ' + r.comune + ': ' + eur(r.prezzo) + ' €/L (' +
(r.self ? 'self' : 'servito') + ')\n' +
'https://benzina.feedme.work/?s=' + r.id;
if (navigator.share) {
navigator.share({ title: 'Benzina Abruzzo', text: txt, url: 'https://benzina.feedme.work/?s=' + r.id })
.catch(function () {});
} else if (navigator.clipboard) {
navigator.clipboard.writeText(txt).then(function () { toast('Copiato negli appunti'); });
} else { toast('Condivisione non disponibile'); }
};
var vb = $('#vbtn');
if (vb) vb.onclick = openSetup;
}
// ---------- PWA / installazione ----------
var LS_INST = 'benzina.installsnooze';
var installEvt = null, installCtx = null;
function isStandalone() {
return window.matchMedia('(display-mode: standalone)').matches ||
window.matchMedia('(display-mode: fullscreen)').matches ||
navigator.standalone === true;
}
function inAppBrowser() {
var ua = navigator.userAgent || '';
if (/FBAN|FBAV|Instagram|Line\/|Twitter|LinkedInApp|Pinterest/i.test(ua)) return 'social';
if (/Telegram/i.test(ua)) return 'telegram';
if (/; wv\)/i.test(ua)) return 'webview';
return '';
}
function platform() {
var ua = navigator.userAgent;
if (/iphone|ipad|ipod/i.test(ua)) return 'ios';
if (/android/i.test(ua)) return 'android';
if (/windows|macintosh|linux/i.test(ua)) return 'desktop';
return 'other';
}
// 0 = non chiedere piu (solo se ha cliccato "Non ora")
function installSnoozed() {
try { return localStorage.getItem(LS_INST) === '1'; } catch (e) { return false; }
}
function snoozeInstall() {
try { localStorage.setItem(LS_INST, '1'); } catch (e) {}
}
function installStepsHTML(p, canPrompt) {
if (canPrompt) return '';
if (p === 'ios') {
return row('1', 'Apri questa pagina in Safari') +
row('2', 'Tocca Condividi in basso') +
row('3', 'Scegli Aggiungi a Home');
}
if (p === 'android') {
return row('1', 'Apri il menu ⋮ del browser') +
row('2', 'Tocca Installa app') +
row('3', 'Conferma');
}
return row('1', 'Icona installa nella barra degli indirizzi') +
row('2', 'Oppure menu del browser → Installa');
}
function showInstallPrompt(ctx) {
installCtx = ctx || 'auto';
var p = platform();
var canPrompt = !!installEvt;
var st = $('#install-state'), ti = $('#install-title'), bo = $('#install-body'),
ste = $('#install-steps'), go = $('#install-go'),
later = $('#install-later'), status = st.parentNode;
status.className = 'shd-status';
ste.innerHTML = '';
go.style.display = 'flex';
if (canPrompt) {
st.textContent = 'Pronta da installare';
ti.textContent = 'Tienila in home';
bo.innerHTML = 'Un tocco e la trovi tra le app: si apre a schermo intero e funziona anche senza rete.';
ste.innerHTML = row('1', 'A schermo intero, senza barra del browser') +
row('2', 'Ultimi prezzi anche offline') +
row('3', 'Si disinstalla come qualsiasi app');
go.textContent = 'Installa l\'app';
later.textContent = 'Non ora';
} else {
st.textContent = p === 'ios' ? 'Aggiungi a Home' : 'Installazione manuale';
ti.textContent = p === 'ios' ? 'Tre tocchi in Safari' : 'Dal menu del browser';
bo.innerHTML = p === 'ios'
? 'Safari non mostra un pulsante automatico: si aggiunge dalla schermata di condivisione.'
: 'Il tuo browser non offre il pulsante automatico: si installa dal menu.';
ste.innerHTML = installStepsHTML(p, false);
go.textContent = 'Ho capito';
later.textContent = 'Non ora';
}
openModal('#install');
}
function bindInstall() {
var ix = $('#install-x');
if (ix) ix.onclick = function () { snoozeInstall(); closeModal('#install'); };
var go = $('#install-go');
if (go) go.onclick = function () {
if (!installEvt) { snoozeInstall(); closeModal('#install'); return; }
var e = installEvt;
installEvt = null;
e.prompt();
e.userChoice.then(function (res) {
closeModal('#install');
if (res.outcome === 'accepted') toast('App installata');
}).catch(function () { closeModal('#install'); });
};
var later = $('#install-later');
if (later) later.onclick = function () {
snoozeInstall();
closeModal('#install');
};
var m = $('#install');
if (m) m.addEventListener('click', function (e) {
if (e.target.id === 'install') { snoozeInstall(); closeModal('#install'); }
});
window.addEventListener('beforeinstallprompt', function (e) {
e.preventDefault();
installEvt = e;
var steps = $('#install-steps');
if (steps) steps.innerHTML = '';
var go = $('#install-go');
if (go) go.style.display = 'flex';
var later = $('#install-later');
if (later) later.textContent = 'Non ora';
});
window.addEventListener('appinstalled', function () {
installEvt = null;
closeModal('#install');
try { localStorage.setItem(LS_INST, '1'); } catch (e) {}
toast('App installata: la trovi nella schermata home');
});
}
function maybeAskInstall() {
if (isStandalone()) return;
if (installSnoozed()) return;
// non sovrapporre al prompt posizione
if (document.querySelector('#geoprompt.open')) {
setTimeout(maybeAskInstall, 4000);
return;
}
showInstallPrompt('auto');
}
// ---------- filtri ----------
function updateFilterBadge() {
var act = (S.band ? 1 : 0) + (S.prov ? 1 : 0) + (S.comune ? 1 : 0) + (S.self ? 1 : 0);
var fc = $('#filterchip'), bd = $('#fcount');
if (bd) {
bd.textContent = act;
bd.className = act ? 'badge-dot on' : 'badge-dot';
}
if (fc) fc.setAttribute('aria-pressed', act ? 'true' : 'false');
}
function openFilters() {
var f = $('#f-fuel');
f.innerHTML = (S.carburanti || ['Benzina']).map(function (x) {
return '';
}).join('');
var b = $('#f-band');
b.innerHTML = '' +
(S.bandiere || []).map(function (x) {
return '';
}).join('');
var p = $('#f-prov');
p.innerHTML = '' +
['AQ', 'CH', 'PE', 'TE'].map(function (x) {
return '';
}).join('');
$('#f-common').value = S.comune || '';
$$('#f-mode button').forEach(function (x) {
x.setAttribute('aria-pressed', String(+x.dataset.m === S.self));
});
openModal('#filters');
}
function bindFilters() {
$('#filterchip').onclick = openFilters;
$('#filtersclose').onclick = function () { closeModal('#filters'); };
$$('#f-mode button').forEach(function (b) {
b.onclick = function () {
$$('#f-mode button').forEach(function (x) { x.setAttribute('aria-pressed', 'false'); });
b.setAttribute('aria-pressed', 'true');
};
});
var fi = $('#f-install');
if (fi) fi.onclick = function () {
closeModal('#filters');
try { localStorage.removeItem('benzina.installsnooze'); } catch (e) {}
showInstallPrompt('manual');
};
$('#f-reset').onclick = function () {
$('#f-fuel').value = 'Benzina';
$('#f-band').value = '';
$('#f-prov').value = '';
$('#f-common').value = '';
$$('#f-mode button')[0].click();
};
$('#f-apply').onclick = function () {
S.fuel = $('#f-fuel').value;
S.band = $('#f-band').value;
S.prov = $('#f-prov').value;
S.comune = $('#f-common').value.trim();
var on = $$('#f-mode button').filter(function (x) { return x.getAttribute('aria-pressed') === 'true'; })[0];
S.self = on ? +on.dataset.m : 0;
savePrefs();
closeModal('#filters');
updateFilterBadge();
load(true);
toast(labelFilters());
};
$('#filters').addEventListener('click', function (e) {
if (e.target.id === 'filters') closeModal('#filters');
});
}
function labelFilters() {
var bits = [S.fuel];
if (S.band) bits.push(S.band);
if (S.prov) bits.push(S.prov);
if (S.comune) bits.push(S.comune);
if (S.self) bits.push('solo self');
return bits.join(' · ');
}
// ---------- prompt posizione ----------
function bindGeoPrompt() {
var gx = $('#geo-x');
if (gx) gx.onclick = function () {
try { localStorage.setItem('benzina.geoask', '1'); } catch (e) {}
closeModal('#geoprompt');
};
$('#geo-on').onclick = function () {
showGeoNote('');
if (geoCurrent === 'inapp' || geoCurrent === 'blocked') {
copyLink();
return;
}
if (geoCurrent === 'denied') {
location.reload();
return;
}
// sincrono, stesso frame del click: e' quello che sblocca il prompt iOS
locate();
};
$('#geo-manual').onclick = function () {
try { localStorage.setItem('benzina.geoask', '1'); } catch (e) {}
closeModal('#geoprompt');
openFilters();
setTimeout(function () { $('#f-common').focus(); }, 400);
};
$('#geo-skip').onclick = function () {
closeModal('#geoprompt');
try { localStorage.setItem('benzina.geoask', '1'); } catch (e) {}
};
$('#geoprompt').addEventListener('click', function (e) {
if (e.target.id === 'geoprompt') closeModal('#geoprompt');
});
}
function copyLink() {
var url = location.origin + location.pathname;
var done = function () { toast('Link copiato: incollalo in Chrome o Safari', 4200); };
var fallback = function () { window.prompt('Copia il link e aprilo in Chrome o Safari:', url); };
var ok = false;
try {
if (navigator.clipboard && navigator.clipboard.writeText) {
var p = navigator.clipboard.writeText(url);
// se il browser non risponde (webview/permessi) non aspettiamo in eterno
var guard = new Promise(function (res) { setTimeout(function () { res('timeout'); }, 1500); });
Promise.race([p.then(function () { ok = true; }), guard]).then(function () {
if (ok) done(); else fallback();
}).catch(fallback);
return;
}
} catch (e) {}
fallback();
}
// ATTENZIONE: getCurrentPosition deve partire DENTRO il gestore del click,
// in modo sincrono. Safari (e iOS in generale) annulla la richiesta se la
// chiamata avviene dopo un await/promise: risponde subito con errore 1 senza
// mostrare il prompt. Per questo qui non si interroga permissions.query.
function askPosition() {
if (inAppBrowser()) { geoState('inapp'); openModal('#geoprompt'); return; }
locate();
}
function maybeAskGeo() {
if (!navigator.geolocation) return;
if (inAppBrowser()) { geoState('inapp'); openModal('#geoprompt'); return; }
if (location.protocol !== 'https:' && location.hostname !== 'localhost') {
geoState('denied', 'Serve HTTPS per chiedere la posizione.');
openModal('#geoprompt');
return;
}
if (navigator.permissions && navigator.permissions.query) {
navigator.permissions.query({ name: 'geolocation' }).then(function (st) {
if (st.state === 'granted') { locate(); return; }
if (st.state === 'denied') { geoState('denied'); openModal('#geoprompt'); return; }
geoState('idle');
openModal('#geoprompt');
}).catch(function () { geoState('idle'); openModal('#geoprompt'); });
} else {
geoState('idle');
openModal('#geoprompt');
}
}
// ---------- boot ----------
function boot() {
listEl = $('#list'); sheet = $('#sheet');
bindInfiniteList();
loadPrefs();
initMap();
bindSetup();
bindChips();
$$('.chip[data-sort]').forEach(function (x) {
x.setAttribute('aria-pressed', String(x.dataset.sort === S.sort));
});
fetch('/api/meta').then(function (r) { return r.json(); }).then(function (d) {
S.carburanti = d.carburanti || [];
S.bandiere = d.bandiere || [];
var dl = $('#comuni-list');
if (dl) {
fetch('/api/comuni').then(function (x) { return x.json(); }).then(function (cs) {
dl.innerHTML = cs.map(function (c) { return '