﻿/* TO API Explorer — ARCADE MODE (game layer). Load AFTER to-explorer.js. */
(function () {
    'use strict';

    const KEY = 'to-arcade';
    const fresh = () => ({ on: true, mute: false, xp: 0, coins: 0, streak: 0, best: 0, reqs: 0, done: {}, ach: {}, welcomed: false });
    let S = (() => { try { return Object.assign(fresh(), JSON.parse(localStorage.getItem(KEY) || '{}')); } catch (e) { return fresh(); } })();
    const save = () => { try { localStorage.setItem(KEY, JSON.stringify(S)); } catch (e) { } };
    const $ = id => document.getElementById(id);
    const esc = s => String(s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
    const pick = a => a[(Math.random() * a.length) | 0];

    const ACH = [
        ['first', '🩸', 'First Blood', 'Send your first request'],
        ['streak5', '🔥', 'On Fire', '5 successful requests in a row'],
        ['streak10', '🌋', 'Unstoppable', '10 successful requests in a row'],
        ['conq10', '⭐', 'Rising Star', 'Conquer 10 endpoints'],
        ['conq25', '🌟', 'Pro Explorer', 'Conquer 25 endpoints'],
        ['world', '🌍', 'World Cleared', 'Conquer every endpoint in one module'],
        ['all', '👑', 'API Legend', 'Conquer every endpoint'],
        ['speed', '⚡', 'Speed Demon', 'Get a 2xx in under 50ms'],
        ['bug', '🐛', 'Bug Hunter', 'Trigger a 5xx server error'],
        ['lost', '🛰️', 'Lost in Space', 'Hit a 404'],
        ['up', '📤', 'Uploader', 'Upload a file successfully'],
        ['down', '📥', 'Downloader', 'Download a file'],
        ['auth', '🔑', 'Key Master', 'Save a JWT token'],
        ['lv5', '🚀', 'Level 5', 'Reach level 5'],
    ];

    /* ───────── spec meta (worlds = tags) ───────── */
    const META = {}, TAGS = {};
    async function loadSpec() {
        for (const u of ['/openapi/v1.json', '/swagger/v1/swagger.json']) {
            try {
                const r = await fetch(u); if (!r.ok) continue;
                const sp = await r.json();
                Object.entries(sp.paths || {}).forEach(([p, po]) => ['get', 'post', 'put', 'delete', 'patch', 'head', 'options'].forEach(m => {
                    const op = po[m]; if (!op) return;
                    const tag = (op.tags && op.tags[0]) || 'General';
                    META[m.toUpperCase() + ' ' + p] = { tag, up: !!(op.requestBody && op.requestBody.content && op.requestBody.content['multipart/form-data']) };
                    TAGS[tag] = (TAGS[tag] || 0) + 1;
                }));
                return;
            } catch (e) { /* next */ }
        }
    }

    /* ───────── progress maths ───────── */
    const level = xp => Math.floor(Math.sqrt(xp / 50)) + 1;
    const lvStart = l => 50 * (l - 1) * (l - 1);
    const conquered = () => Object.keys(S.done).filter(k => S.done[k].ok && META[k]).length;
    const total = () => Object.keys(META).length;
    const tagDone = t => Object.keys(S.done).filter(k => S.done[k].ok && META[k] && META[k].tag === t).length;

    /* ───────── sound ───────── */
    let ac = null;
    function tone(f, d, type, vol, delay) {
        if (S.mute) return;
        try {
            ac = ac || new (window.AudioContext || window.webkitAudioContext)();
            const o = ac.createOscillator(), g = ac.createGain(), t = ac.currentTime + (delay || 0);
            o.type = type || 'square'; o.frequency.value = f;
            g.gain.setValueAtTime(vol || 0.04, t); g.gain.exponentialRampToValueAtTime(0.0001, t + d);
            o.connect(g); g.connect(ac.destination); o.start(t); o.stop(t + d);
        } catch (e) { }
    }
    const SFX = {
        fire: () => tone(220, .08, 'square', .05),
        win: () => [523, 659, 784, 1047].forEach((f, i) => tone(f, .12, 'square', .05, i * .08)),
        bad: () => { tone(180, .15, 'sawtooth', .05); tone(140, .2, 'sawtooth', .05, .12); },
        boss: () => { tone(110, .25, 'sawtooth', .07); tone(80, .35, 'sawtooth', .07, .2); },
        ach: () => [659, 880, 1175, 1568].forEach((f, i) => tone(f, .14, 'triangle', .06, i * .09)),
        lvl: () => [392, 523, 659, 784, 1047, 1319].forEach((f, i) => tone(f, .16, 'square', .05, i * .08)),
    };

    /* ───────── UI pieces ───────── */
    function boot() {
        const link = document.createElement('link');
        link.rel = 'stylesheet';
        link.href = 'https://fonts.googleapis.com/css2?family=Press+Start+2P&display=swap';
        document.head.appendChild(link);

        const shell = $('de-shell');

        const hud = document.createElement('div');
        hud.id = 'ar-hud';
        hud.innerHTML = `
  <div class="ar-lv"><span>LV</span><b id="ar-lv">1</b></div>
  <div class="ar-xp"><div class="ar-bar"><i id="ar-xpfill"></i></div><small id="ar-xptxt">0 / 50 XP</small></div>
  <div class="ar-chip" title="Success streak">🔥 <b id="ar-streak">0</b></div>
  <div class="ar-chip" title="Coins">🪙 <b id="ar-coins">0</b></div>
  <div class="ar-chip" title="Endpoints conquered">⭐ <b id="ar-conq">0</b>/<span id="ar-total">0</span></div>
  <div class="ar-quest" id="ar-quest"></div>
  <button class="ar-ibtn" id="ar-trophy" title="Worlds & achievements">🏆</button>
  <button class="ar-ibtn" id="ar-mute" title="Sound">🔊</button>`;
        shell.insertBefore(hud, $('de-filters'));

        const tgl = document.createElement('button');
        tgl.id = 'ar-toggle'; tgl.className = 'hbtn';
        $('de-hr').insertBefore(tgl, $('de-classic'));

        const extra = document.createElement('div');
        extra.innerHTML = `
<div id="ar-toasts"></div><div id="ar-banner"></div><canvas id="ar-confetti"></canvas>
<div id="ar-bot"><div id="ar-bubble"></div><div id="ar-face">🤖</div></div>
<div id="ar-panel"><div id="ar-pbox"><div class="ar-ph"><b>WORLDS &amp; TROPHIES</b><button id="ar-pclose" class="ar-ibtn">✕</button></div><div id="ar-pbody"></div>
<div class="ar-pf"><button id="ar-reset" class="ar-ibtn">Reset progress</button></div></div></div>`;
        while (extra.firstChild) document.body.appendChild(extra.firstChild);   // keep #ar-bot a sibling of #de-shell

        $('ar-toggle').addEventListener('click', () => setArcade(!S.on));
        $('ar-mute').addEventListener('click', () => { S.mute = !S.mute; save(); paintHud(); });
        $('ar-trophy').addEventListener('click', openPanel);
        $('ar-pclose').addEventListener('click', () => $('ar-panel').classList.remove('show'));
        $('ar-panel').addEventListener('click', e => { if (e.target.id === 'ar-panel') $('ar-panel').classList.remove('show'); });
        $('ar-reset').addEventListener('click', () => { if (confirm('Reset all XP, coins and trophies?')) { S = Object.assign(fresh(), { on: S.on, mute: S.mute, welcomed: true }); save(); paintHud(); decorate(); openPanel(); } });
        $('ar-face').addEventListener('click', () => say(pick(TIPS)));
        document.addEventListener('keydown', e => { if (e.key === 'Escape') $('ar-panel').classList.remove('show'); });

        $('de-exec').addEventListener('click', onSend, true);
        $('de-amsv').addEventListener('click', () => setTimeout(() => { try { if (localStorage.getItem('to-token')) unlock('auth'); } catch (e) { } }, 100));

        new MutationObserver(onStatusChange).observe($('de-rcode-el'), { childList: true, subtree: true });
        obs = new MutationObserver(decorate);
        obs.observe($('de-groups'), { childList: true });

        setArcade(S.on, true);
        paintHud(); decorate();
        setInterval(() => { if (S.on) say(pick(TIPS)); }, 70000);
        if (S.on && !S.welcomed) { S.welcomed = true; save(); setTimeout(() => say('Welcome, Player One! Pick an endpoint and hit FIRE ▶'), 600); }
    }

    let obs = null, awaiting = null, prevTheme = null;

    function setArcade(on, silent) {
        S.on = on; save();
        const shell = $('de-shell');
        if (on) {
            prevTheme = shell.getAttribute('data-theme');
            shell.setAttribute('data-theme', 'dark');
            shell.setAttribute('data-arcade', 'on');
            $('de-exec').innerHTML = '&#9654;&nbsp;FIRE!';
        } else {
            shell.setAttribute('data-arcade', 'off');
            let t = prevTheme || 'dark';
            try { t = localStorage.getItem('to-theme') === 'light' ? 'light' : 'dark'; } catch (e) { }
            shell.setAttribute('data-theme', t);
            $('de-exec').innerHTML = '&#9654;&nbsp;Send';
            $('ar-bot').classList.remove('show');
        }
        $('ar-toggle').textContent = on ? '🎮 Arcade: ON' : '🎮 Arcade: OFF';
        if (!silent && on) say('Arcade mode ON. Let the games begin! 🎮');
        decorate();
    }

    /* ───────── HUD ───────── */
    const QUESTS = [3, 10, 25, 50, 100];
    function paintHud() {
        const lv = level(S.xp), a = lvStart(lv), b = lvStart(lv + 1);
        $('ar-lv').textContent = lv;
        $('ar-xpfill').style.width = Math.min(100, ((S.xp - a) / (b - a)) * 100) + '%';
        $('ar-xptxt').textContent = (S.xp - a) + ' / ' + (b - a) + ' XP';
        $('ar-streak').textContent = S.streak;
        $('ar-coins').textContent = S.coins;
        const c = conquered(), t = total();
        $('ar-conq').textContent = c; $('ar-total').textContent = t;
        const next = QUESTS.find(q => q > c && q <= t);
        $('ar-quest').textContent = t && c >= t ? '👑 All endpoints conquered!' : next ? `🎯 Quest: conquer ${next} endpoints (${c}/${next})` : t ? `🎯 Quest: conquer all ${t} endpoints` : '';
        $('ar-mute').textContent = S.mute ? '🔇' : '🔊';
    }

    /* ───────── decorate cards & worlds ───────── */
    function decorate() {
        const g = $('de-groups'); if (!g) return;
        if (obs) obs.disconnect();
        g.querySelectorAll('.ar-star,.ar-wp').forEach(n => n.remove());
        g.querySelectorAll('.de-card').forEach(card => {
            const key = card.querySelector('.de-badge').textContent.trim() + ' ' + card.querySelector('.de-cp').textContent.trim();
            const d = S.done[key];
            card.classList.toggle('ar-done', !!(d && d.ok));
            if (d && d.ok && S.on) { const s = document.createElement('span'); s.className = 'ar-star'; s.textContent = '⭐'; card.appendChild(s); }
        });
        if (S.on) g.querySelectorAll('.de-group').forEach(gr => {
            const tag = gr.querySelector('.de-gn').textContent.trim(), t = TAGS[tag];
            if (!t) return;
            const d = tagDone(tag), w = document.createElement('span');
            w.className = 'ar-wp' + (d >= t ? ' full' : '');
            w.innerHTML = `<i style="width:${(d / t) * 100}%"></i><em>${d >= t ? '🏁 CLEARED' : d + '/' + t}</em>`;
            gr.querySelector('.de-gh').appendChild(w);
        });
        if (obs) obs.observe(g, { childList: true });
    }

    /* ───────── request lifecycle ───────── */
    function onSend() {
        if (!S.on) return;
        const m = $('de-dm').textContent.trim(), p = $('de-dp').textContent.trim();
        awaiting = { key: m + ' ' + p };
        SFX.fire();
    }

    function onStatusChange() {
        if (!awaiting || !S.on) return;
        const el = $('de-rcode-el').querySelector('.rcode'); if (!el) return;
        const mt = /^\s*(\d{3})/.exec(el.textContent);
        const job = awaiting; awaiting = null;
        if (!mt) return;                                   // "Network Error" / "Missing file"
        const code = parseInt(mt[1], 10), ms = parseInt(($('de-rtime').textContent || '').replace(/\D/g, ''), 10) || 9999;
        setTimeout(() => result(job.key, code, ms), 350);  // wait for the body to render
    }

    function result(key, code, ms) {
        const ok = code >= 200 && code < 300, before = level(S.xp);
        const first = !(S.done[key] && S.done[key].ok);
        S.reqs++; S.coins += 1; let gain = 10;
        const rec = S.done[key] || { n: 0, ok: false }; rec.n++;
        if (ok) {
            gain += 10; S.streak++; S.best = Math.max(S.best, S.streak);
            if (first) { gain += 25; S.coins += 5; }
            rec.ok = true;
        } else S.streak = 0;
        S.done[key] = rec; S.xp += gain; save();

        const meta = META[key] || {};
        if (S.reqs === 1) unlock('first');
        if (ok) {
            banner(pick(['VICTORY!', 'NICE SHOT!', 'GG!', 'SMOOTH!', 'PERFECT!']), 'win'); confetti(); SFX.win();
            say(first ? `New endpoint conquered! +${gain} XP ⭐` : pick(['Clean hit! 🎯', 'Smooth as butter.', 'Another one down.']));
            if (ms < 50) unlock('speed');
            if (meta.up) unlock('up');
            if ($('de-rb').querySelector('.de-file')) unlock('down');
        } else if (code >= 500) {
            banner('BOSS HIT! 💥', 'boss'); shake(); SFX.boss(); unlock('bug');
            say('The server crashed. Check the API console for the stack trace.');
        } else {
            banner(pick(['OOPS!', 'TRY AGAIN!', 'MISSED!']), 'bad'); SFX.bad();
            const hints = { 400: 'Bad request. Check the required (*) fields.', 401: 'Locked door! Click Authorize and paste your JWT.', 403: "You don't have permission for this one.", 404: 'Nothing here. Wrong ID or path?', 409: 'Conflict. That record probably already exists.', 413: 'File too big for the server limit.', 415: 'Wrong content type or file format.', 422: 'Validation failed. Read the response body.' };
            say(hints[code] || 'Not quite. Read the response body for clues.');
            if (code === 404) unlock('lost');
        }
        if (S.streak >= 5) unlock('streak5');
        if (S.streak >= 10) unlock('streak10');
        const c = conquered(), t = total();
        if (c >= 10) unlock('conq10'); if (c >= 25) unlock('conq25'); if (t && c >= t) unlock('all');
        Object.keys(TAGS).forEach(tg => { if (TAGS[tg] && tagDone(tg) >= TAGS[tg]) unlock('world'); });
        if (level(S.xp) > before) { levelUp(level(S.xp)); }
        paintHud(); decorate();
    }

    function levelUp(l) { SFX.lvl(); banner('LEVEL ' + l + '!', 'win'); confetti(); say('LEVEL UP! You are now level ' + l + ' 🚀'); if (l >= 5) unlock('lv5'); }

    function unlock(id) {
        if (S.ach[id]) return;
        const a = ACH.find(x => x[0] === id); if (!a) return;
        S.ach[id] = Date.now(); S.coins += 10; save(); SFX.ach();
        const t = document.createElement('div');
        t.className = 'ar-toast';
        t.innerHTML = `<span>${a[1]}</span><div><small>ACHIEVEMENT UNLOCKED</small><b>${esc(a[2])}</b><em>${esc(a[3])} · +10 🪙</em></div>`;
        $('ar-toasts').appendChild(t);
        setTimeout(() => t.classList.add('out'), 4200); setTimeout(() => t.remove(), 4700);
        paintHud();
    }

    /* ───────── effects ───────── */
    function banner(txt, kind) {
        const b = $('ar-banner'); b.textContent = txt; b.className = '';
        void b.offsetWidth; b.className = 'show ' + kind;
    }
    function shake() { const s = $('de-shell'); s.classList.remove('ar-shake'); void s.offsetWidth; s.classList.add('ar-shake'); }
    let bubT = null;
    function say(msg) {
        if (!S.on) return;
        const bot = $('ar-bot'); $('ar-bubble').textContent = msg; bot.classList.add('show');
        clearTimeout(bubT); bubT = setTimeout(() => bot.classList.remove('show'), 5200);
    }
    const TIPS = ['Press Ctrl+K to jump to search.', 'Drag the divider to resize the panel.', 'Use the 📁 Files filter to find upload endpoints.', 'Authorize first, most endpoints need a JWT.', 'Click my face for a tip!', 'Double-click the divider to reset the width.'];

    function confetti() {
        const c = $('ar-confetti'), x = c.getContext('2d');
        c.width = innerWidth; c.height = innerHeight; c.style.display = 'block';
        const cols = ['#00f0ff', '#ff3cac', '#ffe600', '#7cff6b', '#ff8a3c'];
        const ps = Array.from({ length: 110 }, () => ({ x: innerWidth / 2 + (Math.random() - .5) * 200, y: innerHeight * .35, vx: (Math.random() - .5) * 14, vy: -Math.random() * 13 - 4, s: 4 + Math.random() * 6, c: pick(cols), r: Math.random() * 6.28, vr: (Math.random() - .5) * .4 }));
        const t0 = performance.now();
        (function f(t) {
            x.clearRect(0, 0, c.width, c.height);
            ps.forEach(p => { p.vy += .35; p.x += p.vx; p.y += p.vy; p.r += p.vr; x.save(); x.translate(p.x, p.y); x.rotate(p.r); x.fillStyle = p.c; x.fillRect(-p.s / 2, -p.s / 2, p.s, p.s * .6); x.restore(); });
            if (t - t0 < 1600) requestAnimationFrame(f); else { x.clearRect(0, 0, c.width, c.height); c.style.display = 'none'; }
        })(t0);
    }

    /* ───────── trophy panel ───────── */
    function openPanel() {
        const worlds = Object.keys(TAGS).sort().map(t => {
            const d = tagDone(t), n = TAGS[t];
            return `<div class="ar-w"><span>${esc(t)}</span><div class="ar-wb"><i style="width:${(d / n) * 100}%"></i></div><em>${d >= n ? '🏁' : d + '/' + n}</em></div>`;
        }).join('') || '<div class="ar-empty">No worlds loaded yet.</div>';
        const trophies = ACH.map(a => `<div class="ar-t ${S.ach[a[0]] ? 'on' : ''}"><span>${S.ach[a[0]] ? a[1] : '🔒'}</span><b>${esc(a[2])}</b><small>${esc(a[3])}</small></div>`).join('');
        $('ar-pbody').innerHTML = `<div class="ar-stats">Requests <b>${S.reqs}</b> · Best streak <b>${S.best}</b> · XP <b>${S.xp}</b> · Coins <b>${S.coins}</b></div>
<h4>WORLDS</h4>${worlds}<h4>TROPHIES (${Object.keys(S.ach).length}/${ACH.length})</h4><div class="ar-tg">${trophies}</div>`;
        $('ar-panel').classList.add('show');
    }

    /* ───────── start ───────── */
    loadSpec().finally(() => {
        const t = setInterval(() => { if ($('de-shell') && $('de-exec') && $('de-groups')) { clearInterval(t); boot(); } }, 300);
    });
})();
