<script>
// 🔽 This function toggles the dropdown menu when you click the user button
function toggleDropdown() {
  document.getElementById("profileDropdown").classList.toggle("show");
}

// 🖱️ This global click handler closes the dropdown when clicking outside of it
window.onclick = function(event) {
  // If the clicked element is NOT inside a dropdown...
  if (!event.target.closest('.dropdown')) {
    // Hide all elements with the class 'dropdown-content'
    document.querySelectorAll(".dropdown-content").forEach(drop => {
      drop.classList.remove("show");
    });
  }
}
</script>





<!-- Chart.js -->
<!-- Load Chart.js and the Data Labels plugin -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels"></script>

<script>
// 📊 Chart instance reference and default type
let chartInstance = null;
let currentType = 'bar';

// 📁 Chart data passed from PHP (PHPRunner variables)
const allData = {
  labels: {$chart_labels},              // X-axis labels
  values: {$chart_values},              // Y-axis values
  year: "<?php echo $selected_year ?>"  // Selected year
};

// 🔧 Main function to draw the chart
function drawChart(type = 'bar') {
  const ctx = document.getElementById('productChart').getContext('2d');

  // If a chart already exists, destroy it before redrawing
  if (chartInstance) chartInstance.destroy();

  // Create new chart
chartInstance = new Chart(ctx, {
    type: type,
    data: {
      labels: allData.labels,
      datasets: [{
        label: '',
        data: allData.values,
        backgroundColor: [
          '#007BFF', '#28A745', '#DC3545', '#FFC107', '#6F42C1', '#17A2B8'
        ],
        borderRadius: 6
      }]
    },
    options: {
      responsive: true,
      plugins: {
        // 🎯 Show labels directly on top of bars (if bar chart)
        datalabels: {
          display: type === 'bar',
          anchor: 'end',
          align: 'top',
          font: {
            weight: 'bold'
          }
        },
        legend: {
          display: type !== 'bar' // Only show legend for non-bar charts
        },
        title: {
          display: false // Title is hidden (you can enable it if you want)
        }
      },
      animation: {
        duration: 1000,
        easing: 'easeOutBounce'
      },
      scales: type === 'bar' ? {
        y: {
          beginAtZero: true
        }
      } : {} // No Y-axis if not bar
    },
    plugins: [ChartDataLabels]
  });
}


// 🔄 Toggle between bar and pie chart views
function toggleChartType() {
  currentType = currentType === 'bar' ? 'pie' : 'bar';
  drawChart(currentType);
}

// ⬇️ Export the chart as a PNG image
function downloadChart() {
  const link = document.createElement('a');
  link.download = 'product_chart.png';
  link.href = chartInstance.toBase64Image(); // Convert chart to image
  link.click();
}

// 📅 Apply year-based filter to reload the page with a query string
function filterByYear(year) {
  if (year === "all") {
    window.location.href = window.location.pathname;
  } else {
    const params = new URLSearchParams(window.location.search);
    params.set('year', year);
    window.location.search = params.toString();
  }
}

// 🧠 Draw chart after page is fully loaded
document.addEventListener("DOMContentLoaded", () => {
  drawChart();
});
</script>


<script>
// 🪟 Function to open a modal and load a URL in the iframe
function openModal(url) {
  event.preventDefault(); // Prevent the default link or button behavior

  const modal = document.getElementById("customModal");     // Modal container
  const frame = document.getElementById("modalFrame");      // The iframe inside the modal

  frame.src = url;                // Set the iframe's source to the provided URL
  modal.style.display = "flex";  // Show the modal (flex to center it)
  document.body.style.overflow = 'hidden'; // Prevent page scroll while modal is open
}

// ❌ Function to close the modal
function closeModal() {
  const modal = document.getElementById("customModal");
  const frame = document.getElementById("modalFrame");

  modal.style.display = "none";  // Hide the modal
  frame.src = "";                // Clear the iframe content
  document.body.style.overflow = ''; // Re-enable scrolling on the page
}
</script>



<script>
// 📌 Store the previous scroll position
let lastScrollY = window.scrollY;

// 🎯 Target the page header element
const header = document.querySelector("header");

// 🚀 Listen for scroll events
window.addEventListener("scroll", () => {
  const currentScrollY = window.scrollY;

  // 📦 Add 'shadow' and 'shrink' classes when scrolled more than 80px
  if (currentScrollY > 80) {
    header.classList.add("shadow", "shrink");
  } else {
    header.classList.remove("shadow", "shrink");
  }

  // 👻 Hide header if scrolling down fast past 150px
  if (currentScrollY > lastScrollY && currentScrollY > 150) {
    header.classList.add("hidden");
  } else {
    header.classList.remove("hidden");
  }

  // 🔁 Update scroll position
  lastScrollY = currentScrollY;
});
</script>


<script>
// 🔍 Main function to filter jobs based on keyword, category, and state
function filterJobs(keyword) {
  keyword = keyword.toLowerCase(); // Convert keyword to lowercase for case-insensitive matching

  const selectedState = document.getElementById("filterState").value.toLowerCase();   // Selected State
  const catFilter = document.getElementById("filterCategory").value.toLowerCase();    // Selected Category

  // Loop through each job card
  document.querySelectorAll('.card').forEach(card => {
    const title = card.querySelector('.job-title').textContent.toLowerCase();         // Job Title
    const category = card.getAttribute('data-category')?.toLowerCase() || "";         // Job Category (from data-attribute)
    const state = card.getAttribute('data-state')?.toLowerCase() || "";               // Job State (from data-attribute)

    const matchesCat = !catFilter || category.includes(catFilter);     // Match if no filter or category matches
    const matchesState = !selectedState || state.includes(selectedState); // Same logic for state
    const matchesTitle = title.includes(keyword);                     // Title match

    // 👁 Show or hide the card based on matching logic
    card.style.display = (matchesTitle && matchesCat && matchesState) ? 'block' : 'none';
  });
}

// 🧭 These trigger the main filterJobs() when dropdown filters change
function filterByCategory(category) {
  const keyword = document.querySelector('input[type=text]').value;
  filterJobs(keyword);
}

function filterJobsByState(state) {
  const keyword = document.querySelector('input[type=text]').value;
  filterJobs(keyword);
}

