/* ============================================================================
   Dabil — Splash / Loading Experience (behaviour)
   ----------------------------------------------------------------------------
   Two jobs, kept deliberately small:
     1. Scatter a few ambient "motes" of light (Phase 5).
     2. Hold the splash for a graceful minimum, then dissolve it and move on
        to the destination the server decided (Phase 6).

   No timers race the user: navigation waits for BOTH a minimum on-screen time
   (so the animation is never cut off) AND the window 'load' event (so we don't
   dissolve before the next page is ready to be reached).

   Configuration is read from data-* attributes on <div class="dabil-splash">,
   which keeps the markup/PHP and the logic cleanly separated.
   ============================================================================ */
(function () {
  'use strict';

  var stage = document.querySelector('.dabil-splash');
  if (!stage) return;

  var prefersReduced =
    window.matchMedia &&
    window.matchMedia('(prefers-reduced-motion: reduce)').matches;

  /* --- Config (with sensible defaults) ----------------------------------- */
  var target  = stage.getAttribute('data-target') || '';   // where to go next
  var minHold = parseInt(stage.getAttribute('data-min-hold'), 10);
  if (isNaN(minHold)) minHold = 2300;                       // ms on screen min
  var fadeOut = 600;                                        // matches CSS .6s

  /* ------------------------------------------------------------------------
     1. Ambient particles. Few, small, low-opacity — dust in sunlight.
        Skipped entirely under reduced-motion (CSS hides movement anyway).
  ------------------------------------------------------------------------ */
  function buildParticles() {
    var layer = stage.querySelector('.dabil-particles');
    if (!layer || prefersReduced) return;

    // Scale count to viewport so phones stay light; cap for calm restraint.
    var count = Math.min(16, Math.round(window.innerWidth / 90));

    var frag = document.createDocumentFragment();
    for (var i = 0; i < count; i++) {
      var mote = document.createElement('span');
      mote.className = 'dabil-mote';

      var size = (rand(1.5, 4)).toFixed(2);
      mote.style.setProperty('--x',        rand(2, 98).toFixed(2) + 'vw');
      mote.style.setProperty('--y',        rand(2, 98).toFixed(2) + 'vh');
      mote.style.setProperty('--size',     size + 'px');
      mote.style.setProperty('--opacity',  rand(.15, .5).toFixed(2));
      mote.style.setProperty('--drift-x',  rand(-26, 26).toFixed(1) + 'px');
      mote.style.setProperty('--drift-y',  rand(-44, -14).toFixed(1) + 'px');
      mote.style.setProperty('--duration', rand(7, 13).toFixed(1) + 's');
      mote.style.setProperty('--delay',    rand(0, 4).toFixed(1) + 's');

      frag.appendChild(mote);
    }
    layer.appendChild(frag);
  }

  function rand(min, max) { return Math.random() * (max - min) + min; }

  /* ------------------------------------------------------------------------
     2. Dissolve + navigate. Fire only after the minimum hold AND window load.
  ------------------------------------------------------------------------ */
  var startedAt = Date.now();
  var navigated = false;

  function dissolveAndGo() {
    if (navigated) return;
    navigated = true;

    stage.classList.add('is-dismissed');     // triggers the CSS fade

    // Let the dissolve finish before changing the document.
    window.setTimeout(function () {
      if (target) window.location.href = target;
    }, fadeOut);
  }

  function scheduleExit() {
    var elapsed   = Date.now() - startedAt;
    var remaining = Math.max(0, minHold - elapsed);
    window.setTimeout(dissolveAndGo, remaining);
  }

  /* --- Boot -------------------------------------------------------------- */
  buildParticles();

  if (document.readyState === 'complete') {
    scheduleExit();
  } else {
    window.addEventListener('load', scheduleExit);
    // Safety net: never strand the user if 'load' is unusually slow.
    window.setTimeout(scheduleExit, minHold + 4000);
  }
})();
