/**
 * fleet-flyover.js — Supernova 2.0
 * When the hero countdown hits zero, a fleet of 9 ships (one per event)
 * flies across the viewport in 3 staggered waves.
 *
 * - Fires once on the live zero-crossing of the countdown.
 * - Visitors who load the page after the fest has started see it once
 *   per browser session (sessionStorage flag).
 * - Manual test hook: window.launchFleet() — optional arg slows it down,
 *   e.g. launchFleet(2) = half speed.
 *
 * The ship sprite is currently an inline SVG placeholder. To use the real
 * artwork, drop a TRANSPARENT png at assets/img/spaceship.png and set
 * SHIP_IMG below — the code automatically prefers it when present.
 */
(function () {
    'use strict';

    // Same target as home.js countdown
    var TARGET = new Date('2026-09-04T09:00:00+05:30').getTime();
    var SESSION_KEY = 'snFleetPlayed';

    // Set to the real artwork path once a transparent PNG exists, or null for the SVG placeholder.
    var SHIP_IMG = null; // e.g. 'assets/img/spaceship.png'

    // Placeholder sprite: top-down silver ship pointing RIGHT (offset-rotate needs nose = +x axis)
    var SHIP_SVG =
        '<svg viewBox="0 0 140 100" xmlns="http://www.w3.org/2000/svg">' +
        '<defs><radialGradient id="snHull" cx="45%" cy="40%" r="70%">' +
        '<stop offset="0%" stop-color="#f8fafc"/><stop offset="55%" stop-color="#cbd5e1"/>' +
        '<stop offset="100%" stop-color="#64748b"/></radialGradient></defs>' +
        // engine exhaust (back / left)
        '<rect x="4" y="36" width="12" height="28" rx="6" fill="#22d3ee" opacity="0.95"/>' +
        '<rect x="0" y="42" width="8" height="16" rx="4" fill="#a5f3fc" opacity="0.8"/>' +
        // front mandibles (right)
        '<path d="M84 24 L130 15 L136 24 L94 36 Z" fill="url(#snHull)" stroke="#475569" stroke-width="1.2"/>' +
        '<path d="M84 76 L130 85 L136 76 L94 64 Z" fill="url(#snHull)" stroke="#475569" stroke-width="1.2"/>' +
        // main saucer hull
        '<circle cx="56" cy="50" r="42" fill="url(#snHull)" stroke="#475569" stroke-width="1.5"/>' +
        // panel detail
        '<circle cx="56" cy="50" r="29" fill="none" stroke="#64748b" stroke-width="0.8" opacity="0.7"/>' +
        '<line x1="56" y1="8"  x2="56" y2="21" stroke="#64748b" stroke-width="0.8" opacity="0.6"/>' +
        '<line x1="56" y1="79" x2="56" y2="92" stroke="#64748b" stroke-width="0.8" opacity="0.6"/>' +
        '<line x1="14" y1="50" x2="27" y2="50" stroke="#64748b" stroke-width="0.8" opacity="0.6"/>' +
        // red accent stripes
        '<path d="M40 12 a42 42 0 0 1 32 0" stroke="#dc2626" stroke-width="3.5" fill="none" stroke-linecap="round"/>' +
        '<path d="M40 88 a42 42 0 0 0 32 0" stroke="#dc2626" stroke-width="3.5" fill="none" stroke-linecap="round"/>' +
        // centre dish
        '<circle cx="56" cy="50" r="12" fill="#94a3b8" stroke="#475569" stroke-width="1"/>' +
        '<circle cx="56" cy="50" r="5" fill="#334155"/>' +
        // side cockpit tube (lower-front, Falcon style)
        '<rect x="72" y="58" width="28" height="11" rx="5.5" fill="url(#snHull)" stroke="#475569" stroke-width="1"/>' +
        '<circle cx="100" cy="63.5" r="6.5" fill="#0f172a" stroke="#94a3b8" stroke-width="1.2"/>' +
        '</svg>';

    // ── styles ────────────────────────────────────────────────────────────
    var style = document.createElement('style');
    style.textContent =
        '.sn-fleet-overlay{position:fixed;inset:0;z-index:9990;pointer-events:none;overflow:hidden;}' +
        '.sn-fleet-ship{position:absolute;top:0;left:0;offset-rotate:auto;offset-distance:0%;' +
            'will-change:offset-distance;animation:sn-fleet-fly linear forwards;' +
            'filter:drop-shadow(0 0 4px rgba(34,211,238,.8)) drop-shadow(0 0 16px rgba(34,211,238,.45));}' +
        '.sn-fleet-ship svg,.sn-fleet-ship img{display:block;width:100%;height:auto;' +
            'animation:sn-fleet-rock 1.7s ease-in-out infinite alternate;}' +
        '@keyframes sn-fleet-fly{from{offset-distance:0%}to{offset-distance:100%}}' +
        '@keyframes sn-fleet-rock{from{transform:rotate(-4deg)}to{transform:rotate(4deg)}}' +
        '@media (prefers-reduced-motion:reduce){.sn-fleet-overlay{display:none}}';
    document.head.appendChild(style);

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

    /** Curved bezier flight path across the viewport (ltr = left→right). */
    function buildPath(ltr, vw, vh) {
        var m = 260; // off-screen margin so ships spawn/exit invisibly
        var y0 = rand(vh * 0.06, vh * 0.62);
        var y1 = rand(vh * 0.06, vh * 0.68);
        var c1 = rand(vh * 0.02, vh * 0.75);
        var c2 = rand(vh * 0.02, vh * 0.75);
        if (ltr) {
            return 'M ' + (-m) + ' ' + y0 +
                   ' C ' + (vw * 0.33) + ' ' + c1 + ', ' + (vw * 0.66) + ' ' + c2 +
                   ', ' + (vw + m) + ' ' + y1;
        }
        return 'M ' + (vw + m) + ' ' + y0 +
               ' C ' + (vw * 0.66) + ' ' + c1 + ', ' + (vw * 0.33) + ' ' + c2 +
               ', ' + (-m) + ' ' + y1;
    }

    // ── the fleet ─────────────────────────────────────────────────────────
    function launchFleet(slowdown) {
        slowdown = slowdown || 1;
        var vw = window.innerWidth, vh = window.innerHeight;

        var overlay = document.createElement('div');
        overlay.className = 'sn-fleet-overlay';
        document.body.appendChild(overlay);

        var alive = 0;
        for (var i = 0; i < 9; i++) {
            var wave = Math.floor(i / 3);                 // 3 waves of 3
            var scale = rand(0.35, 1);                    // depth: size…
            var dur = (5.5 / (0.45 + scale)) * slowdown;  // …and speed (closer = faster)
            var ltr = Math.random() > 0.22;               // mostly left→right

            var ship = document.createElement('div');
            ship.className = 'sn-fleet-ship';
            ship.style.width = Math.round(150 * scale) + 'px';
            ship.style.opacity = String(0.55 + scale * 0.45); // distant = fainter
            ship.style.offsetPath = 'path("' + buildPath(ltr, vw, vh) + '")';
            ship.style.animationDuration = dur.toFixed(2) + 's';
            ship.style.animationDelay = (wave * 1.35 + rand(0, 0.9)).toFixed(2) + 's';

            if (SHIP_IMG) {
                var img = document.createElement('img');
                img.src = SHIP_IMG;
                img.alt = '';
                ship.appendChild(img);
            } else {
                ship.innerHTML = SHIP_SVG;
            }

            alive++;
            ship.addEventListener('animationend', function () {
                this.remove();
                if (--alive === 0) overlay.remove();
            });
            overlay.appendChild(ship);
        }
    }

    // ── triggers ──────────────────────────────────────────────────────────
    window.launchFleet = launchFleet;

    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;

    if (TARGET - Date.now() <= 0) {
        // Arrived after liftoff: play once per session
        if (!sessionStorage.getItem(SESSION_KEY)) {
            sessionStorage.setItem(SESSION_KEY, '1');
            setTimeout(function () { launchFleet(); }, 1200);
        }
    } else {
        // Watch for the live zero-crossing
        var watcher = setInterval(function () {
            if (TARGET - Date.now() <= 0) {
                clearInterval(watcher);
                sessionStorage.setItem(SESSION_KEY, '1');
                launchFleet();
            }
        }, 1000);
    }
})();
