/* ============================================================================
   Dabil — Signature Opening (behaviour)
   ----------------------------------------------------------------------------
   1. The living NODE NETWORK — a constellation drawn on <canvas>. Nodes drift;
      links draw between near neighbours and fade with distance. This is the
      "Dabil connects things" motif, and it scales to every future industry.
   2. A few rising MOTES, generated for organic variety.
   3. EXIT — hold for a graceful minimum AND the window 'load' event, then
      dissolve and navigate to the server-decided destination.

   All config comes from data-* attributes on .dabil-splash, keeping the PHP
   and the front-end cleanly separated.
   ============================================================================ */
(function () {
  'use strict';

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

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

  var target  = stage.getAttribute('data-target') || '';
  var minHold = parseInt(stage.getAttribute('data-min-hold'), 10);
  if (isNaN(minHold)) minHold = 2600;
  var fadeOut = 700;                       /* matches CSS .7s dissolve */

  function rand(a, b) { return Math.random() * (b - a) + a; }

  /* ====================================================================
     1. NODE NETWORK
  ==================================================================== */
  function startNetwork() {
    var canvas = stage.querySelector('.dabil-network');
    if (!canvas) return;
    var ctx = canvas.getContext('2d');

    var W, H, DPR, nodes = [], LINK_DIST;

    function resize() {
      DPR = Math.min(window.devicePixelRatio || 1, 2);
      W = canvas.clientWidth;
      H = canvas.clientHeight;
      canvas.width  = Math.floor(W * DPR);
      canvas.height = Math.floor(H * DPR);
      ctx.setTransform(DPR, 0, 0, DPR, 0, 0);
      LINK_DIST = Math.max(120, Math.min(W, H) * 0.22);
    }

    function seed() {
      var count = Math.round(Math.min(34, Math.max(14, (W * H) / 26000)));
      nodes = [];
      for (var i = 0; i < count; i++) {
        nodes.push({
          x: rand(0, W), y: rand(0, H),
          vx: rand(-0.18, 0.18), vy: rand(-0.18, 0.18),
          r: rand(1.1, 2.4)
        });
      }
    }

    function step() {
      ctx.clearRect(0, 0, W, H);
      var cx = W / 2, cy = H / 2, maxR = Math.hypot(cx, cy);

      for (var i = 0; i < nodes.length; i++) {
        var n = nodes[i];
        n.x += n.vx; n.y += n.vy;
        if (n.x < 0 || n.x > W) n.vx *= -1;
        if (n.y < 0 || n.y > H) n.vy *= -1;
      }

      for (var a = 0; a < nodes.length; a++) {
        for (var b = a + 1; b < nodes.length; b++) {
          var dx = nodes[a].x - nodes[b].x;
          var dy = nodes[a].y - nodes[b].y;
          var d  = Math.hypot(dx, dy);
          if (d < LINK_DIST) {
            var mx = (nodes[a].x + nodes[b].x) / 2;
            var my = (nodes[a].y + nodes[b].y) / 2;
            var centerFade = 1 - Math.min(1, Math.hypot(mx - cx, my - cy) / maxR) * 0.5;
            var alpha = (1 - d / LINK_DIST) * 0.22 * centerFade;
            ctx.strokeStyle = 'rgba(47,128,237,' + alpha.toFixed(3) + ')';
            ctx.lineWidth = 1;
            ctx.beginPath();
            ctx.moveTo(nodes[a].x, nodes[a].y);
            ctx.lineTo(nodes[b].x, nodes[b].y);
            ctx.stroke();
          }
        }
      }

      for (var k = 0; k < nodes.length; k++) {
        var p = nodes[k];
        var fade = 1 - Math.min(1, Math.hypot(p.x - cx, p.y - cy) / maxR) * 0.4;
        ctx.beginPath();
        ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2);
        ctx.fillStyle = 'rgba(47,128,237,' + (0.5 * fade).toFixed(3) + ')';
        ctx.fill();
      }
    }

    resize();
    seed();

    if (reduced) { step(); return; }

    var raf;
    (function loop() { step(); raf = requestAnimationFrame(loop); })();

    var rt;
    window.addEventListener('resize', function () {
      clearTimeout(rt);
      rt = setTimeout(function () { resize(); seed(); }, 150);
    });

    stage.addEventListener('dabil:exit', function () {
      if (raf) cancelAnimationFrame(raf);
    });
  }

  /* ====================================================================
     2. RISING MOTES
  ==================================================================== */
  function buildMotes() {
    var layer = stage.querySelector('.dabil-motes');
    if (!layer || reduced) return;
    var count = Math.min(12, Math.round(window.innerWidth / 110));
    var frag = document.createDocumentFragment();
    for (var i = 0; i < count; i++) {
      var m = document.createElement('span');
      m.className = 'dabil-mote';
      m.style.setProperty('--x',        rand(4, 96).toFixed(2) + 'vw');
      m.style.setProperty('--y',        rand(20, 96).toFixed(2) + 'vh');
      m.style.setProperty('--size',     rand(1.5, 3.5).toFixed(2) + 'px');
      m.style.setProperty('--opacity',  rand(0.18, 0.45).toFixed(2));
      m.style.setProperty('--drift-x',  rand(-18, 18).toFixed(1) + 'px');
      m.style.setProperty('--drift-y',  rand(-60, -28).toFixed(1) + 'px');
      m.style.setProperty('--duration', rand(8, 14).toFixed(1) + 's');
      m.style.setProperty('--delay',    rand(0, 3).toFixed(1) + 's');
      frag.appendChild(m);
    }
    layer.appendChild(frag);
  }

  /* ====================================================================
     3. EXIT — dissolve, then navigate
  ==================================================================== */
  var startedAt = Date.now();
  var navigated = false;

  function dissolveAndGo() {
    if (navigated) return;
    navigated = true;
    stage.dispatchEvent(new Event('dabil:exit'));
    stage.classList.add('is-dismissed');
    window.setTimeout(function () {
      if (target) window.location.href = target;
    }, fadeOut);
  }

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

  /* --- Boot ----------------------------------------------------------- */
  startNetwork();
  buildMotes();

  if (document.readyState === 'complete') {
    scheduleExit();
  } else {
    window.addEventListener('load', scheduleExit);
    window.setTimeout(scheduleExit, minHold + 4000);
  }
})();
