var destination = (function ($) {
  var country_array = {};
  // World
  country_array['world'] = [];
  // Africa
  country_array['002'] = ['DZ', 'EG', 'EH', 'LY', 'MA', 'SD', 'SS', 'TN', 'BF', 'BJ', 'CI', 'CV', 'GH', 'GM', 'GN', 'GW', 'LR', 'ML', 'MR', 'NE', 'NG', 'SH', 'SL', 'SN', 'TG', 'AO', 'CD', 'ZR', 'CF', 'CG', 'CM', 'GA', 'GQ', 'ST', 'TD', 'BI', 'DJ', 'ER', 'ET', 'KE', 'KM', 'MG', 'MU', 'MW', 'MZ', 'RE', 'RW', 'SC', 'SO', 'TZ', 'UG', 'YT', 'ZM', 'ZW', 'BW', 'LS', 'NA', 'SZ', 'ZA'];
  // Europe
  country_array['150'] = ['GG', 'JE', 'AX', 'DK', 'EE', 'FI', 'FO', 'GB', 'IE', 'IM', 'IS', 'LT', 'LV', 'NO', 'SE', 'SJ', 'AT', 'BE', 'CH', 'DE', 'DD', 'FR', 'FX', 'LI', 'LU', 'MC', 'NL', 'BG', 'BY', 'CZ', 'HU', 'MD', 'PL', 'RO', 'RU', 'SU', 'SK', 'UA', 'AD', 'AL', 'BA', 'ES', 'GI', 'GR', 'HR', 'IT', 'ME', 'MK', 'MT', 'RS', 'PT', 'SI', 'SM', 'VA', 'YU'];
  // N. America
  country_array['021'] = ['BM', 'CA', 'GL', 'PM', 'US'];
  // Caribbean
  country_array['029'] = ['AG', 'AI', 'AN', 'AW', 'BB', 'BL', 'BS', 'CU', 'DM', 'DO', 'GD', 'GP', 'HT', 'JM', 'KN', 'KY', 'LC', 'MF', 'MQ', 'MS', 'PR', 'TC', 'TT', 'VC', 'VG', 'VI'];
  // Central America
  country_array['013'] = ['BZ', 'CR', 'GT', 'HN', 'MX', 'NI', 'PA', 'SV'];
  // S. America
  country_array['005'] = ['AR', 'BO', 'BR', 'CL', 'CO', 'EC', 'FK', 'GF', 'GY', 'PE', 'PY', 'SR', 'UY', 'VE'];
  // Asia
  country_array['142'] = ['TM', 'TJ', 'KG', 'KZ', 'UZ', 'CN', 'HK', 'JP', 'KP', 'KR', 'MN', 'MO', 'TW', 'AF', 'BD', 'BT', 'IN', 'IR', 'LK', 'MV', 'NP', 'PK', 'BN', 'ID', 'KH', 'LA', 'MM', 'BU', 'MY', 'PH', 'SG', 'TH', 'TL', 'TP', 'VN', 'AE', 'AM', 'AZ', 'BH', 'CY', 'GE', 'IL', 'IQ', 'JO', 'KW', 'LB', 'OM', 'PS', 'QA', 'SA', 'NT', 'SY', 'TR', 'YE', 'YD'];
  // Oceania
  country_array['009'] = ['AU', 'NF', 'NZ', 'FJ', 'NC', 'PG', 'SB', 'VU', 'FM', 'GU', 'KI', 'MH', 'MP', 'NR', 'PW', 'AS', 'CK', 'NU', 'PF', 'PN', 'TK', 'TO', 'TV', 'WF', 'WS'];

  function getCountryCode(countryName) {
    if (isoCountries.hasOwnProperty(countryName)) {
      return isoCountries[countryName];
    } else {
      return countryName;
    }
  }

  var countryArr, region, chart, options;

  function openModal(e) {
    if ($('.w--tab-active .origin').val().length < 2) {
      $('.w--tab-active .origin').get(0).focus();
      $('.w--tab-active .origin').get(0).reportValidity();
    }
    else {
      $("#destModal #form").show();
      $("#destModal #geomap").hide();
      $('#choose-region2').prop('selectedIndex', 0);

      $('#destModal').plainModal('open');
      setTimeout(function () {
        // this focus on last character if input isn't empty
        $('#destModal #destination2').get(0).focus();
      }, 400);
      $('#destModal #destination2').val('');
    }
    e.preventDefault();
  }

  $('.destination').unbind('click').click(function (e) {
    openModal(e);
  });
  $('.destination').unbind('keydown').keydown(function (e) {
    openModal(e);
  });

  $('#destModal .anywhere2').unbind('click').click(function (e) {
    $(".anywhere-link").click();
    $('#destModal').plainModal('close');
    e.preventDefault();
  });

  $('#destModal input[type="text"], #destModal input[type="email"], #destModal textarea').focus(function () {
    var background = $(this).attr('id');
    $('#destModal #' + background + '-form').addClass('formgroup-active');
    $('#destModal #' + background + '-form').removeClass('formgroup-error');
  });
  $('#destModal input[type="text"], #destModal input[type="email"], #destModal textarea').blur(function () {
    var background = $(this).attr('id');
    $('#destModal #' + background + '-form').removeClass('formgroup-active');
  });

  var airports = [];
  var map = null;
  var minPrice = 10000;
  var maxPrice = 0;
  var sliderRange;
  var region = null;
  var originPlace = null;
  var currency = null;
  var passengers = 1;

  $('#destModal #choose-region2').unbind('change').change(function (e) {
    region = ($(this).val() !== "") ? $(this).val() : null;
    originPlace = $('.w--tab-active .origin').val();
    currency = $('.w--tab-active .currency').val();

    if (originPlace.length < 2) {
      $('#choose-region2').prop('selectedIndex', 0);
    } else {
      $("#destModal #form").hide();
      $("#destModal #geomap").show();
      $("#departure-date").val('anytime');
      $("#return-date").val('anytime');
      // hide "Show For Anytime" button
      $('#destModal .show-for-anytime').hide();
      $("#slider-range").closest(".irs").css("display", "none");

      fetchAirportData(region, originPlace, 'anytime', 'anytime', currency);
    }
  });

  function fetchAirportData(region, originPlace, dateFlight, dateReturn, currency) {
    const markerLayer = L.layerGroup(); // Declare the markerLayer here

    if (map) {
      markerLayer.clearLayers(); // Clear the existing markers
      airports.length = 0; // Clear the airports array
      minPrice = 10000;
      maxPrice = 0;

      map.remove();
      map = null;
      $('#regions_div').html('');
    }

    $('#regions_div').html('<img class="center loading2" src="/images/loading_multi.gif" />');

    // Fetch airport data from the database
    $.get("https://skysurf.travel/php/index3.php", {
      originPlace: originPlace,
      whereTo: 'anywhere',
      dateFlight: dateFlight,
      dateReturn: dateReturn,
      currency: currency,
      browse: 'routes'
    }, function (data) {
      // Initialize the map
      map = L.map('regions_div').setView([0, 0], 2);

      // Add a tile layer
      L.tileLayer('https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}{r}.png', {
        attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors',
        maxZoom: 18,
      }).addTo(map);

      initializeDatepicker();

      var quotes = data.content.results.quotes;
      var places = data.content.results.places;

      $.each(quotes, function (i, v) {
        var place = places[v.outboundLeg.destinationPlaceId];
        var country = places[places[place.parentId].parentId].name;
        var city = place.name;
        var longitude = place.coordinates.longitude;
        var latitude = place.coordinates.latitude;
        var departure = v.outboundLeg.departureDateTime;
        var returnDate = v.inboundLeg.departureDateTime;

        if (region === 'world' || country_array[region].includes(getCountryCode(country))) {
          airports.push({
            id: i,
            price: parseInt(v.minPrice.amount),
            city: city,
            country: country,
            longitude: longitude,
            latitude: latitude,
            departureDate: departure.month + '/' + departure.day + '/' + departure.year,
            returnDate: returnDate.month + '/' + returnDate.day + '/' + returnDate.year,
            directFlight: v.isDirect,
            lastUpdate: v.outboundLeg.quoteCreationTimestamp,
            destination: city + ' (' + place.iata + ') - ' + country,
            origin: originPlace,
            destIata: place.iata,
          });
        }
      });

      airports.sort((a, b) => a.price - b.price);

      // Remove duplicate cities
      var uniqueCities = [];
      airports.forEach(airport => {
        if (!uniqueCities.some(city => city === airport.city)) {
          uniqueCities.push(airport.city);
        }
      });

      // Remove duplicate countries
      var uniqueAirports = [];
      airports.forEach(airport => {
        if (!uniqueAirports.some(a => a.country === airport.country)) {
          uniqueAirports.push(airport);
        }
      });

      airports = uniqueAirports;

      airports.forEach(airport => {
        const { latitude, longitude, price } = airport;

        if (price < minPrice) {
          minPrice = price;
        }
        if (price > maxPrice) {
          maxPrice = price;
        }

        const markerIcon = L.divIcon({
          className: 'custom-marker',
          html: `<div class="marker-airplane"></div><div class="marker-price" style="background-color: ${getColor(price)}">$${price}</div>`,
          iconSize: [40, 40]
        });

        const marker = L.marker([latitude, longitude], { icon: markerIcon })
          .bindPopup(createPopupContent(airport))
          .addTo(map);

        markerLayer.addLayer(marker);
      });

      markerLayer.addTo(map);

      const bounds = L.featureGroup(markerLayer.getLayers()).getBounds();
      map.fitBounds(bounds);

      // Clear and reinitialize the price range slider
      if ($("#slider-range").data("ionRangeSlider")) {
        $("#slider-range").data("ionRangeSlider").destroy();
      }

      // Clear and reinitialize the price range slider
      if ($("#slider-range").data("ionRangeSlider")) {
        $("#slider-range").data("ionRangeSlider").update({
          from: minPrice,
          to: maxPrice
        });
      } else {
        $("#slider-range").closest("#slider-range-container").html('<input type="text" id="slider-range">');

        $("#slider-range").ionRangeSlider({
          type: "double",
          min: minPrice,
          max: maxPrice,
          from: minPrice,
          to: maxPrice,
          onChange: function (data) {
            filterMarkers(data.from, data.to);
          },
          onStart: function (data) {
            // Store the ionRangeSlider instance
            sliderRange = data.instance;
          }
        });

        // Reset the sliders to the beginning and end
        if (sliderRange) {
          sliderRange.reset().update({
            from: minPrice,
            to: maxPrice
          });
        }
      }
      $("#slider-range").closest(".irs").css("display", "block");

      function filterMarkers(minPrice, maxPrice) {
        markerLayer.eachLayer(layer => {
          const marker = layer;
          const price = marker.options.icon.options.html.match(/\$(\d+)/)[1];

          if (price >= minPrice && price <= maxPrice) {
            marker.addTo(map);
          } else {
            marker.removeFrom(map);
          }
        });
      }
    });
  }

  function createPopupContent(airport) {
    const { departureDate, returnDate, directFlight, price, lastUpdate, origin, destination, destIata } = airport;

    // Create the HTML content for the popup
    const popupContent = `
      <div>
        <strong>Departure Date:</strong> ${formatDate(departureDate)}<br>
        ${returnDate !== '0/0/0' ? '<strong>Return Date:</strong> ' + formatDate(returnDate) + '<br>' : ''}
        <strong>Flight Type: ${directFlight ? '<font color="green">Direct</font>' : '<font color="maroon">Indirect</font>'}</strong><br>
        <strong>Price:</strong> <b>${price} ${currency}</b> per person<br>
        <strong>Last Update:</strong> ${formatTimestamp(lastUpdate)}<br>
        <strong>Origin:</strong> ${origin}<br>
        <strong>Destination:</strong> ${destination}<br><br>
        <button class="choose-departure-time btn btn-primary" data-origin="` + origin + `" data-departure-date="` + formatDate2(departureDate) + `" data-return-date="` + formatDate2(returnDate) + `" data-dest-iata="` + destIata + `">Choose Departure Time</button>
      </div>
    `;

    return popupContent;
  }

  $('#destModal .show-for-anytime').unbind('click').click(function (e) {
    $("#departure-date").val('anytime');
    $("#return-date").val('anytime');
    $(this).hide();

    $('#destModal .update-price-map button').click();

    e.preventDefault();
  });

  var isRoundtrip = true;
  $('#destModal .roundtrip-toggle').unbind('click').click(function (e) {
    $(this).toggleClass('active');

    // Check if the toggle button is active
    if ($(this).hasClass('active')) {
      // Perform actions when it is active
      $(".return-or-one-way-field").show();
      $("#departure-date").val('anytime');
      $("#return-date").val('anytime');
      isRoundtrip = true;
    } else {
      // Perform actions when it is not active
      $(".return-or-one-way-field").hide();
      isRoundtrip = false;
    }

    e.preventDefault();
  });

  $('#destModal .update-price-map button').unbind('click').click(function (e) {
    originPlace = $('.w--tab-active .origin').val();
    currency = $('#currency-modal').val();
    var dateFlight = $.trim($('#departure-date').val());
    var returnFlight = $.trim($('#return-date').val());

    passengers = $('#passengers').val();

    // set both date fields to 'anytime', if only one is anytime.
    if (dateFlight === 'anytime' || returnFlight === 'anytime') {
      dateFlight = 'anytime';
      returnFlight = 'anytime';
      $('#departure-date').val('anytime');
      $('#return-date').val('anytime');
    }

    // error check and handling
    // Regular expression patterns for date formats
    var dateFormat1 = /^\d{4}-\d{2}-\d{2}$/; // YYYY-MM-DD
    var dateFormat2 = /^\d{4}-\d{2}$/; // YYYY-MM

    // Check dateFlight value
    if (dateFlight !== 'anytime' && !dateFormat1.test(dateFlight) && !dateFormat2.test(dateFlight)) {
      $('#regions_div').html('<p>Departure date is invalid. Please enter "anytime" or a valid date format (YYYY-MM-DD or YYYY-MM).</p>');
      return;
    }

    // Check dateFlight value is not in the past
    if (dateFlight !== 'anytime' && dateFlight.length > 7 && isPastDate(dateFlight)) {
      $('#regions_div').html('<p>Departure date cannot be a past date.</p>');
      return;
    }

    // Check returnFlight value
    if (isRoundtrip && returnFlight !== 'anytime' && !dateFormat1.test(returnFlight) && !dateFormat2.test(returnFlight)) {
      $('#regions_div').html('<p>Return date is invalid. Please enter "anytime" or a valid date format (YYYY-MM-DD or YYYY-MM).</p>');
      return;
    }

    // Check returnFlight value is not in the past
    if (isRoundtrip && returnFlight !== 'anytime' && returnFlight.length > 7 && isPastDate(returnFlight)) {
      $('#regions_div').html('<p>Return date cannot be a past date.</p>');
      return;
    }

    returnFlight = (isRoundtrip) ? returnFlight : '';

    fetchAirportData(region, originPlace, dateFlight, returnFlight, currency);
  });

  function isPastDate(dateString) {
    var currentDate = new Date();
    var inputDate = new Date(dateString);
    return inputDate < currentDate;
  }

  $(document).on("click", ".choose-departure-time", function (e) {
    // Retrieve the departure date and return date from the button's data attributes
    var isRoundtrip = ($('#destModal .roundtrip-toggle').hasClass('active')) ? true : false;
    const departureDate = $(this).data("departure-date");
    const returnDate = (isRoundtrip) ? $(this).data("return-date") : '';
    const origin = $(this).data("origin");
    const originIata = origin.split(' - ');
    const destIata = $(this).data("dest-iata");
    $('#destModal').plainModal('close');

    $('.content-tab-link:nth-child(2)').click();
    if (isRoundtrip) {
      $(".hero-tab-link:nth-child(2)").click();
    }
    else {
      $(".hero-tab-link:nth-child(1)").click();
      $('#destModal .roundtrip-toggle').click();
    }

    $(".destination").val(destIata);
    $(".ddate").val(departureDate);
    if (isRoundtrip) { $(".rdate").val(returnDate); }
    $(".passengers").val(passengers);

    skysurf.setAdults(passengers);
    skysurf.getPricing(origin, destIata, '', originIata[originIata.length - 1], destIata, departureDate, returnDate, true, true, true);

    e.preventDefault();
  });

  var mobile = typeof window.orientation !== 'undefined';
  function initializeDatepicker() {
    $("#departure-date, #return-date").removeClass('calendarclass');
    $("#departure-date, #return-date").removeClass('hasDatepicker');
    $("#departure-date, #return-date").unbind();
    $("#departure-date").datepicker({
      dateFormat: "yy-mm-dd",
      minDate: 0,
      maxDate: "+1Y",
      showOtherMonths: true,
      selectOtherMonths: true,
      changeMonth: true,
      changeYear: true,
      beforeShow: function (textbox, instance) {
        if (mobile) { $('.nav-bar').hide(); }
        $(textbox).parent().css('z-index', 9999);
        instance.dpDiv.css('z-index', 10000);
        $(instance.dpDiv).addClass("my-datepicker");

        $('#destModal .show-for-anytime').show();
      },
      onSelect: function (selectedDate) {
        // Update the minimum date for #return-date
        $("#return-date").datepicker("option", "minDate", selectedDate);
      },
      onClose: function () {
        if (mobile) { $('.nav-bar').show(); }
        $(".my-datepicker").removeClass("my-datepicker");
      }
    });

    $("#return-date").datepicker({
      dateFormat: "yy-mm-dd",
      minDate: 0,
      maxDate: "+1Y",
      showOtherMonths: true,
      selectOtherMonths: true,
      changeMonth: true,
      changeYear: true,
      beforeShow: function (textbox, instance) {
        if (mobile) { $('.nav-bar').hide(); }
        $(textbox).parent().css('z-index', 9999);
        instance.dpDiv.css('z-index', 10000);
        $(instance.dpDiv).addClass("my-datepicker");

        $('#destModal .show-for-anytime').show();

        // Get the selected departure date
        var departureDate = $("#departure-date").datepicker("getDate");
        if (departureDate) {
          // Set the minimum date for #return-date based on departure date
          $(this).datepicker("option", "minDate", departureDate);
        }
      },
      onClose: function () {
        if (mobile) { $('.nav-bar').show(); }
        $(".my-datepicker").removeClass("my-datepicker");
      }
    });
  }

  // Helper function to generate a color based on the price
  function getColor(price) {
    const maxPrice = Math.max(...airports.map(airport => airport.price));
    const minPrice = Math.min(...airports.map(airport => airport.price));
    const percent = (price - minPrice) / (maxPrice - minPrice);
    const hue = 210; // Blue hue
    const lightness = 90 - (percent * 60);
    return `hsl(${hue}, 100%, ${lightness}%)`;
  }

  function formatDate(dateString) {
    // Split the date string into day, month, and year
    const [month, day, year] = dateString.split('/');

    // Create a Date object using the year, month (subtract 1 as months are zero-based), and day
    const date = new Date(year, month - 1, day);

    // Format the date using the toLocaleDateString method
    const formattedDate = date.toLocaleDateString('en-US', {
      month: 'long',
      day: 'numeric',
      year: 'numeric'
    });

    return formattedDate;
  }

  function formatDate2(dateString) {
    // Split the date string into day, month, and year components
    const parts = dateString.split('/');

    // Extract day, month, and year from the parts array
    const day = parts[1].padStart(2, '0');
    const month = parts[0].padStart(2, '0');
    const year = parts[2];

    // Assemble the formatted date string
    const formattedDate = `${year}-${month}-${day}`;

    return formattedDate;
  }

  function formatTimestamp(timestamp) {
    const date = new Date(timestamp * 1000);

    // Format the date
    const formattedDate = date.toLocaleDateString('en-US', {
      month: 'long',
      day: 'numeric',
      year: 'numeric'
    });

    // Format the time
    const formattedTime = date.toLocaleTimeString('en-US', {
      hour: 'numeric',
      minute: 'numeric',
      hour12: true,
      timeZoneName: 'short'
    });

    // Get the timezone abbreviation (e.g., EST)
    const timeZoneAbbr = date.toLocaleTimeString('en-US', { timeZoneName: 'short' }).split(' ')[2];

    // Combine the formatted date, time, and timezone abbreviation
    const formattedDateTime = `${formattedDate} ${formattedTime}`;

    return formattedDateTime;
  }

  $('#destModal .go-back-link').unbind('click').click(function (e) {
    $("#destModal #form").show();
    $("#destModal #geomap").hide();
    $('#choose-region2').prop('selectedIndex', 0);
    e.preventDefault();
  });

  $('#destModal').plainModal({
    offset: function (center) {
      // sizing by view port, step by 100px
      var jqHtml = $('html'),
        width = jqHtml.prop('clientWidth'),
        height = jqHtml.prop('clientHeight');
      width = width * 0.8;
      height = height * 0.8;
  
      // Add top and bottom margin for mobile
      if (width < 600) {
        var top = 20; // Adjust the top position value as needed
        height -= top * 2;
        this.css('top', top + 'px');
      }
  
      width = Math.round(width / 100) * 100;
      height = Math.round(height / 100) * 100;
      if (width < 100) { width = 100; }
      if (height < 100) { height = 100; }
      this.width(width).height(height);
      center(); // position to center.
    }
  });

  // Destroy the plainModal instance when it is no longer needed
  $('#destModal').on('plainmodal.close', function () {
    modalInstance.plainModal('destroy');
  });
})(jQuery);
