// ============================================================================
// Italian Agricultural Parcel Analysis Module
// National cadastral WMS (Agenzia delle Entrate) + Regional WFS (Emilia-Romagna)
// ============================================================================

// Italian cadastral WMS URL (national)
const ITALY_CADASTRAL_WMS = 'https://wms.cartografia.agenziaentrate.gov.it/inspire/wms/ows01.php';

// Emilia-Romagna WFS URL (regional land use)
const ITALY_ER_WFS = 'http://servizigis.regione.emilia-romagna.it/wfs/uso_del_suolo';
const ITALY_ER_LAYER = '_020_uso_suolo_ed2023';

// Emilia-Romagna bounding box (approximate)
const ER_BOUNDS = { south: 43.7, north: 45.15, west: 9.2, east: 12.8 };

// ============================================================================
// ITALIAN LAND USE PHENOLOGY TABLE
// Monthly floral index (0.0-1.0) based on Emilia-Romagna land use codes
// ============================================================================
const ITALIAN_CROP_PHENOLOGY = {
  // Seminativi (arable crops)
  'seminativi':       [0.0, 0.0, 0.0, 0.1, 0.5, 0.8, 0.7, 0.4, 0.1, 0.0, 0.0, 0.0],
  'cereali':          [0.0, 0.0, 0.0, 0.0, 0.2, 0.3, 0.1, 0.0, 0.0, 0.0, 0.0, 0.0],
  'girasole':         [0.0, 0.0, 0.0, 0.0, 0.0, 0.1, 0.8, 0.9, 0.3, 0.0, 0.0, 0.0],
  'colza':            [0.0, 0.0, 0.0, 0.3, 0.8, 0.9, 0.2, 0.0, 0.0, 0.0, 0.0, 0.0],
  'erba medica':      [0.0, 0.0, 0.0, 0.1, 0.5, 0.8, 0.9, 0.7, 0.4, 0.1, 0.0, 0.0],
  'leguminose':       [0.0, 0.0, 0.0, 0.1, 0.4, 0.7, 0.8, 0.5, 0.2, 0.0, 0.0, 0.0],
  'orticole':         [0.0, 0.0, 0.0, 0.2, 0.4, 0.6, 0.7, 0.6, 0.3, 0.1, 0.0, 0.0],

  // Coltivazioni permanenti
  'vigneti':          [0.0, 0.0, 0.0, 0.0, 0.3, 0.7, 0.5, 0.2, 0.0, 0.0, 0.0, 0.0],
  'frutteti':         [0.0, 0.0, 0.1, 0.5, 0.8, 0.5, 0.2, 0.1, 0.0, 0.0, 0.0, 0.0],
  'oliveti':          [0.0, 0.0, 0.0, 0.0, 0.4, 0.7, 0.3, 0.0, 0.0, 0.0, 0.0, 0.0],
  'agrumeti':         [0.0, 0.0, 0.2, 0.6, 0.8, 0.5, 0.1, 0.0, 0.0, 0.0, 0.1, 0.0],
  'castagneti':       [0.0, 0.0, 0.0, 0.0, 0.1, 0.5, 0.6, 0.2, 0.0, 0.0, 0.0, 0.0],

  // Prati e pascoli
  'prati':            [0.0, 0.0, 0.0, 0.2, 0.6, 0.8, 0.7, 0.5, 0.3, 0.1, 0.0, 0.0],
  'pascoli':          [0.0, 0.0, 0.0, 0.2, 0.5, 0.7, 0.6, 0.4, 0.2, 0.1, 0.0, 0.0],
  'prati avvicendati':[0.0, 0.0, 0.0, 0.2, 0.5, 0.8, 0.8, 0.6, 0.3, 0.1, 0.0, 0.0],

  // Boschi e aree naturali
  'boschi latifoglie': [0.0, 0.0, 0.0, 0.1, 0.4, 0.5, 0.3, 0.2, 0.1, 0.0, 0.0, 0.0],
  'boschi conifere':   [0.0, 0.0, 0.0, 0.0, 0.1, 0.2, 0.3, 0.2, 0.0, 0.0, 0.0, 0.0],
  'boschi misti':      [0.0, 0.0, 0.0, 0.1, 0.3, 0.4, 0.3, 0.2, 0.1, 0.0, 0.0, 0.0],
  'macchia':           [0.0, 0.0, 0.0, 0.2, 0.5, 0.7, 0.6, 0.4, 0.2, 0.0, 0.0, 0.0],
  'vegetazione arbustiva': [0.0, 0.0, 0.0, 0.2, 0.4, 0.6, 0.5, 0.3, 0.2, 0.0, 0.0, 0.0],

  // Default
  'default':          [0.0, 0.0, 0.0, 0.1, 0.3, 0.5, 0.4, 0.3, 0.1, 0.0, 0.0, 0.0]
};

