$('#removeResultBtn').hide(); // 隱藏全部清除按鈕

// 處理 radio 選取狀態
$('.filter-list .form-check').click(function (e) {
  e.preventDefault();
  $(this).find('.form-check-input').prop('checked', true);

  // 取得 radio 按鈕的 label
  let radioLabel = $(this).find('.form-check-label').text().trim().replace(/\s+/g, ' '); // 移除換行空白

  // 取上一層 search-tab 按鈕文字
  let buttonValue = $(this).closest('.dropdown').find('.search-tab').text().trim();
  let buttonId = $(this).closest('.dropdown').find('.search-tab').attr('id');

  updateSelectedOptions(buttonId, buttonValue, radioLabel);
});

let filterList = []; // 篩選條件

// 更新篩選狀態
function updateSelectedOptions(id, button, radio) {
  page = 1;
  console.log('更新篩選狀態', button, radio);
  push_GA(button, radio); // 發送 GA

  if (filterList.length) {
    let exists = false; // 判斷是否已存在

    for (let index = 0; index < filterList.length; index++) {
      const element = filterList[index];

      // 如有重複 button 只改 radio 狀態
      if (element.text === button) {
        element.value = radio;
        exists = true;
        // 更新篩選的值
        $(`.search-tab-result .budget:contains(${button})`).find('p').text(`${button}：${radio}`);
      }
    }

    // 如果 filterList 中不存在則新增
    if (!exists) {
      const newItem = {
        id: id,
        text: button,
        value: radio
      };

      filterList.push(newItem);
      createFilterHtml(newItem);
    }


  } else {
    // 儲存篩選條件
    filterList.push({
      id: id,
      text: button,
      value: radio
    })

    for (let index = 0; index < filterList.length; index++) {
      const element = filterList[index];
      createFilterHtml(element);
    }
  }

  page = 1;
  dataSearch(); // 搜尋

  console.log('filterList', filterList);

  // 切換按鈕選取狀態
  $('.dropdown').each(function () {
    let hasCheckedRadio = $(this).find('input[type="radio"]:checked').length > 0;
    $(this).find('.search-tab').toggleClass('active', hasCheckedRadio);
  });
}

// 新增篩選條件 HTML
function createFilterHtml(item) {
  let dom = `
      <span class="me-3">
        <span class="d-flex budget">
          <p class="me-1">${item.text}：${item.value}</p>
          <img onclick="removeBtn(this, '${item.id}', '${item.text}')" src="https://hhh.com.tw/assets/images/section/icon/close-btn-search.svg" alt="close-btn-search">
        </span>
      </span>`;

  $('.search-tab-result').append(dom);
  $('#removeResultBtn').show();
}

// 清除單一篩選條件
function removeBtn(element, id, val) {
  filterList = filterList.filter(item => item.text !== val);

  ; // 移除 div & active
  $(element).closest('.me-3').remove();
  $(`#${id}`).removeClass('active');
  // 移除同一層級 ul 內所有 radio 的選取狀態
  $(`#${id}`).siblings('.dropdown-menu').find('input[type="radio"]').prop('checked', false);

  if (filterList.length === 0) {
    $('#removeResultBtn').hide();
  }

  dataSearch();
}

// 鍵盤 Enter 輸入
$('.keywords').on('keydown', function (event) {
  if (event.key === 'Enter') {
    page = 1;
    dataSearch("keyword");
  }
});

// 點擊 tag 進行搜尋
$(document).on('click', '.tag-item', function (event) {
  event.preventDefault(); // 阻止默認行為
  event.stopPropagation(); // 阻止冒泡
  const tag = $(this).data('tag');
  $(".keywords").val(tag);
  dataSearch();
});

let maxPagesMobile = 5; // 手機板最多顯示 5 頁
let maxPagesDesktop = 10; // 電腦版最多顯示 10 頁

