<%+openclash/common%>
<script src="/luci-static/resources/openclash/js/oc-icons.js?v=<%=plugin_version%>"></script>
<body>
    <div class="oc">
        <div id="selectPopup" class="select-popup hidden">
            <div class="select-popup-header">
                <div class="config-editor-title">
                    <%:Check Update%>
                </div>
                <div class="config-editor-actions">
                    <button type="button" class="icon-btn close-btn" onclick="closeSelectPopup()" title="<%:Close%>">
                        <svg width="14" height="14"><use href="#oc-icon-close"/></svg>
                    </button>
                </div>
            </div>
            <div class="select-config-section">
                <div class="config-grid">
                    <div class="config-item">
                        <div class="config-label"><%:Compiled Version%></div>
                        <select class="select-class oc-arch-select" id="CORE_VERSION_CDN">
                        </select>
                    </div>

                    <div class="config-item">
                        <div class="config-label"><%:Release Branch%></div>
                        <select class="select-class" id="RELEASE_BRANCH_CDN">
                            <option value="master">Master</option>
                            <option value="dev">Developer</option>
                        </select>
                    </div>

                    <div class="config-item">
                        <div class="config-label">
                            <%:Smart Core%>
                            <a href="javascript:void(0);" onclick="window.open('https://github.com/vernesong/mihomo/releases', '_blank');" class="help-link" title="<%:View core infos that support smart group%>">
                                <svg width="12" height="12"><use href="#oc-icon-help"/></svg>
                            </a>
                        </div>
                        <select class="select-class" id="SMART_ENABLE_CDN">
                            <option value="0"><%:Disabled%></option>
                            <option value="1"><%:Enable%></option>
                        </select>
                    </div>
                </div>
            </div>

            <div class="select-popup-body">
                <div class="select-option" data-value="https://raw.githubusercontent.com/">
                    <span>https://raw.githubusercontent.com/ (<%:RAW address%>)</span>
                </div>
                <div class="select-option" data-value="https://fastly.jsdelivr.net/">
                    <span>https://fastly.jsdelivr.net/</span>
                </div>
                <div class="select-option" data-value="https://testingcf.jsdelivr.net/">
                    <span>https://testingcf.jsdelivr.net/</span>
                </div>
                <div class="select-option" data-value="https://cdn.jsdelivr.net/">
                    <span>https://cdn.jsdelivr.net/</span>
                </div>
                <div class="select-option" data-value="custom">
                    <span><%:Custom Your CDN URL%></span>
                    <span style="display: flex; align-items: center; height: 100%;">
                        <svg width="18" height="18" style="display: block;"><use href="#oc-icon-chevron-down"/></svg>
                    </span>
                </div>
                <input type="text" id="customOptionInput" class="custom-option-input" value="https://ghfast.top/" placeholder="<%:Type CDN URL, Format Like%> https://ghfast.top/" style="display: none;">
                <div class="select-option" id="addCustomOption" style="display: none;"><%:Add%></div>
            </div>
        </div>
    </div>
</body>