// ============================================================================
// ITALIAN LAND USE BASE VALUES (Emilia-Romagna SIGLA codes)
// Apicultural value 0.0-1.0
// ============================================================================
const ITALIAN_LANDUSE_VALUES = {
  // High apicultural value
  'Fr': 0.90, // Frutteti (fruit orchards)
  'Ol': 0.85, // Oliveti
  'Ag': 0.80, // Agrumeti (citrus)
  'Cs': 0.80, // Castagneti da frutto
  'Vi': 0.75, // Vigneti
  'Pp': 0.75, // Prati permanenti
  'Pa': 0.70, // Pascoli
  'Se': 0.65, // Seminativi (arable)
  'Or': 0.70, // Orti (vegetable gardens)
  'Ri': 0.60, // Risaie
  'Fl': 0.85, // Floricoltura (floriculture)
  'Vi': 0.75, // Vivai (nurseries)

  // Medium value
  'Bl': 0.55, // Boschi di latifoglie (deciduous forest)
  'Bm': 0.45, // Boschi misti
  'Bc': 0.30, // Boschi di conifere
  'Rb': 0.50, // Rimboschimento
  'Va': 0.55, // Vegetazione arbustiva
  'Ma': 0.60, // Macchia mediterranea
  'Ar': 0.40, // Arboricoltura da legno
  'In': 0.20, // Incolti (uncultivated)

  // Low value
  'Aa': 0.10, // Acquacolture
  'Ac': 0.05, // Acque (water)
  'Ur': 0.05, // Urbano
  'St': 0.05, // Strade
  'Ca': 0.10, // Cave
  'Di': 0.05, // Discariche
  'Ae': 0.10, // Aree estrattive
  'Zo': 0.05, // Zone industriali
  'Fe': 0.05, // Ferrovie
  'Po': 0.05, // Porti
};

// ============================================================================
// ICON MAPPING
// ============================================================================
function getItalianLandIcon(descr) {
  if (!descr) return '📍';
  const d = descr.toLowerCase();
  if (d.includes('frutt') || d.includes('pomacee') || d.includes('drupacee')) return '🍎';
  if (d.includes('oliv') || d.includes('olei')) return '🫒';
  if (d.includes('vignet') || d.includes('vite')) return '🍇';
  if (d.includes('agrum') || d.includes('aranc') || d.includes('limon')) return '🍊';
  if (d.includes('castagn')) return '🌰';
  if (d.includes('semina') || d.includes('cereal') || d.includes('grano') || d.includes('frumento')) return '🌾';
  if (d.includes('girasol')) return '🌻';
  if (d.includes('mais') || d.includes('granoturco')) return '🌽';
  if (d.includes('riso') || d.includes('risai')) return '🍚';
  if (d.includes('prato') || d.includes('pascol') || d.includes('foragger')) return '🌿';
  if (d.includes('ort') || d.includes('legum')) return '🥬';
  if (d.includes('flor') || d.includes('fiori')) return '🌸';
  if (d.includes('bosco') || d.includes('boschi') || d.includes('foresta') || d.includes('latifoglie')) return '🌳';
  if (d.includes('conifer') || d.includes('abete') || d.includes('pino')) return '🌲';
  if (d.includes('acqua') || d.includes('fiume') || d.includes('lago')) return '💧';
  if (d.includes('urban') || d.includes('residen') || d.includes('commer') || d.includes('industr')) return '🏠';
  if (d.includes('incolto') || d.includes('abbandon')) return '🏜️';
  if (d.includes('macchia') || d.includes('arbust')) return '🌿';
  return '📍';
}