// ⬇️ Export filtered jobs to CSV file
function exportCSV() {
  let csv = "Title,Company,City,Posted,Expires\n"; // CSV Header

  // Loop through visible job cards and extract text
  document.querySelectorAll('.card').forEach(card => {
    const title = card.querySelector('.job-title').textContent.trim(); // Job title

    const meta = card.querySelectorAll('.job-meta')[0].innerText.split('\n'); // Meta lines (assumes 4 lines)
    csv += `${title},${meta[0].split(': ')[1]},${meta[1].split(': ')[1]},${meta[2].split(': ')[1]},${meta[3].split(': ')[1]}\n`;
  });

  // Encode the CSV as a downloadable link
  const encodedUri = encodeURI('data:text/csv;charset=utf-8,' + csv);
  const link = document.createElement('a');
  link.setAttribute('href', encodedUri);
  link.setAttribute('download', 'jobs_list.csv');

  // Trigger download
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}
</script>


<script>
// 🗺️ Filter jobs based on selected state, title input, and category filter
function filterByState(state) {
  state = state.toLowerCase(); // Ensure case-insensitive comparison

  const titleInput = document.querySelector('input[type=text]').value.toLowerCase();   // Keyword typed in
  const catFilter = document.getElementById("filterCategory").value.toLowerCase();     // Selected category

  // 🔁 Loop through all job cards
  document.querySelectorAll('.card').forEach(card => {
    const description = card.innerText.toLowerCase();                                   // Entire card text
    const stateMatches = !state || description.includes(state);                         // True if no state filter or match
    const titleMatch = card.querySelector('.job-title').textContent.toLowerCase().includes(titleInput); // Title match
    const catMatch = !catFilter || card.getAttribute('data-category')?.toLowerCase().includes(catFilter); // Category match

    // 👁 Show or hide card based on combined matching rules
    card.style.display = (stateMatches && titleMatch && catMatch) ? 'block' : 'none';
  });
}
</script>


<script>
// 🪟 Open a popup modal and load a page into the iframe
function openPopup(url) {
  const modal = document.getElementById("customModal");   // The modal container
  const iframe = document.getElementById("modalFrame");   // The iframe inside the modal

  iframe.src = url;                // Load the requested page in the iframe
  modal.style.display = "flex";   // Show the modal using flexbox
  document.body.style.overflow = "hidden"; // Prevent background scrolling
}
</script>


<script>
// 📩 Listen for messages sent from an iframe (usually after a form submit)
window.addEventListener("message", function(event) {
  // ✅ If the message from the iframe is exactly 'application_success'
  if (event.data === "application_success") {
    // ❌ Close the modal (assumes you're using Bootstrap modal)
    $('#applyModal').modal('hide');

    // ✅ Show success toast notification
    const toast = new bootstrap.Toast(document.getElementById('applicationToast'));
    toast.show();
  }
});
</script>


<script>
// 🔁 Toggle between showing preview and full description in job cards
function toggleDescription(link) {
  // 🔍 Find the preview and full description elements
  const preview = link.previousElementSibling.previousElementSibling; // The short preview
  const full = link.previousElementSibling;                           // The full description

  // 🎭 Show or hide full/preview description
  if (full.style.display === "none") {
    preview.style.display = "none";      // Hide preview
    full.style.display = "inline";       // Show full text
    link.textContent = "Show less";      // Update link text
  } else {
    preview.style.display = "inline";    // Show preview again
    full.style.display = "none";         // Hide full description
    link.textContent = "Read more";      // Reset link text
  }
}
</script>


<script>
// 🔁 Toggle between preview and full location display
function toggleLocation(link) {
  const preview = link.previousElementSibling.previousElementSibling; // Short version
  const full = link.previousElementSibling;                           // Full location

  if (full.style.display === "none") {
    preview.style.display = "none";
    full.style.display = "inline";
    link.textContent = "Show less";
  } else {
    preview.style.display = "inline";
    full.style.display = "none";
    link.textContent = "Read more";
  }
}
</script>

<script>
// ❌ Close the guest welcome popup
function closeGuestPopup() {
  const popup = document.getElementById("guestPopup");
  popup.style.display = "none";
}
</script>

<script>
// 📢 Show a message prompting guests to register before applying
function showApplyMessage(btn, jobId) {
  // ✅ If the user is already logged in, do nothing
  if (<?php echo json_encode(isLogged()); ?>) return;

  // 🔍 Check if the popup already exists
  let existing = btn.parentElement.querySelector('.apply-message-popup');

  // 🧱 If not, create and insert it
  if (!existing) {
    const div = document.createElement('div');
    div.className = 'apply-message-popup';
    div.innerHTML = `
      You need to register to apply.<br>
      <button onclick="openModal('register.php?page=register_jobseeker')">Register</button>
    `;
    btn.parentElement.appendChild(div);
  }

  // 📣 Show the popup
  btn.parentElement.querySelector('.apply-message-popup').style.display = 'block';

  // ⏱ Hide it after 6 seconds
  setTimeout(() => {
    const popup = btn.parentElement.querySelector('.apply-message-popup');
    if (popup) {
      popup.style.display = 'none';
    }
  }, 6000);
}
</script>

<script>
// 🌐 Open remote job modal and load external job URL in iframe
function openRemoteJobModal(url) {
  document.getElementById('remoteJobFrame').src = url;         // Load the job URL
  document.getElementById('remoteJobModal').style.display = 'flex'; // Show modal
  document.body.style.overflow = 'hidden';                     // Disable background scroll
}

// ❌ Close the modal and clear iframe content
function closeRemoteJobModal() {
  document.getElementById('remoteJobModal').style.display = 'none'; // Hide modal
  document.getElementById('remoteJobFrame').src = '';               // Clear iframe
  document.body.style.overflow = '';                                // Restore scroll
}

// 🖱 Close modal if user clicks outside the iframe content area
window.addEventListener('click', function(e) {
  const modal = document.getElementById('remoteJobModal');

  // Only close if the actual background (not the iframe) was clicked
  if (e.target === modal) {
    closeRemoteJobModal();
  }
});
</script>

<script>
// 📂 Scroll to a category section when it's selected from the dropdown
document.getElementById("category").addEventListener("change", function() {
  const value = this.value; // Get the selected category value
  const el = document.getElementById("category-" + value); // Match corresponding section ID

  // 🧭 Scroll to the element smoothly if it exists
  if (el) {
    el.scrollIntoView({
      behavior: "smooth", // Smooth scroll effect
      block: "start"      // Align to top of the page
    });
  }
});
</script>

