{{-- Guided-tour launcher + engine. Injected on every authenticated app page via
     the get_additional_script seam. Self-contained (no external libraries). --}}
<style>
    #gt-launch{position:fixed;right:18px;bottom:18px;z-index:99990;display:flex;align-items:center;gap:8px;
        background:#0d9488;color:#fff;border:none;border-radius:999px;padding:11px 16px;font-weight:700;
        font-size:14px;cursor:pointer;box-shadow:0 6px 18px rgba(13,148,136,.4);font-family:system-ui,sans-serif}
    #gt-launch:hover{background:#0f766e}
    #gt-overlay{position:fixed;inset:0;z-index:99991;display:none}
    #gt-hole{position:absolute;border-radius:8px;box-shadow:0 0 0 9999px rgba(15,23,42,.62);
        transition:all .25s ease;pointer-events:none;outline:2px solid #0d9488}
    #gt-pop{position:absolute;max-width:360px;width:calc(100vw - 32px);background:#fff;border-radius:14px;
        box-shadow:0 12px 40px rgba(0,0,0,.35);padding:16px 16px 12px;font-family:system-ui,sans-serif;color:#0f172a}
    #gt-pop h3{margin:0 0 6px;font-size:16px}
    #gt-pop .gt-body{font-size:14px;color:#334155;line-height:1.5;max-height:40vh;overflow:auto}
    #gt-pop .gt-media{margin:10px 0 4px;border-radius:10px;overflow:hidden;background:#0f172a}
    #gt-pop .gt-media img,#gt-pop .gt-media video{display:block;width:100%;max-height:220px;object-fit:contain}
    #gt-foot{display:flex;align-items:center;justify-content:space-between;margin-top:12px;gap:8px}
    #gt-count{font-size:12px;color:#64748b}
    .gt-btn{border:none;border-radius:9px;padding:8px 14px;font-size:13px;font-weight:600;cursor:pointer}
    .gt-next{background:#0d9488;color:#fff}.gt-next:hover{background:#0f766e}
    .gt-back{background:#f1f5f9;color:#0f172a}
    #gt-skip{position:absolute;top:8px;right:10px;border:none;background:transparent;font-size:18px;color:#94a3b8;cursor:pointer}
</style>

<button id="gt-launch" type="button" title="Play the guided tour">▶ Tour</button>
<div id="gt-overlay" oncontextmenu="return false;">
    <div id="gt-hole"></div>
    <div id="gt-pop">
        <button id="gt-skip" type="button" aria-label="Close">&times;</button>
        <h3 id="gt-title"></h3>
        <div class="gt-body" id="gt-bodytext"></div>
        <div class="gt-media" id="gt-media" style="display:none"></div>
        <div id="gt-foot">
            <span id="gt-count"></span>
            <div>
                <button class="gt-btn gt-back" id="gt-back" type="button">Back</button>
                <button class="gt-btn gt-next" id="gt-next" type="button">Next</button>
            </div>
        </div>
    </div>
</div>

<script>
(function () {
    if (window.__gtLoaded) return; window.__gtLoaded = true;

    var ACTIVE_URL   = "{{ route('guidedtour.active') }}";
    var PROGRESS_URL = "{{ route('guidedtour.progress') }}";
    var CSRF = (document.querySelector('meta[name=csrf-token]') || {}).content || '';

    var flow = null, steps = [], idx = 0;
    var overlay = document.getElementById('gt-overlay');
    var hole    = document.getElementById('gt-hole');
    var pop     = document.getElementById('gt-pop');

    function api(url, opts) {
        opts = opts || {};
        opts.headers = Object.assign({'Accept':'application/json'}, opts.headers || {});
        if (opts.body) { opts.headers['Content-Type'] = 'application/json'; opts.headers['X-CSRF-TOKEN'] = CSRF; }
        return fetch(url, opts).then(function (r) { return r.json(); });
    }

    function saveProgress(step, completed) {
        try {
            api(PROGRESS_URL, { method:'POST', body: JSON.stringify({ flow_id: flow.id, last_step: step, completed: !!completed }) });
            if (completed) localStorage.setItem('gt_done_' + flow.key, '1');
        } catch (e) {}
    }

    function place(el, rect) {
        // Position the popover under the target if room, else above, else centered.
        var pw = pop.offsetWidth, ph = pop.offsetHeight, m = 12;
        var top, left;
        if (!rect) {
            top = Math.max(m, (window.innerHeight - ph) / 2);
            left = Math.max(m, (window.innerWidth - pw) / 2);
        } else {
            var below = rect.bottom + m + ph < window.innerHeight;
            top  = below ? rect.bottom + m : Math.max(m, rect.top - ph - m);
            left = Math.min(Math.max(m, rect.left), window.innerWidth - pw - m);
        }
        pop.style.top = top + 'px';
        pop.style.left = left + 'px';
    }

    function renderMedia(media) {
        var box = document.getElementById('gt-media');
        if (!media) { box.style.display = 'none'; box.innerHTML = ''; return; }
        box.style.display = 'block';
        if (media.kind === 'video') {
            box.innerHTML = '<video src="' + media.url + '" controls playsinline preload="metadata" ' +
                'controlsList="nodownload noremoteplayback" disablePictureInPicture ' +
                'oncontextmenu="return false;"></video>';
        } else {
            box.innerHTML = '<img src="' + media.url + '" alt="" draggable="false" oncontextmenu="return false;">';
        }
    }

    function showStep(i) {
        if (i < 0 || i >= steps.length) return finish(true);
        idx = i;
        var s = steps[i];

        // Multi-page: jump to the step's route and resume there after load.
        if (s.route && location.pathname.replace(/\/+$/,'') !== s.route.replace(/\/+$/,'') &&
            location.pathname.indexOf(s.route) === -1) {
            try { sessionStorage.setItem('gt_resume', JSON.stringify({ key: flow.key, i: i })); } catch (e) {}
            saveProgress(i, false);
            location.href = s.route;
            return;
        }

        document.getElementById('gt-title').textContent = s.title || '';
        document.getElementById('gt-bodytext').innerHTML = s.body || '';
        renderMedia(s.media);
        document.getElementById('gt-back').style.visibility = i === 0 ? 'hidden' : 'visible';
        document.getElementById('gt-next').textContent = (i === steps.length - 1) ? 'Finish' : 'Next';
        document.getElementById('gt-count').textContent = (i + 1) + ' / ' + steps.length;

        overlay.style.display = 'block';

        var rect = null;
        if (s.selector) {
            var el = document.querySelector(s.selector);
            if (el) {
                el.scrollIntoView({ block:'center', behavior:'smooth' });
                rect = el.getBoundingClientRect();
            }
        }
        if (rect) {
            hole.style.display = 'block';
            hole.style.top = (rect.top - 6) + 'px';
            hole.style.left = (rect.left - 6) + 'px';
            hole.style.width = (rect.width + 12) + 'px';
            hole.style.height = (rect.height + 12) + 'px';
        } else {
            hole.style.display = 'none';
        }
        // Let layout settle, then position the popover.
        setTimeout(function () { place(null, rect); }, 60);
        saveProgress(i, false);
    }

    function finish(completed) {
        overlay.style.display = 'none';
        saveProgress(idx, completed);
    }

    function begin(fromIndex) {
        if (!steps.length) return;
        showStep(Math.min(Math.max(0, fromIndex || 0), steps.length - 1));
    }

    function load(cb) {
        api(ACTIVE_URL).then(function (d) {
            if (!d || !d.flow) return;
            flow = d.flow; steps = d.steps || [];
            cb && cb(d);
        }).catch(function () {});
    }

    // Wire controls
    document.getElementById('gt-next').addEventListener('click', function () { showStep(idx + 1); });
    document.getElementById('gt-back').addEventListener('click', function () { showStep(idx - 1); });
    document.getElementById('gt-skip').addEventListener('click', function () { finish(false); });
    document.getElementById('gt-launch').addEventListener('click', function () {
        if (steps.length) { begin(0); }
        else { load(function () { begin(0); }); }
    });
    window.addEventListener('resize', function () {
        if (overlay.style.display === 'block') showStep(idx);
    });

    // Boot: resume a cross-page tour, else autostart-once for new users.
    document.addEventListener('DOMContentLoaded', function () {
        var resume = null;
        try { resume = JSON.parse(sessionStorage.getItem('gt_resume') || 'null'); } catch (e) {}

        load(function (d) {
            if (resume && resume.key === flow.key) {
                try { sessionStorage.removeItem('gt_resume'); } catch (e) {}
                return begin(resume.i);
            }
            var done = localStorage.getItem('gt_done_' + flow.key) === '1';
            if (flow.autostart_once && !d.progress.completed && !done) {
                begin(d.progress.last_step || 0);
            }
        });
    });
})();
</script>