// ============================================================================
// SCORING
// ============================================================================

function matchItalianLanduse(sigla) {
  if (!sigla) return null;
  const s = sigla.trim();
  // Try exact match first
  if (ITALIAN_LANDUSE_VALUES[s] !== undefined) return s;
  // Try first two characters
  const s2 = s.substring(0, 2);
  if (ITALIAN_LANDUSE_VALUES[s2] !== undefined) return s2;
  return null;
}

function getItalianFloralIndex(descr, month) {
  if (!descr) return ITALIAN_CROP_PHENOLOGY['default'][month - 1];
  const d = descr.toLowerCase();

  if (d.includes('girasol')) return ITALIAN_CROP_PHENOLOGY['girasole'][month - 1];
  if (d.includes('colza')) return ITALIAN_CROP_PHENOLOGY['colza'][month - 1];
  if (d.includes('medica') || d.includes('erba medica')) return ITALIAN_CROP_PHENOLOGY['erba medica'][month - 1];
  if (d.includes('vignet') || d.includes('vite')) return ITALIAN_CROP_PHENOLOGY['vigneti'][month - 1];
  if (d.includes('frutt') || d.includes('pomacee') || d.includes('drupacee')) return ITALIAN_CROP_PHENOLOGY['frutteti'][month - 1];
  if (d.includes('oliv')) return ITALIAN_CROP_PHENOLOGY['oliveti'][month - 1];
  if (d.includes('agrum')) return ITALIAN_CROP_PHENOLOGY['agrumeti'][month - 1];
  if (d.includes('castagn')) return ITALIAN_CROP_PHENOLOGY['castagneti'][month - 1];
  if (d.includes('semina') || d.includes('cereal') || d.includes('grano')) return ITALIAN_CROP_PHENOLOGY['seminativi'][month - 1];
  if (d.includes('legum')) return ITALIAN_CROP_PHENOLOGY['leguminose'][month - 1];
  if (d.includes('ort')) return ITALIAN_CROP_PHENOLOGY['orticole'][month - 1];
  if (d.includes('prato') && d.includes('avvicend')) return ITALIAN_CROP_PHENOLOGY['prati avvicendati'][month - 1];
  if (d.includes('prato') || d.includes('prati')) return ITALIAN_CROP_PHENOLOGY['prati'][month - 1];
  if (d.includes('pascol')) return ITALIAN_CROP_PHENOLOGY['pascoli'][month - 1];
  if (d.includes('latifoglie')) return ITALIAN_CROP_PHENOLOGY['boschi latifoglie'][month - 1];
  if (d.includes('conifer')) return ITALIAN_CROP_PHENOLOGY['boschi conifere'][month - 1];
  if (d.includes('bosco') || d.includes('boschi')) return ITALIAN_CROP_PHENOLOGY['boschi misti'][month - 1];
  if (d.includes('macchia')) return ITALIAN_CROP_PHENOLOGY['macchia'][month - 1];
  if (d.includes('arbust')) return ITALIAN_CROP_PHENOLOGY['vegetazione arbustiva'][month - 1];

  return ITALIAN_CROP_PHENOLOGY['default'][month - 1];
}

function calculateValorApicolaItaly(sigla, descr, month) {
  // Base value from land use code
  const matched = matchItalianLanduse(sigla);
  let baseValue = matched ? ITALIAN_LANDUSE_VALUES[matched] : 0.3;

  // Seasonal floral index
  const floralIndex = getItalianFloralIndex(descr, month);

  // Score = base × seasonal adjustment
  let score = baseValue * (0.4 + floralIndex * 0.6);

  // Mediterranean climate bonus: longer growing season in Italy
  if (month >= 4 && month <= 9) {
    score *= 1.1;
  }

  // Winter penalty
  if (month >= 12 || month <= 2) {
    score *= 0.15;
  }

  return Math.min(score, 1.0);
}