<script type="text/javascript">
//<![CDATA[
    var core_version_cdn = document.getElementById('CORE_VERSION_CDN');
    var release_branch_cdn = document.getElementById('RELEASE_BRANCH_CDN');
    var smart_enable_cdn = document.getElementById('SMART_ENABLE_CDN');

    function get_update_info() {
        XHR.get('<%=luci.dispatcher.build_url("admin", "services", "openclash", "update_info")%>', null, function(x, status) {
            if ( x && x.status == 200 ) {
                if ( status.corever && status.corever != "0" && status.corever != "" ) {
                    core_version_cdn.value = status.corever;
                }
                else {
                    core_version_cdn.value = "0";
                }
                if ( status.release_branch && status.release_branch != "" ) {
                    release_branch_cdn.value = status.release_branch;
                }
                else {
                    release_branch_cdn.value = "master";
                }
                if ( status.smart_enable && status.smart_enable != "" ) {
                    smart_enable_cdn.value = status.smart_enable;
                }
                else {
                    smart_enable_cdn.value = "0";
                }
            }
            else {
                core_version_cdn.value = "0";
                release_branch_cdn.value = "master";
                smart_enable_cdn.value = "0";
            }
        });
    }

    function isValidURL(str) {
        var pattern = new RegExp('^(https?:\\/\\/)?'+ // protocol
            '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name
            '((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
            '(\\:\\d+)?(\\/[-a-z\\d%_.&#126;+]*)*'+ // port and path
            '(\\?[;&a-z\\d%_.&#126;+=-]*)?'+ // query string
            '(\\#[-a-z\\d_]*)?'+'\/$','i'); // fragment locator
        return !!pattern.test(str);
    }

    function HTTP_delay(domain, ID) {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', '/cgi-bin/luci/admin/services/openclash/website_check?domain=' + encodeURIComponent(domain), true);
        xhr.timeout = 5000;

        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4) {
                let status, text, response_time = 0;
                if (xhr.status === 200) {
                    try {
                        var resp = JSON.parse(xhr.responseText);
                        response_time = resp.response_time || 0;
                        if (resp.success) {
                            if (response_time <= 500) {
                                status = 'fast';
                                text = response_time + ' ms';
                            } else if (response_time > 500 && response_time <= 1000) {
                                status = 'medium';
                                text = response_time + ' ms';
                            } else {
                                status = 'slow';
                                text = response_time + ' ms';
                            }
                        } else {
                            status = 'error';
                            text = resp.error || '<%:Access Denied%>';
                        }
                    } catch (e) {
                        status = 'error';
                        text = '<%:Access Denied%>';
                    }
                } else {
                    status = 'error';
                    text = '<%:Access Timed Out%>';
                }
                updateCDNStatus(ID, status, text);
            }
        };

        xhr.ontimeout = function() {
            updateCDNStatus(ID, 'error', '<%:Access Timed Out%>');
        };

        xhr.onerror = function() {
            updateCDNStatus(ID, 'error', '<%:Access Denied%>');
        };

        xhr.send();
    }

    function updateCDNStatus(element, status, text) {
        var existingStatus = element.querySelector('.cdn-status');
        if (existingStatus) {
            existingStatus.remove();
        }

        var statusSpan = document.createElement('span');
        statusSpan.className = 'cdn-status ' + status;
        statusSpan.textContent = text;
        element.appendChild(statusSpan);
    }

    function select_git_cdn(btn, type) {
        var selectPopup = document.getElementById('selectPopup');
        get_update_info();
        selectPopup.classList.remove('hidden');

        var customOptionInput = document.getElementById('customOptionInput');
        var addCustomOption = document.getElementById('addCustomOption');
        var selectOptions = document.getElementsByClassName('select-option');

        customOptionInput.style.display = 'none';
        addCustomOption.style.display = 'none';

        selectPopup.addEventListener('click', function(event) {
            select_window(event, type);
        });

        document.addEventListener('click', select_window_close);

        refresh_httpdelay = setInterval(() => {
            for(var i = 0; i < selectOptions.length; i++) {
                if (isValidURL(selectOptions[i].dataset.value)) {
                    HTTP_delay(selectOptions[i].dataset.value, selectOptions[i]);
                }
            }
        }, Math.floor(Math.random()*(7-3+1)+3)*1000);
    }

    function select_window_close(event) {
        var selectPopup = document.getElementById('selectPopup');
        if (!selectPopup.contains(event.target)) {
            selectPopup.classList.add('hidden');
            if (typeof refresh_httpdelay !== 'undefined') {
                clearInterval(refresh_httpdelay);
            }
        }
    }

    function select_window(event, type) {
        var v = core_version_cdn.value;
        var r = release_branch_cdn.value;
        var s = smart_enable_cdn.value;
        var selectOptions = document.getElementsByClassName('select-option');
        var target = event.target;
        var selectPopup = document.getElementById('selectPopup');
        var customOptionInput = document.getElementById('customOptionInput');
        var addCustomOption = document.getElementById('addCustomOption');

        var optionElem = target.closest ? target.closest('.select-option') : null;

        if (optionElem && optionElem.dataset.value === 'custom' && customOptionInput.style.display === 'block') {
            customOptionInput.style.display = 'none';
            addCustomOption.style.display = 'none';
        } else if (optionElem && optionElem.dataset.value === 'custom') {
            customOptionInput.style.display = 'block';
            addCustomOption.style.display = 'block';
            customOptionInput.focus();
        } else if (target === customOptionInput) {
            customOptionInput.style.display = 'block';
            addCustomOption.style.display = 'block';
            customOptionInput.focus();
        } else if (target === addCustomOption) {
            var newValue = customOptionInput.value.trim();
            if (newValue !== '' && isValidURL(newValue)) {
                var newOption = document.createElement('div');
                newOption.classList.add('select-option');
                newOption.innerHTML = '<span>' + newValue + '</span>';
                newOption.dataset.value = newValue;
                selectPopup.querySelector('.select-popup-body').insertBefore(newOption, selectPopup.querySelector('.select-popup-body').children[selectOptions.length - 2]);
                customOptionInput.style.display = 'none';
                addCustomOption.style.display = 'none';
            }
            else {
                alert("<%:Please enter a valid URL!%>");
            }
        } else if (optionElem && optionElem != addCustomOption && optionElem != customOptionInput)  {
            customOptionInput.style.display = 'none';
            addCustomOption.style.display = 'none';
            if (typeof LogManager !== 'undefined' && LogManager) {
                LogManager.startLogDisplay('<%:Checking...%>');
            }
            if (optionElem.dataset.value === 'https://raw.githubusercontent.com/') {
                optionElem.dataset.value = '';
            }
            if (type === 'core_download') {
                XHR.get('<%=luci.dispatcher.build_url("admin", "services", "openclash", "save_corever_branch")%>', {core_ver: v, release_branch: r, smart_enable: s}, function(x, status) {
                    if (x && x.status == 200) {
                        XHR.get('<%=luci.dispatcher.build_url("admin", "services", "openclash", "core_download")%>', {url: optionElem.dataset.value}, function(x, status) {
                        });
                    }
                });
            }
            else {
                XHR.get('<%=luci.dispatcher.build_url("admin", "services", "openclash", "save_corever_branch")%>', {core_ver: v, release_branch: r, smart_enable: s}, function(x, status) {
                    if (x && x.status == 200) {
                        XHR.get('<%=luci.dispatcher.build_url("admin", "services", "openclash", "one_key_update")%>', {url: optionElem.dataset.value}, function(x, status) {
                        });
                    }
                });
            }

            selectPopup.classList.add('hidden');
            if (typeof refresh_httpdelay !== 'undefined') {
                clearInterval(refresh_httpdelay);
            }
        }
        else if (target != addCustomOption && target != customOptionInput) {
            customOptionInput.style.display = 'none';
            addCustomOption.style.display = 'none';
        }
        else {
            if (target != customOptionInput) {
                selectPopup.classList.add('hidden');
                if (typeof refresh_httpdelay !== 'undefined') {
                    clearInterval(refresh_httpdelay);
                }
            }
        }
    }

    function closeSelectPopup() {
        var selectPopup = document.getElementById('selectPopup');
        selectPopup.classList.add('hidden');
        if (typeof refresh_httpdelay !== 'undefined') {
            clearInterval(refresh_httpdelay);
        }
    }
//]]>
</script>