// 分頁
function setPagination(pages) {
  let screenWidth = $(window).width();
  let maxPages = screenWidth > 991 ? maxPagesDesktop : maxPagesMobile;

  function renderPagination(currentPage) {
    let dom = `
      <li class="page-item" onclick="handlePagination(this, 'previous')">
        <a class="page-link previous hidden" href="#" aria-label="Previous">
          <span aria-hidden="true">＜</span>
        </a>
      </li>`;

    let startPage = Math.max(currentPage - Math.floor(maxPages / 2), 1);
    let endPage = Math.min(startPage + maxPages - 1, pages);

    if (endPage - startPage < maxPages) {
      startPage = Math.max(endPage - maxPages + 1, 1);
    }

    for (let index = startPage; index <= endPage; index++) {
      dom += `
        <li class="page-item ${index === currentPage ? 'active' : ''}" onclick="handlePagination(this)">
          <a class="page-link" href="#">${index}</a>
        </li>`;
    }

    dom += `
      <li class="page-item" onclick="handlePagination(this, 'next')">
        <a class="page-link next" href="#" aria-label="Next">
          <span aria-hidden="true">＞</span>
        </a>
      </li>`;

    $('.filter-list .pagination').html(dom);
    updateVisibility(currentPage, pages);
  }

  // 更新上頁 & 下頁的按鈕顯示狀態
  function updateVisibility(page, pages) {
    if (page === 1) {
      $('.page-link.previous').addClass('hidden');
    } else {
      $('.page-link.previous').removeClass('hidden');
    }

    if (page === pages) {
      $('.page-link.next').addClass('hidden');
    } else {
      $('.page-link.next').removeClass('hidden');
    }
  }

  window.handlePagination = function (item, type = "") {
    if (type === "previous" && page > 1) {
      page--;
    } else if (type === "next" && page < pages) {
      page++;
    } else if (!type) {
      page = parseInt($(item).find('.page-link').text());
    }
    renderPagination(page);
    dataSearch();
  }

  renderPagination(page);

  $(window).on('resize', function () {
    let newScreenWidth = $(window).width();
    if ((newScreenWidth > 991 && maxPages !== maxPagesDesktop) ||
      (newScreenWidth <= 991 && maxPages !== maxPagesMobile)) {
      maxPages = newScreenWidth > 991 ? maxPagesDesktop : maxPagesMobile;
      renderPagination(page);
    }
  });
}

// 頁碼處理
function handlePagination(item, type = "") {
  if (type === "previous") {
    // 往前一頁
    if (page > 1) {
      page--;
    }
    console.log(page);
  } else if (type === "next") {
    // 往後一頁
    page++;
    console.log(page);
  } else {
    // 直接點擊頁碼
    page = parseInt($(item).find('.page-link')[0].innerText);
  }

  // 切換選取狀態
  $('.filter-list .page-item').removeClass('active');
  $('.filter-list .page-item').eq(page).addClass('active');

  // 設定上一頁按鈕的顯示狀態
  if (page === 1) {
    $('.page-link.previous').addClass('hidden');
  } else {
    $('.page-link.previous').removeClass('hidden');
  }

  dataSearch(); // 搜尋
}

// 熱搜關鍵字搜尋
$(".search-bar-keyword a").click(function () {
  let keyword = $(this).text();
  $('.keywords').val(keyword);
  page = 1;
  dataSearch();
});

// 全部清除
$("#removeResultBtn").click(function () {
  console.log('全部清除');
  filterList.length = 0; // 清空篩選陣列
  $('.keywords').val(''); // 清空搜尋欄位
  $('#removeResultBtn').hide(); // 隱藏全部清除按鈕
  $('.search-tab-result').empty(); // 清空篩選條件 dom
  // 取消選取狀態
  $('.filter-list input[type="radio"]').prop('checked', false);
  $('.search-tab').removeClass('active');
  dataSearch();
});

// 輸入框自動補全
let designerKeywordList = [];

async function getKeyword() {
  console.log('getKeyword');
  let url = '../../json/designer_keyword.json';

  try {
    const response = await axios.get(url);
    designerKeywordList = response.data.designer_keyword_list;
  } catch (error) {
    console.log("error", error);
  }
}

getKeyword();