<script>
document.addEventListener("DOMContentLoaded", function () {
  const wrapper = document.querySelector(".external-jobs-wrapper"); // Container for remote jobs

  // 🔁 Function to fetch jobs from the server using AJAX
  function fetchRemoteJobs(page) {
    // ⏳ Show a loading animation while fetching
    wrapper.innerHTML = `
      <div class="loader">
        Loading<span class="dot">.</span><span class="dot">.</span><span class="dot">.</span>
      </div>
    `;

    // 📡 Fetch the remote job listings
    fetch(`jobsjobs_list.php?page=${page}&ajax_remote_jobs=1`)
      .then(res => res.text())           // Convert response to HTML string
      .then(html => {
        const tempDiv = document.createElement("div");
        tempDiv.innerHTML = html;
        tempDiv.style.opacity = 0;
        tempDiv.style.transition = "opacity 0.4s ease, transform 0.4s ease";
        tempDiv.style.transform = "translateX(30px)";

        // 🔄 Replace current job listings with new content
        wrapper.innerHTML = '';
        wrapper.appendChild(tempDiv);

        // ✨ Animate fade-in after short delay
        setTimeout(() => {
          tempDiv.style.opacity = 1;
          tempDiv.style.transform = "translateX(0)";
        }, 50);
      });
  }

//_________________________________________________________________________________________________New

function animateNewCards() {
  document.querySelectorAll('.job-card').forEach((card, index) => {
    setTimeout(() => {
      card.classList.add('highlight-card');
      setTimeout(() => {
        card.classList.remove('highlight-card');
      }, 900); // match animation duration
    }, index * 100); // slight stagger between cards
  });
}

//________________________________________________________________________________________________New

  // 🖱 Listen for clicks on pagination links
  document.body.addEventListener("click", function (e) {
    if (e.target.classList.contains("page-link")) {
      e.preventDefault();
      const page = e.target.dataset.page; // Get the page number from data-page attribute
      fetchRemoteJobs(page);             // Load jobs via AJAX
    }
  });
});
</script>

<script>
// 🪟 Open a modal and load content via URL in iframe
function openModalWithContent(url) {
  const iframe = document.getElementById("modalFrame");
  iframe.src = url; // Load external content
  document.getElementById("customModal").style.display = "flex"; // Show modal
  document.body.style.overflow = 'hidden'; // Prevent background scroll
}

// ❌ Close the modal and clear the iframe
function closeModal() {
  const iframe = document.getElementById("modalFrame");
  iframe.src = ""; // Clear iframe
  document.getElementById("customModal").style.display = "none"; // Hide modal
  document.body.style.overflow = ''; // Restore scrolling
}
</script>

<script>
// 🔍 On scroll, resize the logo for a sleek effect
window.addEventListener("scroll", function () {
  const logo = document.querySelector(".logo");     // Logo image element
  const header = document.querySelector("header");  // Main page header

  // 🎯 If user scrolls down more than 80px, shrink the logo
  if (window.scrollY > 80) {
    logo.style.transform = "scale(0.8)";
  } else {
    logo.style.transform = "scale(1)";
  }
});
</script>

<script>
// 🧠 Wait until the document is fully loaded
document.addEventListener("DOMContentLoaded", function () {
  const logo = document.querySelector(".logo");    // Your logo element
  const header = document.querySelector("header"); // The header you want to observe

  // 👁️ Create an IntersectionObserver to monitor header visibility
  const observer = new IntersectionObserver(
    ([entry]) => {
      if (entry.isIntersecting) {
        // ✅ Header is visible — restore full logo size
        logo.classList.remove("shrink");
      } else {
        // 🔽 Header is out of view — shrink the logo
        logo.classList.add("shrink");
      }
    },
    {
      threshold: 0.1 // Trigger the callback when 10% of the header is visible
    }
  );

  // 🚀 Start observing the header
  if (header) {
    observer.observe(header);
  }
});
</script>

<script>
function dismissNoJobs() {
  const alert = document.getElementById('noJobsAlert');
  alert.style.opacity = '0';
  alert.style.transform = 'translateY(-20px)';
  setTimeout(() => alert.style.display = 'none', 400);
}
</script>

<style>
/* Animation when card appears */
.slide-in {
  animation: slideFadeIn 0.8s ease-out;
}

@keyframes slideFadeIn {
  from {
    transform: translateY(30px);
    opacity: 0;
  }
  to {
    transform: translateY(0px);
    opacity: 1;
  }
}
</style>

<script>
// 🎯 Toggle popup and store dismiss state
function toggleDisclaimerPopup() {
  const popup = document.getElementById("disclaimerPopup");
  const trigger = document.getElementById("disclaimerTrigger");
  const dontShow = document.getElementById("dontShowAgain");
  const toast = document.getElementById("toastDisclaimer");

  const isHidden = popup.style.display === "none" || !popup.style.display;
  popup.style.display = isHidden ? "block" : "none";
  trigger.style.display = isHidden ? "none" : "block";

  if (!isHidden) {
    const dismissUntil = dontShow?.checked
      ? Date.now() + 7 * 24 * 60 * 60 * 1000 // 7 days
      : Date.now() + 1 * 60 * 60 * 1000;     // 1 hour

    localStorage.setItem("jobDisclaimerDismissedUntil", dismissUntil);

    // ✅ Show toast if checkbox was ticked
    if (dontShow?.checked && toast) {
      toast.style.display = "block";
      setTimeout(() => {
        toast.style.display = "none";
      }, 4000); // hide after 4 seconds
    }
  }
}

document.addEventListener("DOMContentLoaded", function () {
  const jobCards = document.getElementById("jobsContainer");
  const externalJobs = document.querySelector(".external-jobs-wrapper");
  const popup = document.getElementById("disclaimerPopup");
  const trigger = document.getElementById("disclaimerTrigger");

  const hasJobs = jobCards && jobCards.innerHTML.trim() !== "";
  const hasExternal = externalJobs && externalJobs.innerHTML.trim() !== "";

  const storedTime = localStorage.getItem("jobDisclaimerDismissedUntil");
  const now = Date.now();

  const isDismissed = storedTime && parseInt(storedTime) > now;

  if (!hasJobs && !hasExternal) {
    popup.style.display = "none";
    trigger.style.display = "none";
  } else {
    popup.style.display = isDismissed ? "none" : "block";
    trigger.style.display = isDismissed ? "block" : "none";
  }
});
</script>

