// Swedish Agricultural Parcel Analysis Module
// Handles Jordbruksverket WFS data for Swedish beekeeping site analysis
// Mirrors analysis_real.js structure (which handles Spanish SIGPAC data)

// ============================================================================
// SWEDISH CROP PHENOLOGY TABLE
// Monthly floral index (0.0-1.0) for Swedish crops and vegetation types
// Sweden's growing season is concentrated May-August with peak in June-July
// ============================================================================
const SWEDISH_CROP_PHENOLOGY = {
  // Major bee-relevant crops
  'raps':         [0.0, 0.0, 0.0, 0.0, 0.7, 0.9, 0.8, 0.1, 0.0, 0.0, 0.0, 0.0], // Rapeseed - peaks late May-June
  'klover':       [0.0, 0.0, 0.0, 0.0, 0.2, 0.6, 0.9, 0.8, 0.5, 0.1, 0.0, 0.0], // Clover - long bloom Jun-Aug
  'vitklover':    [0.0, 0.0, 0.0, 0.0, 0.2, 0.5, 0.9, 0.9, 0.6, 0.2, 0.0, 0.0], // White clover
  'rodklover':    [0.0, 0.0, 0.0, 0.0, 0.1, 0.5, 0.8, 0.8, 0.5, 0.1, 0.0, 0.0], // Red clover
  'alsikeklover': [0.0, 0.0, 0.0, 0.0, 0.1, 0.4, 0.8, 0.7, 0.4, 0.0, 0.0, 0.0], // Alsike clover
  'lind':         [0.0, 0.0, 0.0, 0.0, 0.0, 0.2, 0.9, 0.3, 0.0, 0.0, 0.0, 0.0], // Linden - intense but short July
  'ljung':        [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.1, 0.7, 0.9, 0.2, 0.0, 0.0], // Heather - late season Aug-Sep
  'bovete':       [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.9, 0.6, 0.0, 0.0, 0.0], // Buckwheat - July-Aug
  'senap':        [0.0, 0.0, 0.0, 0.0, 0.3, 0.8, 0.7, 0.2, 0.0, 0.0, 0.0, 0.0], // Mustard
  'fagelvicker':  [0.0, 0.0, 0.0, 0.0, 0.1, 0.5, 0.8, 0.6, 0.2, 0.0, 0.0, 0.0], // Bird's-foot trefoil/vetch
  'lusern':       [0.0, 0.0, 0.0, 0.0, 0.1, 0.4, 0.7, 0.8, 0.5, 0.1, 0.0, 0.0], // Lucerne/alfalfa
  'solros':       [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.3, 0.8, 0.6, 0.0, 0.0, 0.0], // Sunflower (southern Sweden)

  // Berry and fruit crops
  'hallon':       [0.0, 0.0, 0.0, 0.0, 0.1, 0.7, 0.8, 0.3, 0.0, 0.0, 0.0, 0.0], // Raspberry
  'jordgubbar':   [0.0, 0.0, 0.0, 0.0, 0.3, 0.8, 0.4, 0.0, 0.0, 0.0, 0.0, 0.0], // Strawberry
  'blabar':       [0.0, 0.0, 0.0, 0.0, 0.5, 0.7, 0.2, 0.0, 0.0, 0.0, 0.0, 0.0], // Blueberry
  'applen':       [0.0, 0.0, 0.0, 0.0, 0.8, 0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], // Apple
  'korsbarsblom': [0.0, 0.0, 0.0, 0.0, 0.9, 0.3, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], // Cherry blossom
  'fruktodling':  [0.0, 0.0, 0.0, 0.1, 0.7, 0.5, 0.1, 0.0, 0.0, 0.0, 0.0, 0.0], // Fruit orchards generic

  // Wildflowers and natural vegetation
  'vildblommor':  [0.0, 0.0, 0.0, 0.1, 0.4, 0.7, 0.8, 0.7, 0.4, 0.1, 0.0, 0.0], // Wildflowers
  'maskros':      [0.0, 0.0, 0.0, 0.2, 0.8, 0.5, 0.2, 0.1, 0.0, 0.0, 0.0, 0.0], // Dandelion (early)
  'alg':          [0.0, 0.0, 0.0, 0.0, 0.3, 0.6, 0.5, 0.3, 0.1, 0.0, 0.0, 0.0], // Meadow mix
  'skogsblommor': [0.0, 0.0, 0.0, 0.1, 0.5, 0.6, 0.4, 0.2, 0.1, 0.0, 0.0, 0.0], // Forest flowers

  // Trees
  'salix':        [0.0, 0.0, 0.1, 0.7, 0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], // Willow - earliest spring
  'lonn':         [0.0, 0.0, 0.0, 0.1, 0.6, 0.3, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], // Maple
  'bok':          [0.0, 0.0, 0.0, 0.0, 0.4, 0.2, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], // Beech
  'gran':         [0.0, 0.0, 0.0, 0.0, 0.0, 0.1, 0.3, 0.2, 0.0, 0.0, 0.0, 0.0], // Spruce (honeydew)

  // Cereals (low bee value but common)
  'vete':         [0.0, 0.0, 0.0, 0.0, 0.0, 0.1, 0.1, 0.0, 0.0, 0.0, 0.0, 0.0], // Wheat - wind pollinated
  'korn':         [0.0, 0.0, 0.0, 0.0, 0.0, 0.1, 0.1, 0.0, 0.0, 0.0, 0.0, 0.0], // Barley
  'havre':        [0.0, 0.0, 0.0, 0.0, 0.0, 0.1, 0.1, 0.0, 0.0, 0.0, 0.0, 0.0], // Oats
  'rag':          [0.0, 0.0, 0.0, 0.0, 0.0, 0.1, 0.1, 0.0, 0.0, 0.0, 0.0, 0.0], // Rye

  // Land cover types from WFS
  'aker':         [0.0, 0.0, 0.0, 0.1, 0.3, 0.5, 0.5, 0.3, 0.1, 0.0, 0.0, 0.0], // Arable generic
  'bete':         [0.0, 0.0, 0.0, 0.1, 0.4, 0.6, 0.7, 0.6, 0.3, 0.1, 0.0, 0.0], // Pasture
  'slatterang':   [0.0, 0.0, 0.0, 0.1, 0.5, 0.8, 0.9, 0.7, 0.4, 0.1, 0.0, 0.0], // Meadow
  'skogsbete':    [0.0, 0.0, 0.0, 0.1, 0.4, 0.6, 0.6, 0.5, 0.3, 0.1, 0.0, 0.0], // Forest pasture

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

// ============================================================================
// SWEDISH AGOSLAG (LAND TYPE) APICULTURAL VALUES
// Base apicultural value for each Swedish land use category
// ============================================================================
const SWEDISH_AGOSLAG_VALUES = {
  // Primary agricultural types from Jordbruksverket
  'Aker':              0.6,   // Arable land - depends heavily on crop
  'Bete':              0.75,  // Pasture - good wildflower content
  'Slatterang':        0.85,  // Hay meadow - excellent for bees, rich flora
  'Skogsbete':         0.7,   // Forest pasture - mix of woodland and grazing
  'Fruktodling':       0.9,   // Fruit orchards - excellent pollination target
  'Ovrig mark':        0.3,   // Other land - low value
  'Energiskog':        0.4,   // Energy forest (Salix) - early spring value
  'Tradgard':          0.65,  // Garden/horticulture
  'Barrskog':          0.25,  // Coniferous forest - honeydew only
  'Lovskog':           0.55,  // Deciduous forest - linden, maple etc.
  'Blandskog':         0.45,  // Mixed forest
  'Sankmark':          0.35,  // Wetland - some wildflowers
  'Vatten':            0.0,   // Water
  'Bebyggd mark':      0.05,  // Built-up area
  'Impediment':        0.15,  // Impediment/barren
  'Trad och buskmark': 0.5,   // Trees and shrubs
  'Ovrigt akermark':   0.5,   // Other arable
  'Vall':              0.7,   // Ley/temporary grass - clover mixes common
  'Tradda':            0.55,  // Fallow land - wildflowers colonize
  'Gronsaker':         0.4,   // Vegetables - some flowering
  'Potatis':           0.3,   // Potato - minimal bee value
  'Sockerbeta':        0.2,   // Sugar beet - minimal
  'Oljevaxter':        0.85,  // Oilseed crops (rapeseed) - excellent
  'Trindsad':          0.6,   // Grain legumes - peas, beans
  'Fro':               0.5    // Seed crops
};

// ============================================================================
// SWEDISH LAND TYPE ICONS
// Emoji mapping for visualization
// ============================================================================
const SWEDISH_LAND_ICONS = {
  'Aker':              '🌾',
  'Bete':              '🐄',
  'Slatterang':        '🌼',
  'Skogsbete':         '🌲',
  'Fruktodling':       '🍎',
  'Ovrig mark':        '⬜',
  'Energiskog':        '🌿',
  'Tradgard':          '🏡',
  'Barrskog':          '🌲',
  'Lovskog':           '🌳',
  'Blandskog':         '🌳',
  'Sankmark':          '🌊',
  'Vatten':            '💧',
  'Bebyggd mark':      '🏠',
  'Impediment':        '🪨',
  'Trad och buskmark': '🌳',
  'Ovrigt akermark':   '🌾',
  'Vall':              '🍀',
  'Tradda':            '🌻',
  'Gronsaker':         '🥬',
  'Potatis':           '🥔',
  'Sockerbeta':        '🟣',
  'Oljevaxter':        '🌻',
  'Trindsad':          '🟢',
  'Fro':               '🌱',
  'default':           '🟫'
};

// ============================================================================
// CACHE
// ============================================================================
const swedenAnalysisCache = new Map();

let swedenExploracionRapidaCache = {
  center: null,
  radius: null,
  parcelas: null,
  markers: null
};

// ============================================================================
// HELPER: normalize agoslag string for lookup
// Strips Swedish special characters for matching against keys
// ============================================================================
function normalizeAgoslag(raw) {
  if (!raw) return '';
  return raw
    .replace(/[Åå]/g, 'A').replace(/[Ää]/g, 'a')
    .replace(/[Öö]/g, 'O').replace(/[Éé]/g, 'e')
    .replace(/å/gi, 'a').replace(/ä/gi, 'a').replace(/ö/gi, 'o')
    .trim();
}

// Match agoslag to a key in SWEDISH_AGOSLAG_VALUES (case-insensitive, accent-tolerant)
function matchAgoslag(agoslag) {
  if (!agoslag) return null;

  // Direct hit (case-insensitive)
  for (const key of Object.keys(SWEDISH_AGOSLAG_VALUES)) {
    if (key.toLowerCase() === agoslag.toLowerCase()) return key;
  }

  // Normalized comparison
  const normInput = normalizeAgoslag(agoslag).toLowerCase();
  for (const key of Object.keys(SWEDISH_AGOSLAG_VALUES)) {
    if (normalizeAgoslag(key).toLowerCase() === normInput) return key;
  }

  // Partial match
  for (const key of Object.keys(SWEDISH_AGOSLAG_VALUES)) {
    const normKey = normalizeAgoslag(key).toLowerCase();
    if (normInput.includes(normKey) || normKey.includes(normInput)) return key;
  }

  return null;
}

// Get icon for Swedish land type
function getSwedishLandIcon(agoslag) {
  const matched = matchAgoslag(agoslag);
  if (matched && SWEDISH_LAND_ICONS[matched]) return SWEDISH_LAND_ICONS[matched];

  // Try direct key from raw agoslag
  if (agoslag && SWEDISH_LAND_ICONS[agoslag]) return SWEDISH_LAND_ICONS[agoslag];

  return SWEDISH_LAND_ICONS['default'];
}

// ============================================================================
// PHENOLOGY LOOKUP
// Returns floral index 0.0-1.0 for a given land type and month (1-12)
// ============================================================================
function getSwedishFloralIndex(agoslag, month) {
  const idx = Math.max(0, Math.min(11, month - 1));

  // Try to find a phenology entry matching the agoslag
  if (agoslag) {
    const lower = agoslag.toLowerCase()
      .replace(/å/g, 'a').replace(/ä/g, 'a').replace(/ö/g, 'o');

    // Direct lookup
    if (SWEDISH_CROP_PHENOLOGY[lower]) {
      return SWEDISH_CROP_PHENOLOGY[lower][idx];
    }

    // Keyword matching
    const keywords = {
      'aker': 'aker', 'rable': 'aker',
      'bete': 'bete', 'pasture': 'bete',
      'slatter': 'slatterang', 'ang': 'slatterang', 'meadow': 'slatterang',
      'skogsbete': 'skogsbete',
      'frukt': 'fruktodling', 'fruit': 'fruktodling',
      'raps': 'raps', 'oljevaxt': 'raps',
      'klover': 'klover', 'clover': 'klover',
      'ljung': 'ljung', 'heather': 'ljung',
      'lind': 'lind', 'linden': 'lind',
      'vall': 'klover', // ley often contains clover
      'tradda': 'vildblommor', // fallow -> wildflowers
      'energi': 'salix',
      'barr': 'gran', 'gran': 'gran',
      'lov': 'lonn', 'lovskog': 'lonn',
      'hallon': 'hallon', 'jordgubb': 'jordgubbar',
      'bovete': 'bovete', 'buckwheat': 'bovete'
    };

    for (const [kw, phenKey] of Object.entries(keywords)) {
      if (lower.includes(kw)) {
        return SWEDISH_CROP_PHENOLOGY[phenKey][idx];
      }
    }
  }

  return SWEDISH_CROP_PHENOLOGY['default'][idx];
}

// ============================================================================
// calculateValorApicolaSweden(agoslag, month)
// Returns apicultural value 0.0-1.0 combining base value + seasonal phenology
// ============================================================================
function calculateValorApicolaSweden(agoslag, month) {
  if (!month) month = new Date().getMonth() + 1;

  // Get base value from land type
  const matched = matchAgoslag(agoslag);
  let baseValue = matched ? SWEDISH_AGOSLAG_VALUES[matched] : 0.3;

  // Get seasonal floral index
  const floralIndex = getSwedishFloralIndex(agoslag, month);

  // Combine: base value weighted by seasonal activity
  // Even in winter, some base landscape value remains (for planning)
  let valor = baseValue * (0.4 + floralIndex * 0.6);

  // Swedish-specific adjustments
  // Long daylight hours in summer boost nectar production
  if (month >= 5 && month <= 7) {
    valor *= 1.15; // Midnight sun effect on nectar flow
  }

  // Harsh winter penalty
  if (month >= 11 || month <= 2) {
    valor *= 0.1; // Almost no foraging possible
  }

  return Math.min(1.0, Math.max(0.0, valor));
}

// ============================================================================
// calculateCentroid(geometry)
// Computes centroid from GeoJSON geometry
// ============================================================================
function calculateCentroidSweden(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 coord of coords) {
        lng += coord[0];
        lat += coord[1];
      }
      return { lat: lat / coords.length, lng: lng / coords.length };
    }

    if (geometry.type === 'MultiPolygon') {
      const firstPoly = geometry.coordinates[0][0];
      let lat = 0, lng = 0;
      for (const coord of firstPoly) {
        lng += coord[0];
        lat += coord[1];
      }
      return { lat: lat / firstPoly.length, lng: lng / firstPoly.length };
    }

    return null;
  } catch (e) {
    return null;
  }
}

