$(document).ready(function () {
  $(window).scroll(stick_menu);

  $("select").select2({
    minimumResultsForSearch: -1
  });

  $(".home8__link").on("click", function () {
    var nr = $("#home8_block_number").val();

    nr++;

    if (nr >= 4) {
      nr = 1;
    }

    $(".home8__block").hide();
    $("#home8_block_" + nr).fadeIn();

    $("#home8_block_number").val(nr);
  });

  $("#budynek-svg svg g").mouseover(function () {
    var id = $(this).attr("id");

    if (level_status[id]) {
      var level = level_status[id]['level'];
      if (level != "Parter") {
        level = "Piętro " + level;
      }

      var building = id.slice(0, 1);

      $("#speech_bubble_levvel").html(level);
      $("#speech_bubble_free").html(level_status[id]['free']);
      $("#speech_bubble_reserved").html(level_status[id]['reserved']);
      $("#speech_bubble_sold").html(level_status[id]['sold']);
      $("#speech_bubble_building").html(building);

      $(".speech_bubble__svg div").hide();
      $("#speech_bubble__svg-" + building).show();

      $(".speech_bubble").css('display', 'flex');
    }
  });

  $("#budynek-svg svg g").mouseout(function () {
    $(".speech_bubble").css('display', 'none');
  });

  $("#search_button").click(function () {
    var building = $("#search_building").val();
    var level = $("#search_level").val();
    var room = $("#search_room").val();
    var status = $("#search_status").val();
    var from = $("#fromInput").val();
    var to = $("#toInput").val();

    searchApartments(building, level, room, status, from, to);
  });

  $(".send-message").click(function () {
    var id = $(this).data("id");
    var svg_id = $(this).data("pietro");

    sendMessage(id, svg_id);
  });

  $(".modal .close").click(function () {
    $(".modal").hide();
    $(".form_contact_overlay").hide();
  });
});


function calculateMonthlyPayment(propertyPrice, downPaymentRate, loanTermYears) {
  // propertyPrice - Cena nieruchomości (np. 100000 zł)
  // downPaymentRate - Wkład własny w formie ułamka dziesiętnego (np. 0.10 dla 10%)
  // loanTermYears - Okres spłaty kredytu w latach (np. 5, 10, 15, 35)

  var loanAmount = propertyPrice * (1 - downPaymentRate); // Kwota kredytu po odjęciu wkładu własnego
  var monthlyInterestRate = 0.005755; // Średnia miesięczna stopa procentowa (ok. 6.91% rocznie)
  var loanTermMonths = loanTermYears * 12; // Liczba miesięcy spłaty kredytu

  // Wzór na miesięczną ratę kredytu (równe raty kapitałowo-odsetkowe)
  var monthlyPayment = (loanAmount * monthlyInterestRate) /
    (1 - Math.pow(1 + monthlyInterestRate, -loanTermMonths));

  var price2 = propertyPrice * downPaymentRate;

  $("#price2").val(price2.toFixed(1));

  return monthlyPayment.toFixed(0); // Zaokrąglamy wynik do dwóch miejsc po przecinku
}

function hamburgerChange(x) {
  x.classList.toggle("change");
  $(".responsive-menu").toggle();
}

function stick_menu() {
  if ($(window).scrollTop() > 1) {
    $("header").addClass("stick");
    $(".main-content").addClass("main-stick");
  } else if ($(window).scrollTop() < 1) {
    $("header").removeClass("stick");
    $(".main-content").removeClass("main-stick");
  }
}

function wczytaj_pietro(id) {

  var obj = map_svgs['pietra'][id];

  var url = obj['bg'];
  var svg = obj['svg'];
  var svg_id = obj['pietro_id'];


  var level_name = map_svgs['pietra'][svg_id]['pietro_nazwa'];

  if (level_name != "Parter") {
    level_name = 'Piętro <strong>' + level_name + '</strong>';
  }

  $("#levelegend_building").html(svg_id.charAt(0).toUpperCase());
  $("#levelegend_level").html(level_name);
  $("#levelegend_free").html(level_status[svg_id]['free']);
  $("#levelegend_reserved").html(level_status[svg_id]['reserved']);
  $("#levelegend_sold").html(level_status[svg_id]['sold']);

  $("#level-legend").css('display', 'block');

  $('#level-svg').css('background-image', 'url(' + url + ')');
  $('#level-svg-area').html(svg);
  $('#level-svg').show();

  calcTable(svg_id);

  $([document.documentElement, document.body]).animate({
    scrollTop: $(".level-search-row").offset().top - (9.74 * window.screen.width / 100)
  }, 500);

  $("#level-svg").addClass("karta_mieszkania");

  $(".karta_mieszkania svg path").click(function () {
    var id = $(this).parent().attr("id");
    loadCard(id, svg_id);
  });
}