// ============================================================================
// CENTROID CALCULATION
// ============================================================================
function calculateCentroidItaly(geometry) {
  if (!geometry || !geometry.coordinates) return null;
  try {
    if (geometry.type === 'Point') {
      return { lat: geometry.coordinates[1], lng: geometry.coordinates[0] };
    }
    if (geometry.type === 'Polygon') {
      const coords = geometry.coordinates[0];
      let lat = 0, lng = 0;
      for (const c of coords) { lng += c[0]; lat += c[1]; }
      return { lat: lat / coords.length, lng: lng / coords.length };
    }
    if (geometry.type === 'MultiPolygon') {
      const ring = geometry.coordinates[0][0];
      let lat = 0, lng = 0;
      for (const c of ring) { lng += c[0]; lat += c[1]; }
      return { lat: lat / ring.length, lng: lng / ring.length };
    }
    return null;
  } catch (e) { return null; }
}

// ============================================================================
// CHECK IF POINT IS IN EMILIA-ROMAGNA
// ============================================================================
function isInEmiliaRomagna(lat, lng) {
  return lat >= ER_BOUNDS.south && lat <= ER_BOUNDS.north &&
         lng >= ER_BOUNDS.west && lng <= ER_BOUNDS.east;
}

// ============================================================================
// CACHE
// ============================================================================
const italyAnalysisCache = new Map();
let italyExploracionRapidaCache = { center: null, radius: null, parcelas: null, markers: null };