$('#keywordInput').on('input', function () {
  let input = $(this).val();
  closeAllLists();
  if (!input) {
    return false;
  }

  let divList = $('#autocomplete-list');
  for (let i = 0; i < designerKeywordList.length; i++) {
    if (designerKeywordList[i].substr(0, input.length).toUpperCase() === input.toUpperCase()) {
      let item = $('<div></div>');
      item.html("<strong>" + designerKeywordList[i].substr(0, input.length) + "</strong>" + designerKeywordList[i].substr(input.length));
      item.on('click', function () {
        $('#keywordInput').val($(this).text());
        closeAllLists();
      });
      item.on('mouseenter', function () {
        $('#keywordInput').val($(this).text());
      });
      divList.append(item);
    }
  }
});

// 清空自動補全列表
function closeAllLists() {
  $('.autocomplete-items').empty();
}

$(document).on('click', function (e) {
  closeAllLists();
});

// 發送 GA
function push_GA(text, value) {
  if (text === "接案預算") {
    push_GA_tbudge_select(value);
  } else if (text === "接案風格" || text === "設計風格") {
    push_GA_style_select(value);
  } else if (text === "接案類型" || text === "房屋類型") {
    push_GA_dtype_select(value);
  } else if (text === "所在縣市") {
    push_GA_city_select(value);
  } else if (text === "房屋坪數") {
    push_GA_area_select(value);
  } else if (text === "房屋狀況") {
    push_GA_condition_select(value);
  }
}



// 房屋狀況 GA
function push_GA_condition_select(key) {
  console.log('push_GA_condition_select', key);
  let eventLabel = '';

  switch (key) {
    case '新成屋':
      eventLabel = 'new_house';
      break;
    case '毛胚屋':
      eventLabel = 'bare_shell';
      break;
    case '老屋翻新':
      eventLabel = 'renovation_condition';
      break;
    case '自地自建':
      eventLabel = 'self-build';
      break;
    case '中古屋':
      eventLabel = 'second_hand';
      break;
    default:
      eventLabel = 'unknown';
  }
  dataLayer.push({ 'event': eventLabel });
  // 發送 Facebook Pixel 事件
  fbq('trackCustom', eventLabel);
}

// 房屋坪數 GA
function push_GA_area_select(key) {
  console.log('push_GA_area_select', key);
  let eventLabel = '';

  switch (key) {
    case '20坪以下':
      eventLabel = '20_below';
      break;
    case '21~30坪':
      eventLabel = '21_30';
      break;
    case '31~50坪':
      eventLabel = '31_50';
      break;
    case '51坪以上':
      eventLabel = '50_up';
      break;
    default:
      eventLabel = 'unknown';
  }
  dataLayer.push({ 'event': eventLabel });
  // 發送 Facebook Pixel 事件
  fbq('trackCustom', eventLabel);
}

// 接案預算 GA
function push_GA_tbudge_select(key) {
  console.log('push_GA_tbudge_select', key);
  let eventLabel = '';

  switch (key) {
    case '100萬以下':
      eventLabel = '1M_below';
      break;
    case '100~200萬':
      eventLabel = '1M_2M';
      break;
    case '200~300萬':
      eventLabel = '2M_3M';
      break;
    case '300~400萬':
    case '400~500萬':
    case '500萬以上':
      eventLabel = '3M_up';
      break;
    default:
      eventLabel = 'unknown';
  }
  dataLayer.push({ 'event': eventLabel });
  // 發送 Facebook Pixel 事件
  fbq('trackCustom', eventLabel);
}