function sendMessage(mieszkanie, pietro) {

  var nr = mieszkanie.substring(1);
  var budynek = mieszkanie.slice(0, 1);

  var pietro_name = pietro;

  var txt = "Budynek: " + budynek.toUpperCase() + ", Mieszkanie: " + nr + ", Pietro: " + pietro_name;

  $('.modal input[name="your-subject"]').val(txt);

  $(".modal").show();
  $(".form_contact_overlay").show();
}

function loadCard(id, svg_id) {
  var url = map_svgs[svg_id][id]['link'];
  window.open(url, '_blank');
}

function convertMap() {

  var arrayMap = [];
  var arrayStatus = [];

  $.each(map_svgs, function (key, obj) {

    if (key != "pietra") {
      arrayMap[key] = [];
      $.each(obj, function (key2, value) {
        arrayMap[key][key2] = value['status'];

        if (value['status'] == "zarezerwowane") {

          if (!arrayStatus['zarezerwowane']) {
            arrayStatus['zarezerwowane'] = 0
          }

          arrayStatus['zarezerwowane']++;
        }

        if (value['status'] == "sprzedane") {

          if (!arrayStatus['sprzedane']) {
            arrayStatus['sprzedane'] = 0
          }

          arrayStatus['sprzedane']++;
        }

        if (value['status'] == "wolne") {

          if (!arrayStatus['wolne']) {
            arrayStatus['wolne'] = 0
          }

          arrayStatus['wolne']++;
        }
      });
    }
  });

  $.each(map_svgs['pietra'], function (key, obj) {

    var svg = obj['svg'];

    for (let k in arrayMap[obj['pietro_id']]) {
      var status = arrayMap[obj['pietro_id']][k];

      svg = svg.replace('id="' + k + '"', 'id="' + k + '" class="' + status + '"');
    }

    map_svgs['pietra'][key]['svg'] = svg;
  });


  if (!arrayStatus['zarezerwowane']) {
    arrayStatus['zarezerwowane'] = 0;
  }

  if (!arrayStatus['sprzedane']) {
    arrayStatus['sprzedane'] = 0;
  }

  if (!arrayStatus['wolne']) {
    arrayStatus['wolne'] = 0;
  }

  $("#apartments-free").html(parseInt(arrayStatus['wolne']));
  $("#apartments-reserved").html(parseInt(arrayStatus['zarezerwowane']));
  $("#apartments-sold").html(parseInt(arrayStatus['sprzedane']));

  var apartments_all = parseInt(arrayStatus['wolne']) + parseInt(arrayStatus['zarezerwowane']) + parseInt(arrayStatus['sprzedane']);

  $("#apartments-all").html(apartments_all);
}

function clickSvg() {
  $("#budynek-svg svg g").click(function () {
    var id = $(this).attr("id");
    wczytaj_pietro(id);
  });

  $("#budynek-svg svg g").click(function () {
    var id = $(this).attr("id");
    wczytaj_pietro(id);
  });
}

function calcTable(svg_id, nr, free) {
  var tableRow = '';

  if (svg_id) {
    var building = map_svgs[svg_id];

    $.each(building, function (key, value) {
      if (!nr || nr == value['liczba_pokoi']) {

        var nr_bud = key.replace("c", "");
        nr_bud = nr_bud.replace("d", "");
        nr_bud = nr_bud.replace("e", "");

        tableRow = tableRow + '<tr>' +
          '<td>' + key.charAt(0).toUpperCase() + '</td>' +
          '<td>' + map_svgs['pietra'][svg_id]['pietro_nazwa'] + '</td>' +
          '<td>' + nr_bud + '</td>' +
          '<td>' + value['metraz'].replace(",", ".") +
          '<td>' + value['liczba_pokoi'] + '</td>' +
          '<td>' + value['balkon'].replace(",", ".") +
          '<td class="' + value['status'] + '">' + value['status'] + '</td>' +
          '<td class="strong"><span class="offer-show-projection" data-id="' + key + '" data-pietro="' + map_svgs['pietra'][svg_id]['pietro_id'] + '"><i class="fa-solid fa-clipboard-list"></i></span></td>' +
          '<td class="strong"><span class="send-message" data-id="' + key + '" data-pietro="' + map_svgs['pietra'][svg_id]['pietro_nazwa'] + '"><span class="button">zapytaj</span></span></td>' +
          '</tr>';
      }
    });
  } else {
    $.each(map_svgs, function (key, obj) {
      $.each(obj, function (key2, value) {
        if (key != "pietra") {
          if (!nr || nr == value['liczba_pokoi']) {

            var nr_bud = key2.replace("c", "");
            nr_bud = nr_bud.replace("d", "");
            nr_bud = nr_bud.replace("e", "");

            tableRow = tableRow + '<tr>' +
              '<td>' + key2.charAt(0).toUpperCase() + '</td>' +
              '<td>' + map_svgs['pietra'][key]['pietro_nazwa'] + '</td>' +
              '<td>' + nr_bud + '</td>' +
              '<td>' + value['metraz'].replace(",", ".") +
              '<td>' + value['liczba_pokoi'] + '</td>' +
              '<td>' + value['balkon'].replace(",", ".") +
              '<td class="' + value['status'] + '">' + value['status'] + '</td>' +
              '<td class="strong"><span class="offer-show-projection" data-id="' + key2 + '" data-pietro="' + map_svgs['pietra'][key]['pietro_id'] + '"><i class="fa-solid fa-clipboard-list"></i></span></td>' +
              '<td class="strong"><span class="send-message" data-id="' + key2 + '" data-pietro="' + map_svgs['pietra'][key]['pietro_nazwa'] + '"><span class="button">zapytaj</span></span></td>' +
              '</tr>';
          }
        }
      });
    });
  }

  var table = '<table class="table-sort">\n' +
    '            \n' +
    '                <tr>\n' +
    '                    <th class="sort">Budynek</th>\n' +
    '                    <th class="sort">Piętro</th>\n' +
    '                    <th class="sort">Mieszkanie</th>\n' +
    '                    <th class="sort">Metraż [m<sup>2</sup>]</th>\n' +
    '                    <th class="sort">Pokoje</th>\n' +
    '                    <th>Balkon /<br>Taras /<br>Loggia [m<sup>2</sup>]</th>\n' +
    '                    <th class="sort">Status</th>\n' +
    '                    <th>Karta</th>\n' +
    '                    <th>Cena</th>\n' +
    '                </tr>\n' +
    '             \n' +
    '               \n' + tableRow + '\n' +
    '            </table>';

  $(".apartment-table").html(table);

  sortTable();

  $(".offer-show-projection").click(function () {
    var id = $(this).data("id");
    var svg_id = $(this).data("pietro");

    loadCard(id, svg_id);
  });

  $(".send-message").click(function () {
    var id = $(this).data("id");
    var svg_id = $(this).data("pietro");

    sendMessage(id, svg_id);
  });
}

