/* PROJECTPT — site runtime
   - boot sequence (type-out, skippable)
   - hash routing between sections
   - file viewer (fetch + numbered lines)
   - model tabs, secrets mask toggle
*/

(function () {
  'use strict';

  /* ---------- boot overlay ---------- */
  var boot = document.getElementById('boot');
  var lines = [
    '> run projectpt.sys',
    '> load core.module .......... 100%',
    '> mount /northgate_v2 ....... OK',
    '> 8 runs | 18 incidents | 5 proofs',
    '> access granted'
  ];
  function runBoot() {
    if (sessionStorage.getItem('ppt_booted')) { boot.style.display = 'none'; return; }
    var inner = boot.querySelector('.boot-inner');
    var li = 0;
    function typeLine() {
      if (li >= lines.length) { finish(); return; }
      var el = document.createElement('div');
      el.className = 'bl';
      inner.appendChild(el);
      var txt = lines[li], ci = 0;
      var cur = document.createElement('span');
      cur.className = 'cursor';
      el.appendChild(cur);
      var iv = setInterval(function () {
        if (ci < txt.length) {
          cur.insertAdjacentText('beforebegin', txt[ci++]);
        } else {
          clearInterval(iv);
          cur.remove();
          li++;
          setTimeout(typeLine, 90);
        }
      }, 14);
    }
    function finish() {
      setTimeout(function () {
        boot.style.transition = 'opacity .4s';
        boot.style.opacity = '0';
        setTimeout(function () { boot.style.display = 'none'; }, 420);
        sessionStorage.setItem('ppt_booted', '1');
      }, 380);
    }
    boot.addEventListener('click', function () { sessionStorage.setItem('ppt_booted', '1'); boot.style.display = 'none'; });
    typeLine();
  }

  /* ---------- hash routing ---------- */
  var pages = document.querySelectorAll('section.page');
  var links = document.querySelectorAll('#side nav a');
  function route() {
    var h = (location.hash || '#obzor').slice(1);
    var found = false;
    pages.forEach(function (p) {
      var on = p.id === h;
      p.classList.toggle('on', on);
      if (on) found = true;
    });
    if (!found) {
      pages[0].classList.add('on');
      h = pages[0].id;
    }
    links.forEach(function (a) {
      a.classList.toggle('active', a.getAttribute('href') === '#' + h);
    });
    window.scrollTo(0, 0);
  }
  window.addEventListener('hashchange', route);

  /* ---------- file viewer ---------- */
  var viewer = document.getElementById('viewer');
  var vwTitle = viewer.querySelector('.vw-head .t');
  var vwPre = viewer.querySelector('pre');
  window.viewFile = function (path, title) {
    vwTitle.textContent = '> ' + (title || path);
    vwPre.innerHTML = '<span class="dim">loading...</span>';
    viewer.style.display = 'block';
    document.body.style.overflow = 'hidden';
    fetch(path).then(function (r) {
      if (!r.ok) throw new Error('HTTP ' + r.status);
      return r.text();
    }).then(function (txt) {
      var esc = txt.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
      vwPre.innerHTML = esc.split('\n').map(function (l) { return '<span class="vl">' + (l || ' ') + '</span>'; }).join('');
    }).catch(function (e) {
      vwPre.textContent = 'error: ' + e.message;
    });
  };
  window.closeViewer = function () {
    viewer.style.display = 'none';
    document.body.style.overflow = '';
  };
  viewer.addEventListener('click', function (e) { if (e.target === viewer) closeViewer(); });
  document.addEventListener('keydown', function (e) { if (e.key === 'Escape') closeViewer(); });

  /* ---------- model tabs ---------- */
  window.mtab = function (btn) {
    var group = btn.closest('.models');
    group.querySelectorAll('.mtabs button').forEach(function (b) { b.classList.remove('on'); });
    group.querySelectorAll('.mpane').forEach(function (p) { p.classList.remove('on'); });
    btn.classList.add('on');
    document.getElementById(btn.dataset.pane).classList.add('on');
  };

  /* ---------- secrets mask ---------- */
  window.toggleSecrets = function (btn) {
    document.querySelectorAll('.secrets').forEach(function (t) { t.classList.toggle('masked'); });
    var masked = document.querySelector('.secrets').classList.contains('masked');
    btn.textContent = masked ? '[ показать значения ]' : '[ скрыть значения ]';
  };

  /* ---------- scroll fade-in ---------- */
  var io = new IntersectionObserver(function (entries) {
    entries.forEach(function (en) {
      if (en.isIntersecting) {
        en.target.style.opacity = '1';
        en.target.style.transform = 'none';
        io.unobserve(en.target);
      }
    });
  }, { threshold: .06 });
  document.querySelectorAll('.runcard, .inc, .file').forEach(function (el) {
    el.style.opacity = '0';
    el.style.transform = 'translateY(8px)';
    el.style.transition = 'opacity .4s ease, transform .4s ease';
    io.observe(el);
  });

  route();
  runBoot();
})();