// ============================================================================
// getAllParcelasItaly(center, radiusKm)
// Fetches land use data from Emilia-Romagna WFS
// ============================================================================
async function getAllParcelasItaly(center, radiusKm = 5) {
  const cacheKey = `it_${center.lat.toFixed(4)}_${center.lng.toFixed(4)}_${radiusKm}`;

  if (italyAnalysisCache.has(cacheKey)) {
    console.log('[Italy] Using cached data - Key:', cacheKey);
    return italyAnalysisCache.get(cacheKey);
  }

  if (!isInEmiliaRomagna(center.lat, center.lng)) {
    console.warn('[Italy] Center is outside Emilia-Romagna. WFS analysis not available here.');
    logAnalysis('[Italy] Warning: Analysis only available in Emilia-Romagna region.');
    // Still try — the radius might reach into E-R
  }

  logAnalysis('[Italy] Starting WFS query - Center: ' + center.lat.toFixed(4) + ', ' + center.lng.toFixed(4) + ' - Radius: ' + radiusKm + 'km');

  const latDeg = radiusKm / 111.0;
  const lngDeg = radiusKm / (111.0 * Math.cos(center.lat * Math.PI / 180));

  const south = center.lat - latDeg;
  const north = center.lat + latDeg;
  const west = center.lng - lngDeg;
  const east = center.lng + lngDeg;

  const month = new Date().getMonth() + 1;
  const parcelas = [];
  let page = 0;
  const pageSize = 500;
  let totalFetched = 0;
  let hasMore = true;

  updateProgressPopup(0, 1, 5, 'Querying Emilia-Romagna WFS...');

  while (hasMore) {
    try {
      const startIndex = page * pageSize;
      // Note: outputFormat is 'geojson' (not 'application/json' — server rejects that)
      const wfsUrl = ITALY_ER_WFS +
        '?service=WFS' +
        '&version=2.0.0' +
        '&request=GetFeature' +
        '&typeNames=' + ITALY_ER_LAYER +
        '&outputFormat=geojson' +
        '&srsName=EPSG:4326' +
        '&count=' + pageSize +
        '&startIndex=' + startIndex +
        '&bbox=' + south + ',' + west + ',' + north + ',' + east + ',EPSG:4326';

      const proxyUrl = BACKEND + '/proxy?url=' + encodeURIComponent(wfsUrl);

      logAnalysis('[Italy] WFS request page ' + page + ': startIndex=' + startIndex);

      const response = await fetch(proxyUrl);

      if (!response.ok) {
        logAnalysis('[Italy] WFS HTTP error: ' + response.status);
        break;
      }

      const geojson = await response.json();

      if (!geojson || !geojson.features || geojson.features.length === 0) {
        logAnalysis('[Italy] No more features at page ' + page);
        hasMore = false;
        break;
      }

      const features = geojson.features;
      totalFetched += features.length;

      for (const feature of features) {
        const props = feature.properties || {};
        const geometry = feature.geometry;

        const centroid = calculateCentroidItaly(geometry);
        if (!centroid) continue;

        const sigla = props.SIGLA || '';
        const descr = props.DESCR || '';
        const hectares = parseFloat(props.HECTARES || props['SHAPE.AREA'] / 10000 || 0);
        const codTot = props.COD_TOT || '';

        const valorApicola = calculateValorApicolaItaly(sigla, descr, month);

        parcelas.push({
          id: 'IT_' + (props.OBJECTID || parcelas.length),
          cultivoEspecifico: descr || sigla,
          sigla: sigla,
          codTot: codTot,
          superficie: hectares.toFixed(2) + ' ha',
          superficieNum: hectares,
          lat: centroid.lat,
          lng: centroid.lng,
          valorApicola: valorApicola,
          source: 'Emilia-Romagna WFS'
        });
      }

      const pct = Math.min(90, Math.round((totalFetched / Math.max(totalFetched + pageSize, 1)) * 90));
      updateProgressPopup(totalFetched, totalFetched + '?', pct,
        'Fetched ' + totalFetched + ' parcels (' + parcelas.length + ' valid)...');

      if (features.length < pageSize) {
        hasMore = false;
      } else {
        page++;
        await new Promise(resolve => setTimeout(resolve, 200));
      }

    } catch (error) {
      logAnalysis('[Italy] WFS fetch error: ' + error.message);
      hasMore = false;
    }
  }

  logAnalysis('[Italy] Total features fetched: ' + totalFetched + ', valid parcelas: ' + parcelas.length);

  italyAnalysisCache.set(cacheKey, parcelas);
  return parcelas;
}

// ============================================================================
// visualizeParcelasItaly(parcelas)
// ============================================================================
function visualizeParcelasItaly(parcelas) {
  if (typeof analysisMarkers === 'undefined') return;

  // Clear previous
  analysisMarkers.forEach(m => map.removeLayer(m));
  analysisMarkers.length = 0;

  parcelas.forEach(parcela => {
    const icon = getItalianLandIcon(parcela.cultivoEspecifico);
    const pct = Math.round(parcela.valorApicola * 100);
    const color = pct >= 70 ? '#22c55e' : pct >= 50 ? '#f59e0b' : '#9ca3af';

    const marker = L.marker([parcela.lat, parcela.lng], {
      icon: L.divIcon({
        html: '<div style="font-size:14px; text-align:center; background:rgba(255,255,255,0.9); border-radius:50%; width:24px; height:24px; display:flex; align-items:center; justify-content:center; border:2px solid ' + color + ';">' + icon + '</div>',
        className: 'italy-parcela-marker',
        iconSize: [24, 24],
        iconAnchor: [12, 12]
      })
    }).addTo(map);

    marker.bindPopup(
      '<div style="font-family:Arial,sans-serif; min-width:200px;">' +
        '<h4 style="margin:0 0 8px 0; color:#16a34a;">' + icon + ' ' + (parcela.cultivoEspecifico || 'Unknown') + '</h4>' +
        '<div><strong>Code:</strong> ' + parcela.sigla + ' (' + parcela.codTot + ')</div>' +
        '<div><strong>Area:</strong> ' + parcela.superficie + '</div>' +
        '<div><strong>Potential:</strong> <span style="background:' + color + '; color:white; padding:1px 8px; border-radius:10px; font-weight:bold;">' + pct + '%</span></div>' +
        '<small style="color:#666;">Source: ' + parcela.source + '</small>' +
      '</div>'
    );

    marker.isZonaRecomendada = false;
    analysisMarkers.push(marker);
  });
}