<script>
function manualReopenDisclaimer() {
  const popup = document.getElementById("disclaimerPopup");
  const trigger = document.getElementById("disclaimerTrigger");
  if (popup && trigger) {
    popup.style.display = "block";
    trigger.style.display = "none";
  }
}

document.addEventListener("DOMContentLoaded", function () {
  const label = document.getElementById("disclaimerLastSeen");
  const timestamp = localStorage.getItem("jobDisclaimerDismissedUntil");

  if (label && timestamp) {
    const date = new Date(parseInt(timestamp));
    label.textContent = date.toLocaleString();
  } else if (label) {
    label.textContent = "Not dismissed yet.";
  }
});
</script>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels"></script>
<script>
const ctx = document.getElementById('productChart').getContext('2d');
// Assigned from PHPRunner
const labels = {$chart_labels};
const values = {$chart_values};

const total = values.reduce((sum, val) => sum + val, 0);

const chart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: labels,
    datasets: [{
      label: 'Jobs by Location',
      data: values,
      backgroundColor: [
        '#007BFF', '#28A745', '#DC3545', '#FFC107', '#6F42C1', '#17A2B8'
      ],
      borderRadius: 6
    }]
  },
  options: {
    responsive: true,
    plugins: {
      tooltip: {
        callbacks: {
          label: function(context) {
            const value = context.raw;
            const percentage = ((value / total) * 100).toFixed(1);
            const jobText = value === 1 ? "Job" : "Jobs";
            return `${value} ${jobText} in ${context.label}`;
            //return `${value} ${jobText} in ${context.label} (${percentage}%)`;
          }
        }
      },
      datalabels: {
        display: true,
        anchor: 'end',
        align: 'top',
        font: {
          weight: 'bold'
        }
      },
      legend: {
        display: false
      },
      title: {
        display: false
      }
    },
    animation: {
      duration: 1000,
      easing: 'easeOutBounce'
    },
    scales: {
      y: {
        beginAtZero: true
      }
    }
  },
  plugins: [ChartDataLabels]
});
</script>

<script>
function scrollToTop() {
  window.scrollTo({
    top: 0,
    behavior: 'smooth'
  });
  const header = document.querySelector("header");
  // 👇 Add a glow or bounce effect when header becomes visible
  header.classList.add("highlight-top");
  // Remove the class after animation ends (1 second)
  setTimeout(() => {
    header.classList.remove("highlight-top");
  }, 900);
}
</script>

<script>
function openContactModal() {
  document.getElementById("contactModal").style.display = "flex";
}
function closeContactModal() {
  document.getElementById("contactModal").style.display = "none";
}
function submitContact() {
  const email = document.getElementById("contactEmail").value;
  const message = document.getElementById("contactMessage").value;
  const feedback = document.getElementById("contactFeedback");

  // TODO: replace with real AJAX or send to PHP endpoint
  feedback.innerHTML = `✅ Thank you! We'll respond shortly.`;
  document.getElementById("contactEmail").value = "";
  document.getElementById("contactMessage").value = "";
  return false;
}

function openChat() {
  alert("🔧 Chat widget integration coming soon!");
}
</script>

<script>
function togglePanel() {
  const panel = document.getElementById("floatingPanel");
  panel.classList.toggle("expanded");

  const toggleBtn = panel.querySelector(".panel-toggle");
  toggleBtn.textContent = panel.classList.contains("expanded") ? "⏶" : "☰";
}
</script>

<!-- Load Chart.js and DataLabels plugin first -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels"></script>

<!-- 📊 SCRIPT: Initialize All Charts -->
<script>
document.addEventListener("DOMContentLoaded", function () {
  const charts = [
    { id: "govtChart", data: [{$govt_active_raw}, {$govt_expired7_raw}, {$govt_archived_raw}], prefix: 'govt' },
    { id: "sprepChart", data: [{$sprep_active_raw}, {$sprep_expired7_raw}, {$sprep_archived_raw}], prefix: 'sprep' },
    { id: "spcChart", data: [{$spc_active_raw}, {$spc_expired7_raw}, {$spc_archived_raw}], prefix: 'spc' },
    { id: "undpChart", data: [{$undp_active_raw}, {$undp_expired7_raw}, {$undp_archived_raw}], prefix: 'undp' },
    { id: "pifsChart", data: [{$pifs_active_raw}, {$pifs_expired7_raw}, {$pifs_archived_raw}], prefix: 'pifs' },
    { id: "ffaChart", data: [{$ffa_active_raw}, {$ffa_expired7_raw}, {$ffa_archived_raw}], prefix: 'ffa' },
    { id: "pjnChart", data: [{$pjn_active_raw}, {$pjn_expired7_raw}, {$pjn_archived_raw}], prefix: 'pjn' },
    { id: "userChart", data: [{$user_active_raw}, {$user_expired7_raw}, {$user_archived_raw}], prefix: 'user' },
    { id: "himalayasChart", data: [0, 0, 0] }
  ];

    charts.forEach(({ id, data, prefix }) => {
    const ctx = document.getElementById(id);
    if (!ctx) return;

    const total = data.reduce((a, b) => a + b, 0);
    const percentages = data.map(v => total > 0 ? ((v / total) * 100).toFixed(1) + '%' : '0%');

    if (prefix) {
      const activeEl = document.getElementById(`${prefix}_active_pct`);
      const expiredEl = document.getElementById(`${prefix}_expired_pct`);
      const archivedEl = document.getElementById(`${prefix}_archived_pct`);
      if (activeEl) activeEl.textContent = percentages[0];
      if (expiredEl) expiredEl.textContent = percentages[1];
      if (archivedEl) archivedEl.textContent = percentages[2];
    }

    new Chart(ctx, {
      type: 'doughnut',
      data: {
        labels: ["Active", "Expired", "Archived"],
        datasets: [{
          data: data,
          backgroundColor: ["#34a853", "#ea4335", "#9aa0a6"],
          borderWidth: 0
        }]
      },
      options: {
        plugins: {
          legend: { display: false },
          datalabels: {
            color: '#fff',
            font: { weight: 'bold', size: 12 },
            formatter: (value, ctx) => {
              const sum = ctx.chart.data.datasets[0].data.reduce((a, b) => a + b, 0);
              return sum ? Math.round((value / sum) * 100) + '%' : '';
            }
          }
        },
        cutout: "70%",
        responsive: true,
        maintainAspectRatio: false
      },
      plugins: [ChartDataLabels]
    });
  });
});
</script>

