// BS1 — Blind Screen Free v1.2 (qualified free_forever)
// Pure vanilla. No libs. No network after install.
// Storage/cache scoped to v1.2.

var STORAGE_PREFIX = 'bs1_v1_2::';
var LS_LANG = STORAGE_PREFIX + 'lang';
var VERSION = '1.2.0';
var SHORT_CODE = 'BS1';

var lang = 'en';
var overlayEl = null;
var statusEl = null;
var autoTimer = null;
var wakeLock = null;
var isBlind = false;
var blindMode = null; // null | 30 | 300

var STRINGS = {
  en: {
    title: 'BLIND SCREEN',
    tag: 'FREE FOREVER',
    btnOpen: 'OPEN',
    btnClose: 'CLOSE',
    btn30: '30 SEC',
    btn5: '5 MIN',
    hint: 'B / SPACE = open • ESC = close • Tap overlay to close',
    ready: 'Ready — screen visible',
    blindManual: 'BLIND — manual (tap or ESC to close)',
    blind30: 'BLIND — auto close in 30s',
    blind5m: 'BLIND — auto close in 5m',
    overlayLabel: 'BLIND',
    pageTitle: 'Blind Screen Free',
    ariaOpen: 'Open blind',
    ariaClose: 'Close blind',
    aria30: 'Open blind for 30 seconds',
    aria5: 'Open blind for 5 minutes',
    ariaOverlay: 'Blind overlay — tap or press Escape to close',
    ariaLang: 'Language'
  },
  es: {
    title: 'PANTALLA CIEGA',
    tag: 'GRATIS PARA SIEMPRE',
    btnOpen: 'ABRIR',
    btnClose: 'CERRAR',
    btn30: '30 SEG',
    btn5: '5 MIN',
    hint: 'B / ESPACIO = abrir • ESC = cerrar • Toca la cubierta para cerrar',
    ready: 'Listo — pantalla visible',
    blindManual: 'CIEGA — manual (toca o ESC para cerrar)',
    blind30: 'CIEGA — cierre auto en 30s',
    blind5m: 'CIEGA — cierre auto en 5m',
    overlayLabel: 'CIEGA',
    pageTitle: 'Pantalla Ciega Gratis',
    ariaOpen: 'Abrir pantalla ciega',
    ariaClose: 'Cerrar pantalla ciega',
    aria30: 'Abrir por 30 segundos',
    aria5: 'Abrir por 5 minutos',
    ariaOverlay: 'Cubierta ciega — toca o pulsa Escape para cerrar',
    ariaLang: 'Idioma'
  }
};

function t(key) {
  var pack = STRINGS[lang] || STRINGS.en;
  return pack[key] != null ? pack[key] : (STRINGS.en[key] || key);
}

function sanitizeLang(code) {
  if (code === 'es' || code === 'en') return code;
  return 'en';
}

function init() {
  overlayEl = document.getElementById('overlay');
  statusEl = document.getElementById('status');

  try {
    var saved = localStorage.getItem(LS_LANG);
    lang = sanitizeLang(saved);
  } catch (e) {
    lang = 'en';
  }

  bind('btn-open', function () { openBlind(null); });
  bind('btn-close', closeBlind);
  bind('btn-30', function () { openBlind(30); });
  bind('btn-5', function () { openBlind(300); });

  if (overlayEl) {
    overlayEl.addEventListener('click', closeBlind);
    overlayEl.addEventListener('keydown', function (e) {
      if (e.key === 'Escape' || e.key === 'Enter' || e.key === ' ') {
        e.preventDefault();
        closeBlind();
      }
    });
  }

  bind('lang-en', function () { setLang('en'); });
  bind('lang-es', function () { setLang('es'); });

  document.addEventListener('keydown', handleHotkeys);
  registerServiceWorker();
  document.addEventListener('visibilitychange', handleVisibility);

  applyLabels();
  if (isBlind) refreshBlindStatus();
  else updateStatus(t('ready'));
}

function bind(id, fn) {
  var el = document.getElementById(id);
  if (el) el.addEventListener('click', fn);
}

function setLang(code) {
  lang = sanitizeLang(code);
  try {
    localStorage.setItem(LS_LANG, lang);
  } catch (e) {}
  applyLabels();
  if (isBlind) refreshBlindStatus();
  else updateStatus(t('ready'));
  return lang;
}

function applyLabels() {
  document.documentElement.lang = lang;
  document.title = t('pageTitle');

  setText('lbl-title', t('title'));
  setText('lbl-tag', t('tag'));
  setText('lbl-hint', t('hint'));
  setText('btn-open', t('btnOpen'));
  setText('btn-close', t('btnClose'));
  setText('btn-30', t('btn30'));
  setText('btn-5', t('btn5'));

  setAria('btn-open', t('ariaOpen'));
  setAria('btn-close', t('ariaClose'));
  setAria('btn-30', t('aria30'));
  setAria('btn-5', t('aria5'));

  if (overlayEl) {
    overlayEl.setAttribute('data-label', t('overlayLabel'));
    overlayEl.setAttribute('aria-label', t('ariaOverlay'));
  }

  var langGroup = document.querySelector('.lang-toggle');
  if (langGroup) langGroup.setAttribute('aria-label', t('ariaLang'));

  var enBtn = document.getElementById('lang-en');
  var esBtn = document.getElementById('lang-es');
  if (enBtn) {
    enBtn.className = 'lang-btn' + (lang === 'en' ? ' lang-btn--on' : '');
    enBtn.setAttribute('aria-pressed', lang === 'en' ? 'true' : 'false');
  }
  if (esBtn) {
    esBtn.className = 'lang-btn' + (lang === 'es' ? ' lang-btn--on' : '');
    esBtn.setAttribute('aria-pressed', lang === 'es' ? 'true' : 'false');
  }
}