// 設計風格/接案風格 GA
function push_GA_style_select(key) {
  console.log('push_GA_style_select', key);
  let eventLabel = '';

  switch (key) {
    case '北歐風':
      eventLabel = 'Scandi_style';
      break;
    case '現代風':
      eventLabel = 'Modern_style';
      break;
    case '工業風':
      eventLabel = 'Industrial_style';
      break;
    case '美式風':
      eventLabel = 'American_style';
      break;
    case '休閒多元':
      eventLabel = 'Leisure_style';
      break;
    case '前衛風':
      eventLabel = 'Avant_garde_style';
      break;
    case '鄉村風':
      eventLabel = 'Rustic_style';
      break;
    case '混搭風':
      eventLabel = 'Eclectic_style';
      break;
    case '新古典':
      eventLabel = 'Neoclassic_style';
      break;
    case '奢華風':
      eventLabel = 'Luxurious_style';
      break;
    case '古典風':
      eventLabel = 'Classical_style';
      break;
    case '異國風':
      eventLabel = 'Exotic_style';
      break;
    case '日式蟬風':
      eventLabel = 'Zen_style';
      break;
    case '東方風':
      eventLabel = 'Oriental_style';
      break;
    case '無印風':
      eventLabel = 'Muju_style';
      break;
    case '簡約風':
      eventLabel = 'Minimalism_style';
      break;
    case '日式風':
      eventLabel = 'JP_style';
      break;
    case '輕奢風':
      eventLabel = 'Affordable_Luxury_style';
      break;
    default:
      eventLabel = 'unknown';
  }
  dataLayer.push({ 'event': eventLabel });
  // 發送 Facebook Pixel 事件
  fbq('trackCustom', eventLabel);

}

// 接案類型/房屋類型 GA
function push_GA_dtype_select(key) {
  console.log('push_GA_dtype_select', key);
  let eventLabel = '';

  switch (key) {
    case '小坪數':
      eventLabel = 'small';
      break;
    case '標準格局':
      eventLabel = 'standard';
      break;
    case '大坪數':
      eventLabel = 'big';
      break;
    case '別墅':
      eventLabel = 'villa';
      break;
    case '挑高樓層':
      eventLabel = 'raisehigh';
      break;
    case '樓中樓':
      eventLabel = 'duplex_house';
      break;
    case '實品/樣品屋':
      eventLabel = 'sample';
      break;
    case '工作空間':
    case '商業空間':
    case '公共空間':
      eventLabel = 'commercial';
      break;
    case '民宿旅館':
      eventLabel = 'B&B';
      break;
    case '餐飲空間':
      eventLabel = 'dining';
      break;
    case '老屋翻新':
      eventLabel = 'renovation_condition';
      break;
    default:
      eventLabel = 'unknown';
  }
  dataLayer.push({ 'event': eventLabel });
  // 發送 Facebook Pixel 事件
  fbq('trackCustom', eventLabel);

}

// 所在縣市 GA 
function push_GA_city_select(key) {
  console.log('push_GA_city_select', key);
  let eventLabel = '';

  switch (key) {
    case '台北市':
      eventLabel = 'Taipei';
      break;
    case '新北市':
      eventLabel = 'New Taipei';
      break;
    case '基隆市':
      eventLabel = 'Keelung';
      break;
    case '桃園市':
      eventLabel = 'Taoyuan';
      break;
    case '新竹縣':
      eventLabel = 'Hsinchu';
      break;
    case '新竹市':
      eventLabel = 'Hsinchu';
      break;
    case '苗栗縣':
      eventLabel = 'Miaoli';
      break;
    case '台中市':
      eventLabel = 'Taichung';
      break;
    case '南投縣':
      eventLabel = 'Nantou';
      break;
    case '彰化縣':
      eventLabel = 'Changhua';
      break;
    case '雲林縣':
      eventLabel = 'Yunlin';
      break;
    case '嘉義縣':
      eventLabel = 'Chiayi';
      break;
    case '嘉義市':
      eventLabel = 'Chiayi';
      break;
    case '台南市':
      eventLabel = 'Tainan';
      break;
    case '高雄市':
      eventLabel = 'Kaohsiung';
      break;
    case '屏東縣':
      eventLabel = 'Pingtung';
      break;
    case '宜蘭縣':
      eventLabel = 'Yilan';
      break;
    case '花蓮縣':
      eventLabel = 'Hualien';
      break;
    case '台東縣':
      eventLabel = 'Taitung';
      break;
    case '澎湖縣':
      eventLabel = 'Penghu';
      break;
    case '金門縣':
      eventLabel = 'Kinmen';
      break;
    case '連江縣':
      eventLabel = 'Lienchiang';
      break;
    default:
      eventLabel = 'unknown';
  }
  dataLayer.push({ 'event': eventLabel });
  // 發送 Facebook Pixel 事件
  fbq('trackCustom', eventLabel);

}