// Content script: 教程按钮注入
// 运行在 ISOLATED 世界，可访问 DOM 和 fetch()
// 通过 manifest.json content_scripts 声明式注入，无需 scripting 权限

(function () {
    'use strict';

    var SERVER_URLS = [
        'https://go.mtab.cc',
        'https://tab.qingdaohang.cn',
        'https://qingdaohang.cn'
    ];

    var TUTORIAL_ICON = 'data:image/svg+xml,' + encodeURIComponent(
        '<svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg" width="20" height="20">' +
        '<path d="M512 64L128 256v288c0 176 128 336 384 448 256-112 384-272 384-448V256L512 64zM512 872c-153.6-70.4-256-188.8-256-368V326.4l256-128 256 128V504c0 179.2-102.4 297.6-256 368z" fill="#4285F4"/>' +
        '<path d="M464 384h96v256h-96z" fill="#4285F4"/>' +
        '<path d="M464 320h96v64h-96z" fill="#4285F4"/>' +
        '</svg>'
    );

    var tutorialLink = '';
    var injected = false;

    function tryFetchFromServer() {
        var endpoints = [];
        SERVER_URLS.forEach(function (base) {
            endpoints.push(base + '/api/site');
            endpoints.push(base + '/index.php/api/site');
        });

        function tryEndpoint(index) {
            if (index >= endpoints.length) return;

            fetch(endpoints[index], { credentials: 'include' })
                .then(function (res) {
                    if (!res.ok) throw new Error('HTTP ' + res.status);
                    return res.json();
                })
                .then(function (data) {
                    if (data && data.code === 1 && data.data && data.data.tutorial_link) {
                        tutorialLink = data.data.tutorial_link;
                        tryInject();
                    } else {
                        tryEndpoint(index + 1);
                    }
                })
                .catch(function () { tryEndpoint(index + 1); });
        }

        tryEndpoint(0);
    }

    function tryInject() {
        if (!tutorialLink || injected) return;

        var downloadBox = document.querySelector('.downloadBox');
        if (!downloadBox) return;

        if (downloadBox.parentNode.querySelector('[data-tutorial-row]')) return;

        var rowBox = document.createElement('div');
        rowBox.setAttribute('data-tutorial-row', '1');
        rowBox.style.cssText = 'position:absolute;bottom:10px;left:0;display:flex;justify-content:center;width:100%;';

        var newBtn = document.createElement('a');
        newBtn.setAttribute('href', tutorialLink);
        newBtn.setAttribute('target', '_blank');
        newBtn.setAttribute('data-tutorial-btn', '1');

        newBtn.style.cssText = 'padding:6px 14px;background:#fff;border:1.5px solid #4285F4;border-radius:100px;display:inline-flex;align-items:center;gap:8px;font-size:13px;font-weight:500;color:#4285F4;text-decoration:none;cursor:pointer;transition:all .2s;';
        newBtn.onmouseenter = function () {
            this.style.background = '#4285F4';
            this.style.color = '#fff';
        };
        newBtn.onmouseleave = function () {
            this.style.background = '#fff';
            this.style.color = '#4285F4';
        };

        var img = document.createElement('img');
        img.src = TUTORIAL_ICON;
        img.style.cssText = 'width:20px;height:20px;filter:brightness(0) saturate(100%) invert(56%) sepia(93%) saturate(2000%) hue-rotate(205deg) brightness(97%) contrast(101%);';
        newBtn.appendChild(img);
        newBtn.appendChild(document.createTextNode('插件使用教程'));

        rowBox.appendChild(newBtn);
        downloadBox.parentNode.insertBefore(rowBox, downloadBox.nextSibling);

        var parent = downloadBox.parentNode;
        if (getComputedStyle(parent).position === 'static') {
            parent.style.position = 'relative';
        }
        injected = true;
    }

    var observer = new MutationObserver(function (mutations) {
        for (var i = 0; i < mutations.length; i++) {
            if (mutations[i].addedNodes.length > 0) {
                tryInject();
                return;
            }
        }
    });

    observer.observe(document.documentElement, { childList: true, subtree: true });

    tryFetchFromServer();
})();
