let wakeLock = null;
let wakeLockActive = false;

const requestWakeLock = async () => {
  if ('wakeLock' in navigator && !wakeLockActive) {
    try {
      wakeLock = await navigator.wakeLock.request('screen');
      wakeLockActive = true;
      console.log('Screen Wake Lock activated.');

      wakeLock.addEventListener('release', () => {
        console.log('Screen Wake Lock was released.');
        wakeLockActive = false;
        wakeLock = null; // Clear the reference
        // Optionally, re-request if it was released unexpectedly and should be active
        // For now, we'll let it be re-requested manually by the app logic
      });
    } catch (err) {
      console.error(`Failed to acquire Screen Wake Lock: ${err.name}, ${err.message}`);
      wakeLock = null;
      wakeLockActive = false;
    }
  } else {
    console.warn('Screen Wake Lock API not supported or already active.');
  }
};

const releaseWakeLock = async () => {
  if (wakeLock && wakeLockActive) {
    try {
      await wakeLock.release();
      // The 'release' event listener on wakeLock itself will set wakeLockActive = false and wakeLock = null
    } catch (err) {
      console.error(`Failed to release Screen Wake Lock: ${err.name}, ${err.message}`);
      // Even if release fails, mark as inactive to allow re-request
      wakeLock = null;
      wakeLockActive = false;
    }
  } else {
    // console.log('No active Screen Wake Lock to release or already released.');
  }
};

// Handle visibility changes to re-acquire lock if necessary
const handleVisibilityChange = () => {
  if (wakeLock !== null && document.visibilityState === 'visible') {
    // If we had a wake lock and the page became visible again,
    // it might have been released by the browser. Try to re-acquire.
    // This behavior is usually handled automatically by the browser with the 'release' event
    // but can be a fallback. For now, we rely on manual re-request.
    // console.log('Page visible, checking wake lock status.');
  } else if (document.visibilityState === 'hidden' && wakeLockActive) {
      // The browser usually releases the wake lock when tab is hidden.
      // Our 'release' event listener should handle this.
  }
};

document.addEventListener('visibilitychange', handleVisibilityChange);
// document.addEventListener('fullscreenchange', handleVisibilityChange); // Also useful for fullscreen

export const WakeLockService = {
  request: requestWakeLock,
  release: releaseWakeLock,
  isActive: () => wakeLockActive,
};