(function() {

const constants = {
  NOT_FOUND: "Newspaper is empty or null. Returning 404.",
};

const API_CONFIG = {
  API_URL: "https://api.servicemacha.my/api",
  API_KEY: "job-ads-newspaper",
  APP_URL: "https://servicemacha.my",
};

const employmentType = {
  full_time: "全职",
  part_time: "兼职",
  internship: "实习",
};

const questionMarkImg = "https://servicemacha-prod.oss-ap-southeast-3.aliyuncs.com/servicemacha-jobads-default-logo.png";

const jobMachaLogo = "https://servicemacha-prod.oss-ap-southeast-3.aliyuncs.com/servicemacha_2025_logo.png";

const styleText = `
<style>
  body {
    margin: 0;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji';
  }

  .sm-jobads-position {
      padding-bottom: 16px;
  }

  .sm-jobads-company-logo-container {
      display: flex;
      justify-content: center;
      width: 64px;
      height: 64px;
      aspect-ratio: 1;
      box-sizing: border-box;
  }

  .sm-jobads-company-logo-image {
      width: 100%;
      height: 100%;
      object-fit: contain;
      border-radius: 8px;
  }

  @media screen and (max-width: 480px) {
    .sm-jobads-company-logo-container {
      width: 56px;
      height: 56px;
    }

    .sm-jobads-company-logo-image {
      border-radius: 7px;
    }
  }

  .sm-jobads-company-logo-parent-container {
      display: flex;
      width: 100%;
      justify-content: center;
      padding-bottom: 16px;
  }

  .sm-jobads-text-container {
      display: flex;
      flex-direction: column;
      gap: 8px;
  }

  .sm-jobads-position-title-container {
    font-size: 14px;
    font-weight: 600;
    color: #a20720;
  }

  @media screen and (max-width:480px) {
    .sm-jobads-position-title-container {
      font-size: 12px;
    }
  }

  .sm-jobads-position-company-container {
      font-size: 12px;
      font-weight: 400;
      color: #262626;
  }

  .sm-jobads-tags-container {
      display: flex;
      gap: 8px;
      flex-wrap: wrap;
      padding-bottom: 16px;
  }

  .sm-jobads-tags {
      font-size: 12px;
      color: #FFFFFF;
      background-color: #a20720;
      padding: 4px 8px;
      border-radius: 4px;
  }

  .sm-jobads-salary-and-location-container {
      display: flex;
      flex-direction: column;
      gap: 8px;
  }
  
  .sm-jobads-salary-container {
      font-size: 14px;
      font-weight: 600;
      color: #a20720;
  }

  .sm-jobads-location-container {
      font-size: 12px;
      font-weight: 400;
      color: #8C8C8C;
  }

  .sm-jobads-card {
      border: 1px solid #a20720;
      border-radius: 6px;
      padding: 12px;
      text-decoration: none;
      height: auto !important;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      box-sizing: border-box;
  }

  .sm-jobads-container {
    align-items: stretch;
    height: fit-content!important;
  }

  .jobmacha-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 16px;
  }

  .jobmacha-logo-container {
    width: 200px;
  }

  @media screen and (max-width:480px) {
    .jobmacha-logo-container {
      width: 100px;
    }
  }

  .jobmacha-logo-container img {
    object-fit: contain;
    width: 100%;
  }

  .jobmacha-button-container {
    display: flex;
    gap: 16px;
  }

  .jobmacha-button-link {
    text-decoration: none;
  }

  .jobmacha-button {
    font-size: 16px;
    font-weight: 600;
    padding: 12px;
    border: 1px solid #a20720;
    border-radius: 4px;
  }

  @media screen and (max-width:480px) {
    .jobmacha-button {
      font-size: 12px;
    }
  }

  .post-ads {
    color: #FFFFFF;
    background-color: #a20720;
  }

  .more-ads {
    color: #a20720;
    background-color: #FFFFFF;
  }

  .swiper-parent {
    position: relative;
    margin: 0 auto;
  }

  .swiper-pagination {
    bottom: -30px!important;
  }
  
  .swiper-button-prev, 
  .swiper-button-next {
    width: 32px;
    height: 32px;
    background-color: #a207207F;
    border-radius: 50%;
    z-index: 1000;
  }

  .swiper-button-next:after, 
  .swiper-button-prev:after {
    color: #FFFFFF;
    font-size: 16px;
    font-weight: 700;
  }

  .swiper-button-prev {
      left: 0px;
  }
  .swiper-button-next {
      right: 0px;
  }

  .swiper-pagination-bullet-active {
    background-color: #a20720 !important;
  }
</style>
`;

function fetchData(url) {
  return new Promise(async (resolve, reject) => {
    try {
      var xhr = new XMLHttpRequest();
      xhr.open("GET", url, true);

      xhr.onload = function () {
        if (xhr.status >= 200 && xhr.status < 300) {
          try {
            const responseObject = JSON.parse(xhr.responseText);
            resolve(responseObject);
          } catch (parseError) {
            reject("Error parsing response:", parseError);
          }
        } else {
          reject("Request failed with status:", xhr.status);
        }
      };

      xhr.onerror = function () {
        reject("Request failed");
      };

      xhr.send();
    } catch (error) {
      reject(error);
    }
  });
}

async function fetchDataAsync(newspaper) {
  try {
    if (!newspaper) {
      throw new Error(constants.NOT_FOUND);
    }

    const response = await fetchData(
      `${API_CONFIG.API_URL}/${API_CONFIG.API_KEY}/${newspaper}`
    );

    return response;
    // Handle the response here
  } catch (error) {
    if (error.message === constants.NOT_FOUND) {
      console.error("404 Not Found:", error.message);
    } else {
      console.error("Error:", error);
      // Handle other errors here
    }
  }
}

function stringToHTML(str) {
  var parser = new DOMParser();
  var doc = parser.parseFromString(str, "text/html");
  return doc.body.firstChild;
}

function createJobAdsPositionContainer(jobads) {
  const jobAdsPositionContainer = document.createElement("div");
  jobAdsPositionContainer.classList.add("sm-jobads-position");

  const companyLogoContainer = createCompanyLogoContainer(jobads);
  const jobTextContainer = createJobTextContainer(jobads);

  jobAdsPositionContainer.appendChild(companyLogoContainer);
  jobAdsPositionContainer.appendChild(jobTextContainer);
  return jobAdsPositionContainer;
}

function createCompanyLogoContainer(jobads) {
  const companyLogoContainer = document.createElement("div");
  companyLogoContainer.classList.add("sm-jobads-company-logo-container");

  const companyLogoImage = document.createElement("img");
  companyLogoImage.classList.add("sm-jobads-company-logo-image");
  companyLogoImage.src = jobads?.is_confidential ? questionMarkImg :
    jobads.company.logo_url && jobads.company.logo_url !== ""
      ? jobads.company.logo_url
      : questionMarkImg;
  companyLogoContainer.appendChild(companyLogoImage);
  const companyLogoParentContainer = document.createElement("div");
  companyLogoParentContainer.classList.add(
    "sm-jobads-company-logo-parent-container"
  );
  companyLogoParentContainer.appendChild(companyLogoContainer);

  return companyLogoParentContainer;
}

function createJobTextContainer(jobads) {
  const jobTextContainer = document.createElement("div");
  jobTextContainer.classList.add("sm-jobads-text-container");

  const jobTitleContainer = createJobTitleContainer(jobads);
  const companyTitleContainer = createCompanyTitleContainer(jobads);
  const jobLocationContainer = createJobLocationContainer(jobads);

  jobTextContainer.appendChild(jobTitleContainer);
  jobTextContainer.appendChild(companyTitleContainer);
  jobTextContainer.appendChild(jobLocationContainer);
  return jobTextContainer;
}

function createJobTitleContainer(jobads) {
  const jobTitleContainer = document.createElement("div");
  jobTitleContainer.classList.add("sm-jobads-position-title-container");
  jobTitleContainer.innerHTML = `
          <div>${jobads.job_title.zh}</div>
          <div>${jobads.job_title.en}</div>
      `;

  return jobTitleContainer;
}

function createCompanyTitleContainer(jobads) {
  const companyTitleContainer = document.createElement("div");
  companyTitleContainer.classList.add("sm-jobads-position-company-container");
  companyTitleContainer.innerHTML = `${jobads.is_confidential ? 'Confidential Advertiser' : jobads.company.name}`;

  return companyTitleContainer;
}

function createJobTagsContainer(jobads) {
  const jobTagsContainer = document.createElement("div");
  jobTagsContainer.classList.add("sm-jobads-tags-container");

  const tags = [
    "sm-jobads-employment-type-tag",
    "sm-jobads-education-level-tag",
    "sm-jobads-total-experience-tag",
  ];

  tags.map((tagClass) => {
    const tagElement = document.createElement("div");
    tagElement.classList.add("sm-jobads-tags", tagClass);
    tagElement.innerHTML = getTagValue(tagClass, jobads);
    jobTagsContainer.appendChild(tagElement);
  });
  return jobTagsContainer;
}

function getTagValue(tagClass, jobads) {
  switch (tagClass) {
    case "sm-jobads-employment-type-tag":
      return employmentType[jobads.employment_type];
    case "sm-jobads-education-level-tag":
      return jobads.education_level?.name?.zh ?? "学历不限";
    case "sm-jobads-total-experience-tag":
      return `${jobads.total_experience} 年经验`;
    default:
      return "";
  }
}

function createJobSalaryAndLocationContainer(jobads) {
  const jobSalaryAndLocationContainer = document.createElement("div");
  jobSalaryAndLocationContainer.classList.add(
    "sm-jobads-salary-and-location-container"
  );

  const jobSalaryContainer = createJobSalaryContainer(jobads);

  jobSalaryAndLocationContainer.appendChild(jobSalaryContainer);
  return jobSalaryAndLocationContainer;
}

function createJobSalaryContainer(jobads) {
  const jobSalaryContainer = document.createElement("div");
  jobSalaryContainer.classList.add("sm-jobads-salary-container");
  const currency = jobads.currency ?? 'MYR'
  jobSalaryContainer.innerHTML = jobads.is_negotiable ? `Contact For Enquiry` : `${currency} ${jobads.min_salary ? Math.floor(jobads.min_salary).toLocaleString('en-US') : ""} - ${currency} ${jobads.max_salary ? Math.floor(jobads.max_salary).toLocaleString('en-US') : ""}`;
  return jobSalaryContainer;
}

function createJobLocationContainer(jobads) {
  const jobLocationContainer = document.createElement("div");
  jobLocationContainer.classList.add("sm-jobads-location-container");
  jobLocationContainer.innerHTML = `${jobads.city}, ${jobads.state}`;

  return jobLocationContainer;
}

function createJobAdsElement(jobads, anchorHref = "") {
  const anchorElement = document.createElement("a");
  anchorElement.classList.add("sm-jobads-card", "swiper-slide");
  if (anchorHref) {
    anchorElement.href = anchorHref;
    anchorElement.target = "_blank";
  }

  const jobAdsPositionContainer = createJobAdsPositionContainer(jobads);
  // const jobTagsContainer = createJobTagsContainer(jobads);

  const jobAdsUpperPart = document.createElement("div");
  jobAdsUpperPart.classList.add("sm-jobads-upper-part");
  jobAdsUpperPart.appendChild(jobAdsPositionContainer);
  // jobAdsUpperPart.appendChild(jobTagsContainer);

  const jobSalaryAndLocationContainer =
    createJobSalaryAndLocationContainer(jobads);

  anchorElement.appendChild(jobAdsUpperPart);
  anchorElement.appendChild(jobSalaryAndLocationContainer);
  return anchorElement;
}

function createJobAdsContainer(fragment) {
  const jobAdsContainer = document.createElement("div");
  jobAdsContainer.classList.add("sm-jobads-container", "swiper-wrapper");
  jobAdsContainer.appendChild(fragment);
  return jobAdsContainer;
}

var isEmptyJobAds = true

async function renderData() {
  try {
    const response = await fetchDataAsync("sinchew");
    const jobAdsFragment = document.createDocumentFragment();
    let jobAdsElement;
    if(response.data?.length > 0) {
      isEmptyJobAds = false
      response.data?.forEach((jobads) => {
        const targetUrl = API_CONFIG.APP_URL + "/zh/services/" +  (jobads?.platform_uuid ?? jobads.id) + jobads.slug;
        const jobAdsElement = createJobAdsElement(jobads, targetUrl);
        jobAdsFragment.appendChild(jobAdsElement);
      });
    } else {
      for(var i = 0; i < 3; i++) {
        jobAdsElement = document.createElement("div");
        jobAdsElement.classList.add("swiper-slide");
        jobAdsFragment.appendChild(jobAdsElement);
      }
    }
    const jobAdsContainer = createJobAdsContainer(jobAdsFragment);
    return jobAdsContainer.outerHTML;
  } catch (error) {
    console.error(error);
  }
}

async function renderHTML() {
  const containerString = await renderData();

  const swiperCssSrc =
  '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.css"/>';
  const swiperJsSrc =
  '<script src="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.js"></script>';

  const customHeader = `
    <title>JobMacha</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    ${swiperCssSrc}
    ${styleText}
  `;

  const swiperContainerString = `
    <div class="swiper-parent">
      <div class="swiper">
        ${containerString}
      </div>

      <div class="swiper-button-prev"></div>
      <div class="swiper-button-next"></div>
      <div class="swiper-pagination"></div>
    </div>
  `;

  const customScript = `
    <script>
      var element = document.querySelector('.swiper');
      var computedStyle = window.getComputedStyle(element);

      const swiper = new Swiper('.swiper', {
        slidesPerGroup: 2,
        rewind: true,
        slidesPerView: 2,
        spaceBetween: 4,
        breakpoints: {
          638: { // 360 + 128 + 30
            slidesPerGroup: 3,
            slidesPerView: 3,
          },
          698: { // 540 + 128 + 30
            slidesPerGroup: 3,
            slidesPerView: 3,
          },
        },
        grid : {
          rows: 2,
          fill: "row",
        },
        navigation: {
          nextEl: '.swiper-button-next',
          prevEl: '.swiper-button-prev',
        },
        pagination: {
          el: ".swiper-pagination",
        },
      });
    </script>
  `;

  const jobMachaHeader = `
    <div class="jobmacha-header">
      <div class="jobmacha-logo-container">
      <img src="${jobMachaLogo}"/>
      </div>
      <div class="jobmacha-button-container">
        <a class="jobmacha-button-link" target="_blank" href="${API_CONFIG.APP_URL}/zh/advertiser/create-post">
          <div class="jobmacha-button post-ads">
            刊登广告
          </div>
        </a>

        <a class="jobmacha-button-link" target="_blank" href="${API_CONFIG.APP_URL}/zh/services">
          <div class="jobmacha-button more-ads">
            更多广告
          </div>
        </a>
      </div>
    </div>
  `;

  const fullHtmlString = `
    <html>
      <head>
        ${customHeader}
      </head>
      <body>
        <div class="jobmacha-parent-container">
          ${jobMachaHeader}
          ${swiperContainerString}
        </div>
        ${swiperJsSrc}
        ${customScript}
      </body>
    </html>
  `;

  return fullHtmlString;
}

async function renderIframe() {
  try {
    const htmlString = await renderHTML();

    var iframe = document.createElement("iframe");
    iframe.className = "sm-jobads-iframe-container";
    iframe.style.border = "none";

    if (!iframe || iframe.tagName.toLowerCase() !== "iframe") {
      console.log("Error: jobads-iframe-container is either null or not an iframe.");
      return;
    }
    console.log("Log: jobads-iframe-container is created.");

    // Set iframe attributes for full size
    iframe.style.width = "100%";
    iframe.style.height = "0px";

    // Listen for the load event on the iframe
    iframe.onload = function() {
      var iframeDocument = iframe.contentDocument || iframe.contentWindow?.document;
      if (!iframeDocument) {
        console.log("Error: Could not access iframe document.");
        return;
      }
      console.log("Log: iframe document is accessible.");

      // Write content into the iframe document
      iframeDocument.write(htmlString);
    };

    var parent = document.querySelector(".sm-jobads-container");
    if (!parent || parent.tagName.toLowerCase() !== "div") {
      console.log("Error: jobads-container is either null or not a div.");
      return;
    }

    parent.appendChild(iframe);
    setTimeout(updateIframeMinHeightV2, 5000);
    return iframe;
  } catch (error) {
    console.error(error);
  }
}

function updateIframeMinHeight() {
  return;
  iframe = document.querySelector('.sm-jobads-iframe-container');

  var iframeDocument = iframe.contentDocument || iframe.contentWindow?.document;
  if (!iframeDocument) {
    return;
  }
  
  var height = iframeDocument.documentElement.offsetHeight + 50;
  iframe.style.height = `${height}px`;
}

function updateIframeMinHeightV2() {
  if(isEmptyJobAds) return
  iframe = document.querySelector('.sm-jobads-iframe-container');

  var iframeDocument = iframe.contentDocument || iframe.contentWindow?.document;
  if (!iframeDocument) {
    return;
  }
  
  var height = iframeDocument.documentElement.offsetHeight + 50;
  iframe.style.height = `${height}px`;
}

renderIframe();
})();