function sortTable() {
  const getCellValue = (tr, idx) => tr.children[idx].innerText || tr.children[idx].textContent;

  const comparer = (idx, asc) => (a, b) => ((v1, v2) =>
    v1 !== '' && v2 !== '' && !isNaN(v1) && !isNaN(v2) ? v1 - v2 : v1.toString().localeCompare(v2)
  )(getCellValue(asc ? a : b, idx), getCellValue(asc ? b : a, idx));

  // do the work...
  document.querySelectorAll('th.sort').forEach(th => th.addEventListener('click', (() => {
    const table = th.closest('table');
    Array.from(table.querySelectorAll('tr:nth-child(n+2)'))
      .sort(comparer(Array.from(th.parentNode.children).indexOf(th), this.asc = !this.asc))
      .forEach(tr => table.appendChild(tr));
  })));
}

function printPDF() {
  var pdfFrame = document.getElementById('offer_pdf');
  pdfFrame.focus();
  pdfFrame.contentWindow.print();
}

function controlFromInput(fromSlider, fromInput, toInput, controlSlider) {
  const [from, to] = getParsed(fromInput, toInput);
  fillSlider(fromInput, toInput, '#ededed', '#C1AF69', controlSlider);
  if (from > to) {
    fromSlider.value = to;
    fromInput.value = to;
  } else {
    fromSlider.value = from;
  }
}

function controlToInput(toSlider, fromInput, toInput, controlSlider) {
  const [from, to] = getParsed(fromInput, toInput);
  fillSlider(fromInput, toInput, '#ededed', '#C1AF69', controlSlider);
  setToggleAccessible(toInput);
  if (from <= to) {
    toSlider.value = to;
    toInput.value = to;
  } else {
    toInput.value = from;
  }
}

function controlFromSlider(fromSlider, toSlider, fromInput) {
  const [from, to] = getParsed(fromSlider, toSlider);
  fillSlider(fromSlider, toSlider, '#ededed', '#C1AF69', toSlider);
  if (from > to) {
    fromSlider.value = to;
    fromInput.value = to;
  } else {
    fromInput.value = from;
  }
}

function controlToSlider(fromSlider, toSlider, toInput) {
  const [from, to] = getParsed(fromSlider, toSlider);
  fillSlider(fromSlider, toSlider, '#ededed', '#C1AF69', toSlider);
  setToggleAccessible(toSlider);
  if (from <= to) {
    toSlider.value = to;
    toInput.value = to;
  } else {
    toInput.value = from;
    toSlider.value = from;
  }
}

function getParsed(currentFrom, currentTo) {
  const from = parseInt(currentFrom.value, 10);
  const to = parseInt(currentTo.value, 10);
  return [from, to];
}

function fillSlider(from, to, sliderColor, rangeColor, controlSlider) {
  const rangeDistance = to.max - to.min;
  const fromPosition = from.value - to.min;
  const toPosition = to.value - to.min;
}

function setToggleAccessible(currentTarget) {
  const toSlider = document.querySelector('#toSlider');
  if (Number(currentTarget.value) <= 0) {
    toSlider.style.zIndex = 2;
  } else {
    toSlider.style.zIndex = 0;
  }
}