<!-- 📌 DRAG + PIN SCRIPT -->
<script>
function togglePin(button, cardId, innerId) {
  const card = document.getElementById(cardId);
  const inner = document.getElementById(innerId);
  const label = button.nextElementSibling;

  if (inner.classList.contains("pinned")) {
    inner.classList.remove("pinned");
    card.classList.remove("pinned");
    label.textContent = "Pin to stop flip";
    button.textContent = "";
  } else {
    inner.classList.add("pinned");
    card.classList.add("pinned");
    label.textContent = "Unpin to allow flip";
    button.textContent = "📌";
  }
}

function makeDraggable(selector) {
  const container = document.getElementById("dashboard");
  let dragged = null;

  document.querySelectorAll(selector).forEach(card => {
    card.setAttribute("draggable", true);

    card.addEventListener("dragstart", function (e) {
      dragged = this;
      e.dataTransfer.effectAllowed = "move";
      this.style.opacity = 0.5;
    });

    card.addEventListener("dragend", function () {
      this.style.opacity = 1;
    });

    card.addEventListener("dragover", function (e) {
      e.preventDefault();
      e.dataTransfer.dropEffect = "move";
    });

    card.addEventListener("drop", function (e) {
      e.preventDefault();
      if (dragged && dragged !== this) {
        const children = Array.from(container.children);
        const draggedIndex = children.indexOf(dragged);
        const targetIndex = children.indexOf(this);
        if (draggedIndex < targetIndex) {
          container.insertBefore(dragged, this.nextSibling);
        } else {
          container.insertBefore(dragged, this);
        }
      }
    });
  });
}

document.addEventListener("DOMContentLoaded", function () {
  makeDraggable(".draggable");
});
</script>

<script>
function togglePin(button, cardId, innerId) {
  const card = document.getElementById(cardId);
  const inner = document.getElementById(innerId);
  const label = button.nextElementSibling;

  if (inner.classList.contains("pinned")) {
    inner.classList.remove("pinned");
    card.classList.remove("pinned");
    label.textContent = "Pin to stop flip";
    button.textContent = "📌";
  } else {
    inner.classList.add("pinned");
    card.classList.add("pinned");
    label.textContent = "Unpin to allow flip";
    button.textContent = "📍";
  }
}
</script>


<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels"></script>
<script>
function toggleDashboardCards() {
  const dash = document.getElementById("dashboard");
  const filters = document.getElementById("dashboardFilters");
  const charts = document.getElementById("dashboardCharts");
  const btn = document.getElementById("dashToggleBtnTop");

  dash.classList.toggle("dashboard-hidden");
  filters.classList.toggle("dashboard-filters-hidden");
  charts.classList.toggle("dashboard-charts-hidden");
  charts.classList.toggle("dashboard-chart-wrapper-hidden");

  const isHidden = dash.classList.contains("dashboard-hidden");
  btn.textContent = isHidden ? "Show Dashboard" : "Hide Dashboard";
  localStorage.setItem("dashboardVisible", isHidden ? "hidden" : "visible");

  if (!isHidden) {
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }
}

document.addEventListener("DOMContentLoaded", function () {
  const dash = document.getElementById("dashboard");
  const filters = document.getElementById("dashboardFilters");
  const charts = document.getElementById("dashboardCharts");
  const btn = document.getElementById("dashToggleBtnTop");

  const dashState = localStorage.getItem("dashboardVisible");
  const isInitiallyHidden = dashState === "hidden";

  if (isInitiallyHidden) {
    dash.classList.add("dashboard-hidden");
    filters.classList.add("dashboard-filters-hidden");
    charts.classList.add("dashboard-charts-hidden", "dashboard-chart-wrapper-hidden");
    btn.textContent = "Show Dashboard";
  }
});

function togglePin(button, cardId, innerId) {
  const card = document.getElementById(cardId);
  const inner = document.getElementById(innerId);
  const label = button.nextElementSibling;

  if (inner.classList.contains("pinned")) {
    inner.classList.remove("pinned");
    card.classList.remove("pinned");
    label.textContent = "Pin to stop flip";
    button.textContent = "📌";
  } else {
    inner.classList.add("pinned");
    card.classList.add("pinned");
    label.textContent = "Unpin to allow flip";
    button.textContent = "📍";
  }
}

function toggleUserPostedChart() {
  const chart = document.getElementById("dashboardCharts");
  const filtersToHide = [
    document.getElementById("filterAll"),
    document.getElementById("filterMonth"),
    document.getElementById("filter12mo"),
    document.getElementById("downloadBtn")
  ];
  const btn = document.getElementById("toggleChartBtn");

  const isHidden = chart.classList.toggle("dashboard-charts-hidden");
  chart.classList.toggle("dashboard-chart-wrapper-hidden");

  filtersToHide.forEach(el => {
    if (isHidden) {
      el.classList.add("dashboard-buttons-hidden");
    } else {
      el.classList.remove("dashboard-buttons-hidden");
    }
  });

  btn.textContent = isHidden ? "📊 Show Chart" : "📉 Hide Chart";
}
</script>


