// Define the coordinates for the specific point (e.g., the location of interest)
var point = ee.Geometry.Point(90.2611485521762, 23.44690280909043);

// Create a buffer around the point (e.g., 20 kilometers)
var bufferRadius = 20000; // 20 km in meters
var pointBuffer = point.buffer(bufferRadius);

// Create a Landsat 8 Collection 2 Tier 1 image collection for the desired date range
var startDate = '2017-10-01';
var endDate = '2017-10-31';

var landsatCollection2 = ee.ImageCollection('LANDSAT/LC08/C02/T1_TOA')
  .filterBounds(point)
  .filterDate(startDate, endDate);

// Cloud masking function for Landsat
function maskL8Clouds(image) {
  var qa = image.select('QA_PIXEL');
  var cloudMask = qa.bitwiseAnd(1 << 3).eq(0); // Cloud bit is 3rd
  return image.updateMask(cloudMask);
}

// Apply the cloud mask to the collection
var cloudFreeCollection = landsatCollection2.map(maskL8Clouds);

// Print the number of images in the cloud-free collection
var imageCount = cloudFreeCollection.size();
print('Number of cloud-free images in the collection:', imageCount);

// Use JRC Global Surface Water dataset to create a water mask
var waterMask = ee.Image('JRC/GSW1_4/GlobalSurfaceWater').select('occurrence');

// Define water body threshold (e.g., areas with water occurrence > 50% are considered water bodies)
var waterThreshold = 50;
var waterBodies = waterMask.gt(waterThreshold);

// Clip water bodies to the buffer area
var clippedWaterBodies = waterBodies.clip(pointBuffer);

// Mask water bodies in the cloud-free collection
var landOnlyCollection = cloudFreeCollection.map(function(image) {
  return image.updateMask(clippedWaterBodies.not());  // Mask out water bodies
});

// Compute the maximum and minimum temperature across all non-water pixels
var maxTemperature = landOnlyCollection.select('B10').max();
var minTemperature = landOnlyCollection.select('B10').min();

// Convert temperatures from Kelvin to Celsius
var maxTemperatureCelsius = maxTemperature.subtract(273.15);
var minTemperatureCelsius = minTemperature.subtract(273.15);

// Clip the max and min temperature images to the buffer region around the point
var clippedMaxTemperature = maxTemperatureCelsius.clip(pointBuffer);
var clippedMinTemperature = minTemperatureCelsius.clip(pointBuffer);

// Filter out negative temperature pixels (set to null)
var filteredMaxTemperature = clippedMaxTemperature.updateMask(clippedMaxTemperature.gt(0));
var filteredMinTemperature = clippedMinTemperature.updateMask(clippedMinTemperature.gt(0));

// Adjust the scale to match the thermal band resolution (100m)
var maxTempStats = filteredMaxTemperature.reduceRegion({
  reducer: ee.Reducer.max(),
  geometry: pointBuffer,
  scale: 100,  // Updated scale
  bestEffort: true  // Tries to use the best resolution possible
});
var minTempStats = filteredMinTemperature.reduceRegion({
  reducer: ee.Reducer.min(),
  geometry: pointBuffer,
  scale: 100,  // Updated scale
  bestEffort: true  // Tries to use the best resolution possible
});

print('Maximum Temperature (Celsius):', maxTempStats);
print('Minimum Temperature (Celsius):', minTempStats);

// Display the specific point, water bodies, and temperature layers on the map
Map.centerObject(point, 10);
Map.addLayer(point, {color: 'red'}, 'Specific Point');

// Add water bodies to the map with a distinct color (e.g., light blue)
Map.addLayer(
  clippedWaterBodies,
  {palette: ['cyan'], opacity: 0.5},  // Use a distinct color like 'cyan'
  'Water Bodies',
  true  // You can set this to true if you want the water bodies visible by default
);

// Add the filtered max temperature layer to the map
Map.addLayer(
  filteredMaxTemperature,
  {
    min: 0, // Min temperature range (Celsius)
    max: 50, // Max temperature range (Celsius)
    palette: ['blue', 'lightblue', 'green', 'yellow', 'orange', 'red']
  },
  'Filtered Max Land Surface Temperature (Celsius)',
  true,
  0.75
);

// Add the filtered min temperature layer to the map (can toggle display)
Map.addLayer(
  filteredMinTemperature,
  {
    min: 0, // Min temperature range (Celsius)
    max: 50, // Max temperature range (Celsius)
    palette: ['blue', 'lightblue', 'green', 'yellow', 'orange', 'red']
  },
  'Filtered Min Land Surface Temperature (Celsius)',
  true,
  0.75
);

// Add a legend for the temperature range (Max and Min)
var legend = ui.Panel({
  style: {
    position: 'bottom-right',
    padding: '8px 15px'
  }
});
legend.add(ui.Label({
  value: 'Land Surface Temperature (°C)',
  style: {
    fontWeight: 'bold',
    fontSize: '14px',
    margin: '0 0 4px 0',
    padding: '0'
  }
}));

// Define the color palette and corresponding temperature ranges (0-50°C)
var palette = ['blue', 'lightblue', 'green', 'yellow', 'orange', 'red'];
var tempRanges = ['0-8 °C', '9-16 °C', '17-24 °C', '25-32 °C', '33-40 °C', '41-50 °C'];

// Add water bodies legend entry (cyan for water)
legend.add(ui.Label({
  value: 'Water Bodies',
  style: {
    fontWeight: 'bold',
    fontSize: '14px',
    margin: '0 0 4px 0',
    padding: '0'
  }
}));

// Add the water color box
var waterColorBox = ui.Label({
  style: {
    backgroundColor: 'cyan',  // Cyan color for water bodies
    padding: '8px',
    margin: '0 0 4px 0'
  }
});
var waterDescription = ui.Label({
  value: 'Water Bodies',
  style: {margin: '0 0 4px 6px'}
});
legend.add(
  ui.Panel({
    widgets: [waterColorBox, waterDescription],
    layout: ui.Panel.Layout.Flow('horizontal')
  })
);

// Add temperature ranges to the legend
for (var i = 0; i < palette.length; i++) {
  var colorBox = ui.Label({
    style: {
      backgroundColor: palette[i],
      padding: '8px',
      margin: '0 0 4px 0'
    }
  });
  var description = ui.Label({
    value: tempRanges[i],
    style: {margin: '0 0 4px 6px'}
  });
  legend.add(
    ui.Panel({
      widgets: [colorBox, description],
      layout: ui.Panel.Layout.Flow('horizontal')
    })
  );
}
// Add the legend to the map
Map.add(legend);