<script>
  import { onMount } from 'svelte';
  import * as L from 'leaflet';
  import 'leaflet/dist/leaflet.css';

  /**
     * @type {{ removeLayer: (arg0: any) => void; setView: (arg0: number[], arg1: any) => void; getZoom: () => any; on: (arg0: string, arg1: (e: any) => void) => void; }}
     */
  let map;
  let mouseLat = 0;
  let mouseLng = 0;
  /**
     * @type {null}
     */
  let marker = null;

  let startPoint = 'Custom';
  let startHeight = 0;
  let startTime = '13:13';
  let startDate = new Date(2025, 2, 24);
  let ascentRate = 5;
  let burstAltitude = 30000;
  let flightProfile = 'Normal';
  let descentRate = 5;
  let forecastMode = 'Single';
  let inputLat = '56.3576';
  let inputLng = '39.8666';

  let showBurstCalculator = false;
  let payloadMass = 1500;
  let balloonMass = 1000;
  let desiredBurstAltitude = 33000;
  let desiredAscentRate = 2.33;

  let burstAltitudeResult = 33000;
  let timeToBurst = 236;
  let initialVolume = 2.66;
  let ascentRateResult = 2.33;
  let liftForce = 1733;
  let volumeLiters = 2662;
  let volumeCubicFeet = 94.0;

  const toggleBurstCalculator = () => {
    showBurstCalculator = !showBurstCalculator;
  };

  const calculateBurst = () => {
    // In a real app, you would implement actual calculations here
    // These are just placeholder values matching your image
    burstAltitudeResult = desiredBurstAltitude;
    timeToBurst = 236;
    initialVolume = 2.66;
    ascentRateResult = desiredAscentRate;
    liftForce = 1733;
    volumeLiters = 2662;
    volumeCubicFeet = 94.0;
  };

  const updateMapPosition = () => {
    const lat = parseFloat(inputLat);
    const lng = parseFloat(inputLng);
    
    if (isNaN(lat)) {
      alert("Please enter a valid latitude");
      return;
    }
    if (isNaN(lng)) {
      alert("Please enter a valid longitude");
      return;
    }
    if (lat < -90 || lat > 90) {
      alert("Latitude must be between -90 and 90");
      return;
    }
    if (lng < -180 || lng > 180) {
      alert("Longitude must be between -180 and 180");
      return;
    }
    
    // Remove existing marker if it exists
    if (marker) {
      map.removeLayer(marker);
    }
    
    // Create new marker
    marker = L.marker([lat, lng]).addTo(map)
      .bindPopup("Launch Point");
    
    // Center map on new coordinates
    map.setView([lat, lng], map.getZoom());
  };
  
  onMount(() => {
    map = L.map('map').setView([51.505, -0.09], 13);
    
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(map);

    map.on('mousemove', (e) => {
      mouseLat = e.latlng.lat.toFixed(6);
      mouseLng = e.latlng.lng.toFixed(6);
    });

    marker = L.marker([56.3576, 39.8666]).addTo(map)
    .bindPopup(() => {
        return `
          <b>Launch Point</b><br>, Lat: ${marker.getLatLng().lat.toFixed(6)}<br>, Long: ${marker.getLatLng().lng.toFixed(6)}<br>
        `;
      });
  });

  // Forecast request function
  const getForecast = async () => {
    // Create request object
    const request = {
      ascent_rate: parseFloat(ascentRate),
      burst_altitude: parseFloat(burstAltitude),
      dataset: new Date().toISOString(), // Current time as dataset timestamp
      descent_rate: parseFloat(descentRate),
      format: "json",
      launch_altitude: parseFloat(startHeight),
      launch_datetime: new Date(
        `${startDate.getFullYear()}-${startDate.getMonth() + 1}-${startDate.getDate()}T${startTime}:00Z`
      ).toISOString(),
      launch_latitude: parseFloat(inputLat),
      launch_longitude: parseFloat(inputLng),
      profile: flightProfile === 'Normal' ? 'standard_profile' : 'custom_profile',
      version: 2
    };

    console.log("Sending request:", request);

    try {
      // Example POST request - replace with your actual API endpoint
      const response = await fetch('https://api.example.com/forecast', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(request)
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data = await response.json();
      console.log("Forecast response:", data);
      alert("Forecast request successful!");
      // Handle the response data as needed
    } catch (error) {
      console.error("Error sending forecast request:", error);
      alert("Error getting forecast: " + error.message);
    }
  };

  // Helper function to format date as YYYY-MM-DD
  const formatDateForAPI = (date) => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  };
</script>

<div class="container-fluid position-relative h-100">
  <div id="map" class="w-100 h-100 position-absolute"></div>
  <div class="position-absolute top-0 end-0 bg-light p-2 rounded shadow-sm">
    Lat: {mouseLat}, Long: {mouseLng}
  </div>
</div>