// ============================================================================
// findBeeLocationsItalyByGeography() — Quick Exploration
// ============================================================================
async function findBeeLocationsItalyByGeography() {
  console.log('[Italy] Starting quick bee location exploration');

  let center, radiusKm;

  if (typeof currentCircle !== 'undefined' && currentCircle) {
    center = currentCircle.getLatLng();
    radiusKm = currentCircle.getRadius() / 1000;
  } else {
    center = map.getCenter();
    const bounds = map.getBounds();
    const latSpan = bounds.getNorth() - bounds.getSouth();
    radiusKm = Math.min((latSpan / 2) * 111, 50);
    console.log('[Italy] Quick exploration: using map bounds radius =', radiusKm.toFixed(1), 'km');
  }

  // Check cache
  if (italyExploracionRapidaCache.center &&
      italyExploracionRapidaCache.center.lat === center.lat &&
      italyExploracionRapidaCache.center.lng === center.lng &&
      italyExploracionRapidaCache.radius === radiusKm &&
      italyExploracionRapidaCache.parcelas) {
    console.log('[Italy] Using quick exploration cache');
    visualizeParcelasItaly(italyExploracionRapidaCache.parcelas);
    return;
  }

  showProgressPopup();
  updateProgressPopup(0, 3, 10, 'Fetching Italian agricultural data...');

  try {
    const parcelas = await getAllParcelasItaly(center, radiusKm);

    if (parcelas.length === 0) {
      hideProgressPopup();
      alert('No land use parcels found in this area. Note: detailed analysis is currently available only in the Emilia-Romagna region.');
      return;
    }

    updateProgressPopup(1, 3, 50, 'Filtering best bee locations...');

    const goodParcelas = parcelas
      .filter(p => p.valorApicola > 0.4)
      .sort((a, b) => b.valorApicola - a.valorApicola);

    const selected = [];
    const minDistKm = radiusKm * 0.15;

    for (const p of goodParcelas) {
      if (selected.length >= 6) break;
      const tooClose = selected.some(s => {
        const dLat = (s.lat - p.lat) * 111;
        const dLng = (s.lng - p.lng) * 111 * Math.cos(p.lat * Math.PI / 180);
        return Math.sqrt(dLat * dLat + dLng * dLng) < minDistKm;
      });
      if (!tooClose) selected.push(p);
    }

    if (selected.length < 3) {
      const remaining = goodParcelas.filter(p => !selected.includes(p));
      for (const p of remaining) {
        if (selected.length >= 6) break;
        selected.push(p);
      }
    }

    updateProgressPopup(2, 3, 80, 'Placing markers...');

    if (typeof analysisMarkers !== 'undefined') {
      analysisMarkers.forEach(m => map.removeLayer(m));
      analysisMarkers.length = 0;
    }

    selected.forEach((parcela) => {
      const icon = getItalianLandIcon(parcela.cultivoEspecifico);
      const pct = Math.round(parcela.valorApicola * 100);
      const color = pct >= 70 ? '#22c55e' : pct >= 50 ? '#f59e0b' : '#3b82f6';

      const marker = L.marker([parcela.lat, parcela.lng], {
        icon: L.divIcon({
          html: '<div style="font-size:18px; text-align:center; background:rgba(255,255,255,0.9); border-radius:50%; width:28px; height:28px; display:flex; align-items:center; justify-content:center; border:2px solid ' + color + ';">' + icon + '</div>',
          className: 'italy-parcela-marker',
          iconSize: [28, 28],
          iconAnchor: [14, 14]
        })
      }).addTo(map);

      marker.bindPopup(
        '<div style="font-family:Arial,sans-serif; min-width:220px;">' +
          '<h4 style="margin:0 0 8px 0; color:#16a34a;">' + icon + ' ' + (parcela.cultivoEspecifico || 'Unknown') + '</h4>' +
          '<div><strong>Code:</strong> ' + parcela.sigla + ' (' + parcela.codTot + ')</div>' +
          '<div><strong>Area:</strong> ' + parcela.superficie + '</div>' +
          '<div><strong>Potential:</strong> <span style="background:' + color + '; color:white; padding:1px 8px; border-radius:10px; font-weight:bold;">' + pct + '%</span></div>' +
          '<small style="color:#666;">Source: ' + parcela.source + '</small>' +
        '</div>'
      );

      marker.isZonaRecomendada = false;
      analysisMarkers.push(marker);
    });

    italyExploracionRapidaCache = {
      center: center,
      radius: radiusKm,
      parcelas: selected,
      markers: analysisMarkers.slice()
    };

    updateProgressPopup(3, 3, 100, 'Done! Found ' + selected.length + ' locations.');
    setTimeout(() => { hideProgressPopup(); }, 1500);

    logAnalysis('[Italy] Quick exploration complete: ' + selected.length + ' locations from ' + parcelas.length + ' parcels');

  } catch (error) {
    console.error('[Italy] Quick exploration error:', error);
    hideProgressPopup();
    alert('Error fetching Italian data: ' + error.message);
  }
}