<script>
document.addEventListener("DOMContentLoaded", function () {
  // 🟦 General Dropdown Toggle by ID (works for userMenuDropdown or profileDropdown)
  window.toggleDropdownById = function (dropdownId, toggleBtnClass = "") {
    const dropdown = document.getElementById(dropdownId);
    if (!dropdown) return;
    dropdown.style.display = (dropdown.style.display === "block") ? "none" : "block";

    // Optional: auto-close when clicking outside
    document.addEventListener("click", function (event) {
      const toggleBtn = toggleBtnClass ? document.querySelector(toggleBtnClass) : null;
      if (!dropdown.contains(event.target) && (!toggleBtn || !toggleBtn.contains(event.target))) {
        dropdown.style.display = "none";
      }
    }, { once: true });
  };

  // 🔐 Login/Logout Button Visibility (PHP-controlled)
  const isLoggedIn = <?= json_encode(isLogged()); ?>;
  const loginBtn = document.getElementById("loginform_login");
  const logoutBtn = document.getElementById("logout_link");

  if (loginBtn && logoutBtn) {
    if (isLoggedIn) {
      loginBtn.style.display = "none";
      logoutBtn.style.display = "inline-block";
    } else {
      loginBtn.style.display = "inline-block";
      logoutBtn.style.display = "none";
    }
  }

  // 🧩 Shorthand for user menu toggle
  window.toggleUserMenu = function () {
    toggleDropdownById("userMenuDropdown", ".dropdown-toggle");
  };

  window.closeUserMenu = function () {
    const menu = document.getElementById("userMenuDropdown");
    if (menu) menu.style.display = "none";
  };

  // 👤 Optional: support a separate profile dropdown toggle
  window.toggleProfileDropdown = function (event) {
    event.stopPropagation();
    toggleDropdownById("profileDropdown", ".dropdown-btn");
  };
});
</script>

<script>
  function applyTheme(theme) {
    const body = document.body;
    const btn = document.getElementById("themeToggleBtn");
    if (theme === "dark") {
      body.classList.add("dark-mode");
      btn.classList.add("active");
    } else {
      body.classList.remove("dark-mode");
      btn.classList.remove("active");
    }
    localStorage.setItem("theme", theme);
  }

  function toggleTheme() {
    const isDark = document.body.classList.contains("dark-mode");
    applyTheme(isDark ? "light" : "dark");
  }

  document.addEventListener("DOMContentLoaded", () => {
    const saved = localStorage.getItem("theme") || "light";
    applyTheme(saved);
    document.getElementById("themeToggleBtn").addEventListener("click", toggleTheme);
  });
</script>





<script>
// Matrix code background
const canvas = document.getElementById('matrix-bg');
const ctx = canvas.getContext('2d');
let w = canvas.width = window.innerWidth;
let h = canvas.height = window.innerHeight;
const letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789@#$%^&*";
const fontSize = 18;
const columns = Math.floor(w / fontSize);
const drops = Array(columns).fill(1);

function drawMatrix() {
    ctx.fillStyle = "rgba(0,0,0,0.30)";
    ctx.fillRect(0, 0, w, h);

    ctx.font = fontSize + "px monospace";
    ctx.fillStyle = "#00ff57";
    for (let i = 0; i < drops.length; i++) {
        const text = letters.charAt(Math.floor(Math.random() * letters.length));
        ctx.fillText(text, i * fontSize, drops[i] * fontSize);

        if (drops[i] * fontSize > h && Math.random() > 0.975) drops[i] = 0;
        drops[i]++;
    }
}

setInterval(drawMatrix, 140);