// ============================================================================
// getAllParcelasSweden(center, radiusKm)
// Fetches agricultural block data from Jordbruksverket WFS via BACKEND proxy
// Returns array of parcela objects
// ============================================================================
async function getAllParcelasSweden(center, radiusKm = 5) {
  const cacheKey = `se_${center.lat.toFixed(4)}_${center.lng.toFixed(4)}_${radiusKm}`;

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

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

  // Convert radius to bounding box in degrees
  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 Jordbruksverket WFS...');

  while (hasMore) {
    try {
      const startIndex = page * pageSize;
      const wfsUrl = 'http://epub.sjv.se/inspire/inspire/wfs' +
        '?service=WFS' +
        '&version=2.0.0' +
        '&request=GetFeature' +
        '&typeNames=inspire:senaste_arslager_block' +
        '&outputFormat=application/json' +
        '&srsName=EPSG:4326' +
        '&count=' + pageSize +
        '&startIndex=' + startIndex +
        '&bbox=' + west + ',' + south + ',' + east + ',' + north + ',EPSG:4326';

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

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

      const response = await fetch(proxyUrl);

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

      const geojson = await response.json();

      if (!geojson || !geojson.features || geojson.features.length === 0) {
        logAnalysis('[Sweden] 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 = calculateCentroidSweden(geometry);
        if (!centroid) continue;

        const agoslag = props.agoslag || props.AGOSLAG || '';
        const areal = parseFloat(props.areal || props.AREAL || 0);
        const blockid = props.blockid || props.BLOCKID || '';
        const regionKod = props.region_kod || props.REGION_KOD || '';
        const kategori = props.kategori || props.KATEGORI || '';

        const valorApicola = calculateValorApicolaSweden(agoslag, month);

        parcelas.push({
          id: blockid + '_' + parcelas.length,
          cultivoEspecifico: agoslag,
          superficie: areal.toFixed(2) + ' ha',
          superficieNum: areal,
          lat: centroid.lat,
          lng: centroid.lng,
          valorApicola: valorApicola,
          blockid: blockid,
          regionKod: regionKod,
          kategori: kategori,
          source: 'Jordbruksverket'
        });
      }

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

      // If we got fewer than pageSize, we are done
      if (features.length < pageSize) {
        hasMore = false;
      } else {
        page++;
        // Small delay to be polite to the WFS server
        await new Promise(resolve => setTimeout(resolve, 200));
      }

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

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

  // Cache the result
  swedenAnalysisCache.set(cacheKey, parcelas);
  console.log('[Sweden] Cached - Key:', cacheKey, 'Parcels:', parcelas.length);

  return parcelas;
}

// ============================================================================
// findBeeLocationsSwedenByGeography()
// Quick exploration: fetches parcels and shows top 6 locations on map
// ============================================================================
async function findBeeLocationsSwedenByGeography() {
  console.log('[Sweden] Starting quick bee location exploration');

  let center, radiusKm;

  if (typeof currentCircle !== 'undefined' && currentCircle) {
    center = currentCircle.getLatLng();
    radiusKm = currentCircle.getRadius() / 1000;
  } else {
    center = map.getCenter();
    // Calculate radius from visible map bounds instead of fixed 5km
    const bounds = map.getBounds();
    const latSpan = bounds.getNorth() - bounds.getSouth();
    radiusKm = Math.min((latSpan / 2) * 111, 50); // half the visible area, max 50km
    console.log('[Sweden] Quick exploration: using map bounds radius =', radiusKm.toFixed(1), 'km');
  }

  // Check if we can reuse the quick exploration cache
  if (swedenExploracionRapidaCache.center &&
      swedenExploracionRapidaCache.center.lat === center.lat &&
      swedenExploracionRapidaCache.center.lng === center.lng &&
      swedenExploracionRapidaCache.radius === radiusKm &&
      swedenExploracionRapidaCache.parcelas) {
    console.log('[Sweden] Using quick exploration cache');
    visualizeParcelasSweden(swedenExploracionRapidaCache.parcelas);
    return;
  }

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

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

    if (parcelas.length === 0) {
      hideProgressPopup();
      alert('No agricultural blocks found in this area from Jordbruksverket. Make sure you are looking at Sweden.');
      return;
    }

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

    // Filter parcels with good apicultural value
    const goodParcelas = parcelas
      .filter(p => p.valorApicola > 0.4)
      .sort((a, b) => b.valorApicola - a.valorApicola);

    // Take top 6 diverse locations (avoid clustering)
    const selected = [];
    const minDistKm = radiusKm * 0.15; // Minimum spacing between selections

    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 not enough spread-out parcels, just take top ones
    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...');

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

    // Show markers
    selected.forEach((parcela, index) => {
      const icon = getSwedishLandIcon(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: 'sweden-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: #2563eb;">' + icon + ' ' + (parcela.cultivoEspecifico || 'Unknown') + '</h4>' +
          '<div><strong>Blockid:</strong> ' + parcela.blockid + '</div>' +
          '<div><strong>Agoslag (land type):</strong> ' + parcela.cultivoEspecifico + '</div>' +
          '<div><strong>Area:</strong> ' + parcela.superficie + '</div>' +
          '<div><strong>Region:</strong> ' + parcela.regionKod + '</div>' +
          '<div><strong>Kategori:</strong> ' + parcela.kategori + '</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: Jordbruksverket WFS</small>' +
        '</div>'
      );

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

    // Update cache
    swedenExploracionRapidaCache = {
      center: center,
      radius: radiusKm,
      parcelas: selected,
      markers: analysisMarkers.slice()
    };

    updateProgressPopup(3, 3, 100, 'Done! Found ' + selected.length + ' locations.');

    setTimeout(() => {
      hideProgressPopup();
    }, 1500);

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

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

// ============================================================================
// performDeepAnalysisSweden()
// Deep zone analysis: grid-based aggregation of parcel data
// Shows top 10 recommended beekeeping zones
// ============================================================================
async function performDeepAnalysisSweden() {
  // Clear previous analysis markers
  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('[Sweden] Deep analysis: using map bounds radius =', radiusKm.toFixed(1), 'km');
  }

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

  // STEP 1: Fetch all parcels
  updateProgressPopup(1, 5, 10, 'Fetching all Swedish agricultural blocks...');
  const parcelas = await getAllParcelasSweden(center, radiusKm);

  if (parcelas.length === 0) {
    logAnalysis('[Sweden] No parcels found in area');
    hideProgressPopup();
    stopLogging();
    alert('No agricultural blocks found in this area from Jordbruksverket. Make sure you are looking at Sweden.');
    return;
  }

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

  // STEP 3: Build grid and aggregate
  updateProgressPopup(3, 5, 50, 'Building analysis grid (~1km cells)...');

  const gridSize = 0.009; // ~1km at Swedish latitudes (~58-68 N)
  const zonas = new Map();

  const parcelasMeliferas = parcelas.filter(p => p.valorApicola > 0.3);
  logAnalysis('[Sweden] 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 * gridSize + gridSize / 2,
        lng: gridX * gridSize + gridSize / 2,
        parcelas: [],
        valorTotal: 0,
        superficieTotal: 0
      });
    }

    const zona = zonas.get(gridKey);
    zona.parcelas.push(parcela);
    zona.valorTotal += parcela.valorApicola * parcela.superficieNum;
    zona.superficieTotal += parcela.superficieNum;
  });

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

  const zonasArray = Array.from(zonas.values())
    .filter(zona => zona.parcelas.length >= 1)
    .map(zona => ({
      ...zona,
      score: zona.superficieTotal > 0 ? zona.valorTotal / zona.superficieTotal : 0,
      densidad: zona.parcelas.length
    }))
    .sort((a, b) => b.score - a.score)
    .slice(0, 10);

  logAnalysis('[Sweden] Top zones found: ' + zonasArray.length);

  // STEP 5: Show recommended zones
  updateProgressPopup(5, 5, 90, 'Placing zone recommendations...');

  zonasArray.forEach((zona, index) => {
    const color = index < 3 ? '#22c55e' : index < 6 ? '#f59e0b' : '#ef4444';
    const size = index < 3 ? 30 : index < 6 ? 25 : 20;
    const scorePct = Math.round(zona.score * 100);

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

    // Build land type summary
    const landTypeCounts = {};
    zona.parcelas.forEach(p => {
      const lt = p.cultivoEspecifico || 'Unknown';
      landTypeCounts[lt] = (landTypeCounts[lt] || 0) + 1;
    });
    const landTypeSummary = Object.entries(landTypeCounts)
      .sort((a, b) => b[1] - a[1])
      .slice(0, 8)
      .map(([type, count]) => getSwedishLandIcon(type) + ' ' + type + ' (' + count + ')')
      .join(' &bull; ');

    // Seasonal advice
    const month = new Date().getMonth() + 1;
    let seasonalAdvice = '';
    if (month >= 5 && month <= 7) {
      seasonalAdvice = 'Peak season! Long daylight hours maximize nectar production.';
    } else if (month === 4 || month === 8) {
      seasonalAdvice = 'Shoulder season. Willow (spring) or heather (late summer) may provide resources.';
    } else if (month >= 9 && month <= 10) {
      seasonalAdvice = 'Late season. Consider heather moorland areas for final harvest.';
    } else {
      seasonalAdvice = 'Winter period. Use this data for planning next season\'s apiary placement.';
    }

    // Hive density recommendation
    const hiveDensity = Math.min(8, Math.max(2, Math.round(zona.superficieTotal / 40)));

    marker.bindPopup(
      '<div style="width: 55vw; max-width: none; min-width: 400px;">' +
        '<h4 style="margin: 0 0 12px 0; text-align: center; color: #2563eb;">Recommended Zone #' + (index + 1) + ' (Sweden)</h4>' +

        '<div style="background: #f8f9fa; padding: 12px; border-radius: 6px; margin-bottom: 12px;">' +
          '<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px; font-size: 13px;">' +
            '<div><strong>Suitability Score:</strong> ' +
              '<span style="background: ' + color + '; color: white; padding: 2px 8px; border-radius: 12px; font-weight: bold;">' +
                scorePct + '%</span></div>' +
            '<div><strong>Ranking:</strong> #' + (index + 1) + ' of ' + zonasArray.length + '</div>' +
            '<div><strong>Blocks Analyzed:</strong> ' + zona.parcelas.length + '</div>' +
            '<div><strong>Total Area:</strong> ' + zona.superficieTotal.toFixed(1) + ' ha</div>' +
            '<div><strong>Recommended Hives:</strong> ' + hiveDensity + '</div>' +
            '<div><strong>Block Density:</strong> ' + zona.densidad + ' per cell</div>' +
          '</div>' +
        '</div>' +

        '<div style="border-left: 4px solid #3b82f6; padding-left: 12px; margin: 12px 0;">' +
          '<div style="font-weight: bold; color: #1e40af; margin-bottom: 6px; font-size: 14px;">Why this zone?</div>' +
          '<div style="font-size: 13px; line-height: 1.4; color: #374151;">' +
            'This zone ranks #' + (index + 1) + ' with ' + zona.parcelas.length + ' agricultural blocks ' +
            'covering ' + zona.superficieTotal.toFixed(1) + ' ha. ' +
            (scorePct >= 70 ? 'Excellent concentration of bee-friendly land types.' :
             scorePct >= 50 ? 'Good mix of agricultural land types for beekeeping.' :
             'Moderate potential, suitable as a secondary or seasonal location.') +
          '</div>' +
        '</div>' +

        '<div style="border-left: 4px solid #f59e0b; padding-left: 12px; margin: 12px 0;">' +
          '<div style="font-weight: bold; color: #92400e; margin-bottom: 6px; font-size: 14px;">Seasonal Advice</div>' +
          '<div style="font-size: 13px; line-height: 1.4; color: #374151;">' + seasonalAdvice + '</div>' +
        '</div>' +

        '<div style="background: #f0f9ff; padding: 10px; border-radius: 6px; margin: 12px 0;">' +
          '<div style="font-weight: bold; color: #0369a1; margin-bottom: 6px; font-size: 13px;">Land Types in Zone</div>' +
          '<div style="font-size: 12px; line-height: 1.3; color: #374151; max-height: 80px; overflow-y: auto;">' +
            landTypeSummary +
          '</div>' +
        '</div>' +

        '<small style="color: #666; font-size: 11px; text-align: center; display: block;">' +
          'Analysis based on Jordbruksverket official data ' + new Date().getFullYear() +
        '</small>' +
      '</div>',
      {
        maxWidth: 'none',
        minWidth: 400,
        className: 'sweden-zone-analysis-popup'
      }
    );

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

  updateProgressPopup(5, 5, 100, 'Analysis complete!');

  logAnalysis('[Sweden] DEEP ANALYSIS COMPLETE: ' + parcelas.length + ' parcels, ' + zonasArray.length + ' zones recommended');

  stopLogging();

  // Show completion summary
  setTimeout(() => {
    hideProgressPopup();
    const validParcels = parcelas.filter(p => p.valorApicola > 0).length;
    showAnalysisComplete(validParcels, parcelas.length, zonasArray.length);
  }, 1000);
}

// ============================================================================
// visualizeParcelasSweden(parcelas)
// Shows parcel markers on map with Swedish land type icons
// ============================================================================
function visualizeParcelasSweden(parcelas) {
  logAnalysis('[Sweden] Visualizing ' + parcelas.length + ' parcels');

  parcelas.forEach(parcela => {
    if (!parcela.lat || !parcela.lng) return;

    const icon = getSwedishLandIcon(parcela.cultivoEspecifico);
    const pct = Math.round(parcela.valorApicola * 100);
    const borderColor = pct >= 60 ? '#22c55e' : pct >= 40 ? '#f59e0b' : '#9ca3af';

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

    marker.bindPopup(
      '<div style="font-family: Arial, sans-serif;">' +
        '<h4 style="margin: 0 0 8px 0; color: #2563eb;">' + icon + ' ' + (parcela.cultivoEspecifico || 'Unknown') + '</h4>' +
        '<div><strong>Blockid:</strong> ' + parcela.blockid + '</div>' +
        '<div><strong>Land Type:</strong> ' + parcela.cultivoEspecifico + '</div>' +
        '<div><strong>Area:</strong> ' + parcela.superficie + '</div>' +
        '<div><strong>Region:</strong> ' + parcela.regionKod + '</div>' +
        '<div><strong>Kategori:</strong> ' + parcela.kategori + '</div>' +
        '<div><strong>Bee Potential:</strong> ' + pct + '%</div>' +
      '</div>'
    );

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