// ============================================================================
// performDeepAnalysisItaly() — Deep Zone Analysis
// ============================================================================
async function performDeepAnalysisItaly() {
  if (typeof analysisMarkers !== 'undefined') {
    analysisMarkers.forEach(m => map.removeLayer(m));
    analysisMarkers.length = 0;
  }

  startLogging();
  showProgressPopup();

  let center, radiusKm;

  if (typeof currentCircle !== 'undefined' && currentCircle) {
    center = currentCircle.getLatLng();
    radiusKm = currentCircle.getRadius() / 1000;
  } else {
    center = map.getCenter();
    const bounds = map.getBounds();
    const latSpan = bounds.getNorth() - bounds.getSouth();
    radiusKm = Math.min((latSpan / 2) * 111, 50);
    console.log('[Italy] Deep analysis: using map bounds radius =', radiusKm.toFixed(1), 'km');
  }

  logAnalysis('[Italy] DEEP ANALYSIS START: radius ' + radiusKm + 'km');

  // Step 1: Fetch all parcels
  updateProgressPopup(1, 5, 10, 'Fetching Italian land use data...');
  const parcelas = await getAllParcelasItaly(center, radiusKm);

  if (parcelas.length === 0) {
    logAnalysis('[Italy] No parcels found in area');
    hideProgressPopup();
    stopLogging();
    alert('No land use parcels found. Detailed analysis is currently available only in the Emilia-Romagna region.');
    return;
  }

  // Step 2: Visualize all parcels
  updateProgressPopup(2, 5, 30, 'Visualizing ' + parcelas.length + ' parcels...');
  visualizeParcelasItaly(parcelas);

  // Step 3: Grid aggregation
  updateProgressPopup(3, 5, 50, 'Building analysis grid (~1km cells)...');

  const gridSize = 0.009; // ~1km
  const zonas = new Map();

  const parcelasMeliferas = parcelas.filter(p => p.valorApicola > 0.3);
  logAnalysis('[Italy] Bee-valuable parcels: ' + parcelasMeliferas.length + ' of ' + parcelas.length);

  parcelasMeliferas.forEach(parcela => {
    if (!parcela.lat || !parcela.lng) return;
    const gridX = Math.floor(parcela.lng / gridSize);
    const gridY = Math.floor(parcela.lat / gridSize);
    const gridKey = gridX + '_' + gridY;

    if (!zonas.has(gridKey)) {
      zonas.set(gridKey, {
        lat: (gridY + 0.5) * gridSize,
        lng: (gridX + 0.5) * gridSize,
        parcelas: [],
        totalArea: 0,
        totalScore: 0,
        landTypes: {}
      });
    }

    const zona = zonas.get(gridKey);
    zona.parcelas.push(parcela);
    zona.totalArea += parcela.superficieNum;
    zona.totalScore += parcela.valorApicola;

    const lt = parcela.sigla || 'Unknown';
    zona.landTypes[lt] = (zona.landTypes[lt] || 0) + 1;
  });

  // Step 4: Score and rank
  updateProgressPopup(4, 5, 75, 'Scoring ' + zonas.size + ' zones...');

  const zonasArray = Array.from(zonas.values()).map(zona => {
    const avgScore = zona.totalScore / zona.parcelas.length;
    const diversityBonus = Math.min(Object.keys(zona.landTypes).length * 0.03, 0.15);
    const areaBonus = Math.min(zona.totalArea / 100, 0.1);
    zona.finalScore = Math.min(avgScore + diversityBonus + areaBonus, 1.0);
    return zona;
  });

  zonasArray.sort((a, b) => b.finalScore - a.finalScore);
  const topZonas = zonasArray.slice(0, 10);

  // Step 5: Show top zones
  updateProgressPopup(5, 5, 90, 'Generating recommendations...');

  topZonas.forEach((zona, idx) => {
    const rank = idx + 1;
    const pct = Math.round(zona.finalScore * 100);
    const color = pct >= 70 ? '#22c55e' : pct >= 50 ? '#f59e0b' : '#3b82f6';
    const hiveDensity = Math.round(zona.totalArea * 0.3);

    const landTypeList = Object.entries(zona.landTypes)
      .sort((a, b) => b[1] - a[1])
      .map(([lt, count]) => '<span style="background:#e8f5e9; padding:1px 6px; border-radius:8px; margin:2px; display:inline-block;">' + lt + ' (' + count + ')</span>')
      .join(' ');

    const marker = L.marker([zona.lat, zona.lng], {
      icon: L.divIcon({
        html: '<div style="background:' + color + '; color:white; border-radius:50%; width:32px; height:32px; display:flex; align-items:center; justify-content:center; font-weight:bold; font-size:14px; border:2px solid white; box-shadow:0 2px 6px rgba(0,0,0,0.3);">#' + rank + '</div>',
        className: 'italy-zone-marker',
        iconSize: [32, 32],
        iconAnchor: [16, 16]
      }),
      zIndexOffset: 1000 - idx
    }).addTo(map);

    marker.bindPopup(
      '<div style="font-family:Arial,sans-serif; min-width:280px; max-width:55vw;">' +
        '<h3 style="margin:0 0 8px 0; color:' + color + ';">🇮🇹 Recommended Zone #' + rank + '</h3>' +
        '<div style="display:grid; grid-template-columns:1fr 1fr; gap:4px; margin-bottom:8px;">' +
          '<div><strong>Score:</strong> <span style="background:' + color + '; color:white; padding:1px 8px; border-radius:10px; font-weight:bold;">' + pct + '%</span></div>' +
          '<div><strong>Parcels:</strong> ' + zona.parcelas.length + '</div>' +
          '<div><strong>Total area:</strong> ' + zona.totalArea.toFixed(1) + ' ha</div>' +
          '<div><strong>Hives:</strong> ~' + hiveDensity + ' recommended</div>' +
        '</div>' +
        '<div style="margin-bottom:8px;"><strong>Land types:</strong><br>' + landTypeList + '</div>' +
        '<small style="color:#666;">Analysis based on Regione Emilia-Romagna land use data (2023)</small>' +
      '</div>',
      { maxWidth: 450 }
    );

    marker.isZonaRecomendada = true;
    analysisMarkers.push(marker);
  });

  updateProgressPopup(5, 5, 100, 'Done! ' + topZonas.length + ' zones recommended.');
  setTimeout(() => { hideProgressPopup(); }, 2000);

  logAnalysis('[Italy] Deep analysis complete: ' + topZonas.length + ' zones from ' + parcelas.length + ' parcels');
  stopLogging();
}
