// $( document ).ready(function() {
// });

// 載入共用 template
$('#navbar').load('../../template/navbar.html');
$('#footer').load('../../template/footer.html');

$('#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) {
  console.log('更新篩選狀態', button, radio);

  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);
    }
  }

  designerSearch(); // 搜尋

  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 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();
}

let page = 1; // 當前頁數
let pageSize = 18; // 每頁數量
let isFirstLoad = true; // 初始載入

// 列表篩選
async function designerSearch(type = "") {
  if (isFirstLoad) {
    // 第一次載入使用本地 JSON 文件
    url = './json/designers_lists_data.json';
  } else {
    // 後續使用 API (預設排序為 recommend)
    url = `https://m3.hhh.com.tw:18673/designer_search?page=${page}&page_size=${pageSize}&order_by=recommend`;

    if (type === "order_by") {
      url += `&${type}=${assignOrder}`;
    }

    let input = $(".keywords").val();

    if (input !== "") {
      url += `&keyword=${input}`;
    }

    if (filterList.length) {
      filterList.map(item => {
        if (item.id === 'budget') {
          switch (item.value) {
            case "100萬以下":
              url += `&${item.id}=1`;
              break;
            case "100~200萬":
              url += `&${item.id}=2`;
              break;
            case "200~300萬":
              url += `&${item.id}=3`;
              break;
            case "300~400萬":
              url += `&${item.id}=4`;
              break;
            case "400~500萬":
              url += `&${item.id}=5`;
              break;
            case "500萬以上":
              url += `&${item.id}=6`;
              break;
            default:
              break;
          }
        } else {
          url += `&${item.id}=${item.value}`;
        }
      });
    }
  }

  // // 預設排序為 recommend
  // let url = `https://m3.hhh.com.tw:18673/designer_search?page=${page}&page_size=${pageSize}&order_by=recommend`;

  // console.log('type', type);

  // if (type === "order_by") {
  //   url += `&${type}=${assignOrder}`
  // }

  // let input = $(".keywords").val();
  // console.log('input', input);

  // if (input !== "") {
  //   url += `&keyword=${input}`
  // }

  // if (filterList.length) {
  //   filterList.map(item => {
  //     if (item.id === 'budget') {
  //       switch (item.value) {
  //         case "100萬以下":
  //           url += `&${item.id}=1`
  //           break;
  //         case "100~200萬":
  //           url += `&${item.id}=2`
  //           break;
  //         case "200~300萬":
  //           url += `&${item.id}=3`
  //           break;
  //         case "300~400萬":
  //           url += `&${item.id}=4`
  //           break;
  //         case "400~500萬":
  //           url += `&${item.id}=5`
  //           break;
  //         case "500萬以上":
  //           url += `&${item.id}=6`
  //           break;
  //         default:
  //           break;
  //       }

  //     } else {
  //       url += `&${item.id}=${item.value}`
  //     }
  //   })
  // }

  try {
    const response = await axios.get(url);
    console.log('response.data.designers', response.data.designers);

    let totalCount = response.data.total_count;
    let totalPages = Math.ceil(totalCount / pageSize);

    $("#totalCount").html(totalCount);

    if (totalPages) {
      $('.filter-list .pagination').show();
      setPagination(totalPages); // 分頁處理
    } else {
      $('.filter-list .pagination').hide();
    }

    let resultHtml = '';

    if (response.data.designers.length) {
      response.data.designers.forEach((item) => {
        resultHtml += `
        <div class="col-md-4 mb-4">
          <a href="${item.DesignerLink}">
            <div class="card designer-card">
              <img src="${item.CaseCoverImg}" class="cover-img" alt="${item.DesignerName} ${item.DesignerTitle}">
                <div class="card-body d-flex align-items-center">
                  <div class="person-img me-3 me-md-2 me-lg-3" style="background-image: url('${item.DesignerCoverImg}');"></div>
                  <section>
                    <h5 class="card-text text-muted mb-2">${item.DesignerTitle}</h5>
                    <h6 class="card-title mb-0 text-dark">
                      <span class="font-weight-bold">
                        ${item.DesignerName}
                      </span>
                      設計師
                    </h6>
                  </section>
                </div>
            </div>
          </a>
        </div>`;
      });
    } else {
      resultHtml += "<p class='text-center mt-5'>找不到符合的資料，請重新搜尋。</p>"
    }

    $('#designerList').html(resultHtml);

    // 更新初始載入狀態
    if (isFirstLoad) {
      isFirstLoad = false;
    }
  } catch (error) {
    console.log("error", error);
  }
}

designerSearch();

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);
    designerSearch();
  }

  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');
  }

  designerSearch(); // 搜尋
}

let assignOrder = ""; // 當前排序

// new, hot, recommend 排序 (預設推薦)
$(".search-btn-filter button").click(function () {
  // 切換選取狀態
  $('.search-btn-filter').find('.active').removeClass('active');
  $(this).addClass('active');
  assignOrder = $(this).attr('id');
  designerSearch("order_by");
});


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