window.addEventListener('resize', () => {
    w = canvas.width = window.innerWidth;
    h = canvas.height = window.innerHeight;
});
</script>
<script>
// Display years and days since founding
function updateSinceFounded() {
    const founded = new Date("2012-11-20T00:00:00+13:00");
    const now = new Date();
    // Calculate total days
    const msPerDay = 1000 * 60 * 60 * 24;
    const days = Math.floor((now - founded) / msPerDay);
    // Calculate years and remaining days
    let years = now.getFullYear() - founded.getFullYear();
    let anniversary = new Date(founded);
    anniversary.setFullYear(now.getFullYear());
    if (now < anniversary) years--;
    anniversary.setFullYear(founded.getFullYear() + years);
    const daysSinceAnniversary = Math.floor((now - anniversary) / msPerDay);

    document.getElementById('since-founded').innerText =
        `Serving Samoa and the Pacific for ${years} years and ${daysSinceAnniversary} days (since Nov 20, 2012)`;
}
updateSinceFounded();
setInterval(updateSinceFounded, 3600 * 1000); // Update every hour
</script>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const popup = document.createElement('div');
    popup.className = 'preview-popup';
    document.body.appendChild(popup);

    let hideTimeout;

    function closePopup() {
        popup.classList.add('hide');
        setTimeout(() => {
            popup.style.display = 'none';
            popup.classList.remove('hide');
        }, 220); // match fadeOutPopup animation duration
    }

    function showPopup(link) {
        clearTimeout(hideTimeout);
        const title = link.dataset.previewTitle || '';
        const htmlContent = link.dataset.previewHtml || '';
        const textContent = link.dataset.previewText || '';
        const mapLink = link.dataset.previewLink || '';

        // Close button HTML
        let closeBtn = `<button class="popup-close" aria-label="Close preview" tabindex="0">&times;</button>`;

        let inner = closeBtn;
        inner += title ? `<strong>${title}</strong><br>` : '';
        if (htmlContent) {
            inner += htmlContent;
        } else if (textContent) {
            inner += textContent;
            if (mapLink) {
                inner += `<br><a href="${mapLink}" target="_blank">View on Google Maps</a>`;
            }
        }
        popup.innerHTML = inner;
        popup.style.display = 'block';
        popup.scrollTop = 0;

        // Positioning
        const rect = link.getBoundingClientRect();
        let top = window.scrollY + rect.bottom + 8;
        let left = window.scrollX + rect.left;

        popup.style.maxHeight = '350px';
        popup.style.overflowY = 'auto';
        popup.style.width = '';
        popup.style.transform = '';
        popup.style.bottom = '';

        // Mobile: center and stick to bottom if screen is narrow
        if (window.innerWidth < 600) {
            popup.style.left = '50%';
            popup.style.top = '';
            popup.style.bottom = '10px';
            popup.style.transform = 'translateX(-50%)';
            popup.style.width = '96vw';
        } else {
            popup.style.top = `${top}px`;
            popup.style.left = `${left}px`;
            popup.style.width = '';
            popup.style.transform = '';
            popup.style.bottom = '';

            // Ensure popup stays in viewport (scroll up if needed)
            setTimeout(() => {
                const popupRect = popup.getBoundingClientRect();
                const overflow = (popupRect.bottom > window.innerHeight) ? (popupRect.bottom - window.innerHeight + 14) : 0;
                if (overflow > 0) {
                    popup.style.top = `${top - overflow}px`;
                }
            }, 10);
        }

        // Handle close button click
        popup.querySelector('.popup-close').onclick = closePopup;
    }

    document.querySelectorAll('.preview-link').forEach(link => {
        link.addEventListener('mouseenter', function(e) {
            showPopup(link);
        });
        link.addEventListener('focus', function(e) {
            showPopup(link);
        });
        link.addEventListener('mouseleave', function() {
            hideTimeout = setTimeout(closePopup, 180);
        });
        link.addEventListener('blur', function() {
            hideTimeout = setTimeout(closePopup, 180);
        });
    });

    popup.addEventListener('mouseenter', function() {
        clearTimeout(hideTimeout);
    });
    popup.addEventListener('mouseleave', function() {
        closePopup();
    });

    // Allow keyboard ESC to close the popup
    document.addEventListener('keydown', function(e) {
        if (popup.style.display === 'block' && (e.key === "Escape" || e.keyCode === 27)) {
            closePopup();
        }
    });
});
</script>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Tooltip creation
    let donorTooltip = document.createElement('div');
    donorTooltip.className = 'donor-tooltip';
    donorTooltip.tabIndex = 0; // For accessibility
    document.body.appendChild(donorTooltip);

    let tooltipTimeout;
    let currentTarget = null;

    // Show the tooltip
    function showTooltip(target) {
        currentTarget = target;
        const previewText = target.dataset.previewText || '';
        const previewUrl = target.dataset.previewUrl || target.href;
        const title = target.dataset.previewTitle || target.textContent;
        // Tooltip HTML with close icon
        donorTooltip.innerHTML = `
            <button class="donor-tooltip-close" aria-label="Close preview" tabindex="0">&times;</button>
            <strong>${title}</strong><br>${previewText}<br>
            <a href="#" class="donor-tooltip-visit" data-preview-title="${title}" data-preview-url="${previewUrl}" tabindex="0">Visit Website</a>
        `;
        donorTooltip.style.display = 'block';
        donorTooltip.style.opacity = '1';

        // Position below link
        let rect = target.getBoundingClientRect();
        donorTooltip.style.top = (window.scrollY + rect.bottom + 6) + 'px';
        donorTooltip.style.left = (window.scrollX + rect.left) + 'px';
    }

    // Hide the tooltip
    function hideTooltip() {
        donorTooltip.style.opacity = '0';
        tooltipTimeout = setTimeout(() => {
            donorTooltip.style.display = 'none';
        }, 160);
    }

    // Keep tooltip visible when mouse enters, hide when leaves both link and tooltip
    document.body.addEventListener('mouseover', function(e) {
        if (e.target.classList.contains('donor-preview')) {
            clearTimeout(tooltipTimeout);
            showTooltip(e.target);
        }
    });
    document.body.addEventListener('mouseout', function(e) {
        if (e.target.classList.contains('donor-preview')) {
            tooltipTimeout = setTimeout(hideTooltip, 180);
        }
    });
    donorTooltip.addEventListener('mouseenter', function() {
        clearTimeout(tooltipTimeout);
    });
    donorTooltip.addEventListener('mouseleave', function() {
        hideTooltip();
    });

    // Tooltip close icon
    donorTooltip.addEventListener('click', function(e) {
        if (e.target.classList.contains('donor-tooltip-close')) {
            hideTooltip();
        }
        // Intercept "Visit Website" click to open modal (if using modal for iframe preview)
        if (e.target.classList.contains('donor-tooltip-visit')) {
            e.preventDefault();
            const title = e.target.dataset.previewTitle;
            const url = e.target.dataset.previewUrl;
            // You can call your openDonorModal(title, url) function here if needed
            if (typeof openDonorModal === 'function') openDonorModal(title, url);
            hideTooltip();
        }
    });

    // ESC closes tooltip if focused
    donorTooltip.addEventListener('keydown', function(e) {
        if (e.key === "Escape" || e.keyCode === 27) {
            hideTooltip();
        }
    });
});
</script>


<script>
document.addEventListener('DOMContentLoaded', function() {
    // --- Modal Element References ---
    const modal = document.getElementById('donor-modal');
    const modalHeader = modal.querySelector('.donor-modal-header');
    const modalIframe = modal.querySelector('.donor-modal-iframe');
    const closeModalBtn = modal.querySelector('.donor-modal-close');
    const fallbackDiv = modal.querySelector('.modal-fallback');
    const modalContent = modal.querySelector('.donor-modal-content');

    // --- Modal Open/Close Functions ---
    function openDonorModal(title, url) {
        modalHeader.textContent = title;
        modalIframe.src = url;
        modalIframe.style.display = '';
        fallbackDiv.style.display = 'none';
        fallbackDiv.innerHTML = '';
        modal.style.display = 'flex';
        document.body.style.overflow = 'hidden';

        // Fallback: show external link if iframe does not load after 2.2 seconds
        setTimeout(function() {
            // Check if modal is still open and iframe hasn't been interacted with
            if (modal.style.display === 'flex') {
                // Try to detect blank iframe (some browsers block access to contents)
                // If you want to be more robust, always show fallback for known domains
                modalIframe.style.display = 'none';
                fallbackDiv.style.display = 'block';
                fallbackDiv.innerHTML = `
                    <p>Sorry, this website does not allow preview inside other sites.</p>
                    <a href="${url}" target="_blank" class="visit-in-new-tab">Open in New Tab</a>
                `;
            }
        }, 2200);

        // Optional: clear fallback if iframe loads successfully
        modalIframe.onload = function() {
            // Some sites may still block, but if iframe loads, show it
            fallbackDiv.style.display = 'none';
            modalIframe.style.display = '';
        };
        // Optional: show fallback immediately if iframe errors
        modalIframe.onerror = function() {
            modalIframe.style.display = 'none';
            fallbackDiv.style.display = 'block';
            fallbackDiv.innerHTML = `
                <p>Sorry, this website does not allow preview inside other sites.</p>
                <a href="${url}" target="_blank" class="visit-in-new-tab">Open in New Tab</a>
            `;
        };
    }

    function closeDonorModal() {
        modal.style.display = 'none';
        modalIframe.src = '';
        fallbackDiv.style.display = 'none';
        fallbackDiv.innerHTML = '';
        document.body.style.overflow = '';
    }

    // --- Modal Close Listeners ---
    closeModalBtn.addEventListener('click', closeDonorModal);
    modal.addEventListener('click', function(e) {
        if (e.target === modal) closeDonorModal();
    });
    document.addEventListener('keydown', function(e) {
        if (modal.style.display === 'flex' && (e.key === "Escape" || e.keyCode === 27)) {
            closeDonorModal();
        }
    });

    // --- Listen for Donor Preview Link Clicks ---
    document.body.addEventListener('click', function(e) {
        // For .donor-preview links (in popup or tooltip)
        if (e.target.classList.contains('donor-preview') || e.target.classList.contains('donor-tooltip-visit')) {
            e.preventDefault();
            const title = e.target.dataset.previewTitle || e.target.textContent;
            const url = e.target.dataset.previewUrl || e.target.href;
            openDonorModal(title, url);
            // Also hide any open tooltip (optional)
            if (window.donorTooltip) {
                window.donorTooltip.style.display = 'none';
            }
        }
    });
});
</script>