function setText(id, value) {
  var el = document.getElementById(id);
  if (el) el.textContent = value;
}

function setAria(id, value) {
  var el = document.getElementById(id);
  if (el) el.setAttribute('aria-label', value);
}

function handleHotkeys(e) {
  var tag = (e.target && e.target.tagName) || '';
  if (tag === 'INPUT' || tag === 'TEXTAREA') return;

  var key = e.key ? e.key.toLowerCase() : '';

  if (key === 'b' || e.key === ' ') {
    e.preventDefault();
    if (isBlind) closeBlind();
    else openBlind(null);
  }

  if (e.key === 'Escape') {
    closeBlind();
  }
}

function handleVisibility() {
  if (!isBlind) return;
  if (wakeLock && document.visibilityState === 'visible') {
    requestWakeLock();
  }
}

function updateStatus(text) {
  if (statusEl) statusEl.textContent = String(text == null ? '' : text);
}

function refreshBlindStatus() {
  if (!isBlind) {
    updateStatus(t('ready'));
    return;
  }
  if (blindMode === 30) updateStatus(t('blind30'));
  else if (blindMode === 300) updateStatus(t('blind5m'));
  else updateStatus(t('blindManual'));
}

function openBlind(seconds) {
  if (!overlayEl) return false;

  var mode = null;
  if (seconds === 30 || seconds === 300) mode = seconds;
  else if (seconds != null && seconds !== undefined) {
    // reject invalid timer values; open manual instead of inventing behavior
    mode = null;
  }

  overlayEl.style.display = 'block';
  overlayEl.classList.add('is-open');
  overlayEl.removeAttribute('hidden');
  isBlind = true;
  blindMode = mode;

  clearAutoTimer();

  if (mode) {
    refreshBlindStatus();
    startAutoTimer(mode * 1000);
  } else {
    refreshBlindStatus();
  }

  requestFullscreen();
  requestWakeLock();
  return true;
}

function closeBlind() {
  if (!overlayEl) return false;

  overlayEl.style.display = 'none';
  overlayEl.classList.remove('is-open');
  overlayEl.setAttribute('hidden', '');
  isBlind = false;
  blindMode = null;

  clearAutoTimer();
  releaseWakeLock();
  exitFullscreenGraceful();

  updateStatus(t('ready'));
  return true;
}

function startAutoTimer(ms) {
  clearAutoTimer();
  if (typeof ms !== 'number' || !(ms > 0) || ms > 3600000) return;
  autoTimer = setTimeout(function () {
    closeBlind();
  }, ms);
}

function clearAutoTimer() {
  if (autoTimer) {
    clearTimeout(autoTimer);
    autoTimer = null;
  }
}

function requestFullscreen() {
  try {
    var docEl = document.documentElement;
    if (docEl.requestFullscreen) {
      docEl.requestFullscreen().catch(function () {});
    } else if (docEl.webkitRequestFullscreen) {
      docEl.webkitRequestFullscreen();
    }
  } catch (e) { /* best-effort */ }
}

function exitFullscreenGraceful() {
  try {
    if (document.fullscreenElement || document.webkitFullscreenElement) {
      if (document.exitFullscreen) {
        document.exitFullscreen().catch(function () {});
      } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen();
      }
    }
  } catch (e) { /* best-effort */ }
}

async function requestWakeLock() {
  try {
    if ('wakeLock' in navigator && navigator.wakeLock) {
      wakeLock = await navigator.wakeLock.request('screen');
    }
  } catch (e) {
    // overlay still works without wake lock
  }
}

function releaseWakeLock() {
  if (wakeLock) {
    try { wakeLock.release(); } catch (e) {}
    wakeLock = null;
  }
}

function registerServiceWorker() {
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('sw.js').catch(function () {});
  }
}

/** Read-only snapshot for tests / diagnostics (no secrets). */
function getState() {
  return {
    version: VERSION,
    shortCode: SHORT_CODE,
    lang: lang,
    isBlind: isBlind,
    blindMode: blindMode,
    hasTimer: !!autoTimer,
    storagePrefix: STORAGE_PREFIX
  };
}

window.BS = {
  openBlind: openBlind,
  closeBlind: closeBlind,
  setLang: setLang,
  getState: getState,
  t: t,
  VERSION: VERSION,
  SHORT_CODE: SHORT_CODE
};

window.addEventListener('load', init);
