/* =========================================================
   🛡️ ZA-FARM-KH — Client-Side Security
   ========================================================= */

// ── Prevent right-click context menu (deters casual source viewing)
document.addEventListener('contextmenu', function(e) { e.preventDefault(); });

// ── Block keyboard shortcuts for DevTools / View Source
document.addEventListener('keydown', function(e) {
  // F12
  if (e.key === 'F12') { e.preventDefault(); return false; }
  // Ctrl+Shift+I (DevTools)
  if (e.ctrlKey && e.shiftKey && (e.key === 'I' || e.key === 'i')) { e.preventDefault(); return false; }
  // Ctrl+Shift+J (Console)
  if (e.ctrlKey && e.shiftKey && (e.key === 'J' || e.key === 'j')) { e.preventDefault(); return false; }
  // Ctrl+U (View Source)
  if (e.ctrlKey && (e.key === 'U' || e.key === 'u')) { e.preventDefault(); return false; }
  // Ctrl+S (Save page)
  if (e.ctrlKey && (e.key === 'S' || e.key === 's')) { e.preventDefault(); return false; }
});

// ── Detect DevTools open (basic detection)
(function() {
  let devtoolsOpen = false;
  const threshold = 160;
  
  function check() {
    const widthThreshold = window.outerWidth - window.innerWidth > threshold;
    const heightThreshold = window.outerHeight - window.innerHeight > threshold;
    if (widthThreshold || heightThreshold) {
      if (!devtoolsOpen) {
        devtoolsOpen = true;
        console.clear();
        console.log('%c⚠️ Security Warning', 'color:red;font-size:24px;font-weight:bold;');
        console.log('%cការប្រើ DevTools ត្រូវបានកត់ត្រា។', 'color:orange;font-size:14px;');
      }
    } else {
      devtoolsOpen = false;
    }
  }
  
  setInterval(check, 1000);
})();

// ── Prevent drag (stops dragging images/links to reveal URLs)
document.addEventListener('dragstart', function(e) { e.preventDefault(); });

// ── Token expiry auto-logout
(function() {
  const token = localStorage.getItem('zafarm_token');
  if (token) {
    try {
      const payload = JSON.parse(atob(token.split('.')[1]));
      if (payload.exp * 1000 < Date.now()) {
        localStorage.removeItem('zafarm_token');
        localStorage.removeItem('zafarm_user');
        if (!window.location.pathname.includes('login') && !window.location.pathname.includes('register') && !window.location.pathname.includes('forgot') && !window.location.pathname.includes('reset')) {
          window.location.href = '/login';
        }
      }
    } catch(e) {
      localStorage.removeItem('zafarm_token');
      localStorage.removeItem('zafarm_user');
    }
  }
})();