<script>
document.addEventListener('DOMContentLoaded', function() {
    const loginBox = document.getElementById('loginBox');
    const hideLoginBtn = document.getElementById('hideLoginBtn');
    const showLoginBtn = document.getElementById('showLoginBtn');

    hideLoginBtn.onclick = function() {
        loginBox.style.display = 'none';
        hideLoginBtn.style.display = 'none';
        showLoginBtn.style.display = 'inline-block';
    };
    showLoginBtn.onclick = function() {
        loginBox.style.display = 'flex'; // or 'block' depending on your CSS
        hideLoginBtn.style.display = 'inline-block';
        showLoginBtn.style.display = 'none';
    };
});
</script>

<script>
document.addEventListener('DOMContentLoaded', function() {
  // Open modal
  var showBtn = document.getElementById('showEmailBtn');
  if(showBtn){
    showBtn.onclick = function() {
      document.getElementById('email-form-container').classList.add('active');
	  document.querySelector('.content-container').classList.add('fade-blur'); //latest
    };
  }
  // Close modal
  document.getElementById('hideEmailBtn').onclick = closeModal;

  // Click outside form closes modal
  document.getElementById('email-form-container').addEventListener('click', function(e){
    if(e.target === this) closeModal();
  });

  function closeModal() {
    document.getElementById('email-form-container').classList.remove('active');
	document.querySelector('.content-container').classList.remove('fade-blur');
    setTimeout(function(){
      document.getElementById('emailMsg').textContent = '';
      document.getElementById('emailForm').reset();
    }, 300);
  }

  // AJAX form send
  document.getElementById('emailForm').onsubmit = function(e) {
    e.preventDefault();
    var formData = new FormData(this);
    fetch('send_email.php', {
      method: 'POST',
      body: formData
    })
    .then(response => response.text())
    .then(result => {
      if(result.trim() === "success") {
        document.getElementById('emailMsg').textContent =
          "Thank you for contacting us! If your email address is valid, we will respond to you shortly. We appreciate your interest and your visit to our website. You may now close this form. Thank you.";
		  
  // Show balloon
  var balloon = document.getElementById('successBalloon');
  if(balloon){
    balloon.classList.add('show');
    setTimeout(function(){ balloon.classList.remove('show'); }, 4000);
  }

  // Show splash
  var splash = document.getElementById('splashThankYou');
  if(splash){
    splash.classList.add('show');
    setTimeout(function(){ splash.classList.remove('show'); }, 4000);
  }

  setTimeout(closeModal, 8000); // Auto-close after 6 sec
      } else if(result.trim() === "fail") {
        document.getElementById('emailMsg').textContent =
          "Sorry, your message could not be sent. Please try again later.";
      } else if(result.trim() === "invalid") {
        document.getElementById('emailMsg').textContent =
          "Please fill out all fields correctly.";
      } else {
        document.getElementById('emailMsg').textContent = result;
      }
    });
  };
});
</script>

<script>
document.getElementById('openPortfolioBtn').onclick = function() {
    var modal = document.getElementById('portfolioModal');
    var content = document.getElementById('portfolioContent');
    modal.style.display = 'flex';
    content.innerHTML = '<div style="text-align:center;padding:40px;">Loading projects...</div>';
    fetch('portfolio_content.php')
        .then(res => res.text())
        .then(html => {
            content.innerHTML = html;
        })
        .catch(() => {
            content.innerHTML = '<div style="text-align:center;padding:40px;color:#d32f2f;">Failed to load portfolio.</div>';
        });
    // Optional: blur background if you like
    document.body.classList.add('fade-blur');
};
// Close modal
document.getElementById('closePortfolioBtn').onclick = function() {
    document.getElementById('portfolioModal').style.display = 'none';
    document.body.classList.remove('fade-blur');
};
// Click outside modal to close
document.getElementById('portfolioModal').onclick = function(e) {
    if(e.target === this) {
        this.style.display = 'none';
        document.body.classList.remove('fade-blur');
    }
};
// ESC closes modal
document.addEventListener('keydown', function(e){
    if(e.key === "Escape" || e.keyCode === 27) {
        document.getElementById('portfolioModal').style.display = 'none';
        document.body.classList.remove('fade-blur');
    }
});
</script>




<div id="chatWaver" style="
  position: fixed;
  bottom: 80px;
  right: 20px;
  z-index: 9999;
">
  <a href="https://m.me/MCILSamoa" target="_blank" id="chatBtn" style="
    display: flex;
    align-items: center;
    justify-content: center;
    background: #0084FF;
    color: #fff;
    padding: 10px 16px;
    border-radius: 8px;
    text-decoration: none;
    font-weight: 500;
    font-size: 14px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.2);
    transition: transform 0.3s ease;
  ">
    💬 Chat with our team
  </a>
</div>


<script>
let ticking = false;
window.addEventListener('scroll', () => {
  if (!ticking) {
    window.requestAnimationFrame(() => {
      const chatBtn = document.getElementById('chatBtn');
      if (chatBtn) {
        chatBtn.style.transform = 'rotate(5deg) scale(1.05)';
        setTimeout(() => {
          chatBtn.style.transform = 'rotate(-5deg) scale(1.05)';
        }, 100);
        setTimeout(() => {
          chatBtn.style.transform = 'rotate(0deg) scale(1)';
        }, 200);
      }
      ticking = false;
    });
    ticking = true;
  }
});
