<%+cbi/valueheader%>
<%
    local fs = require "luci.openclash"
    local plugin_version = fs.oc_version()
%>
<script src="/luci-static/resources/openclash/js/oc-icons.js?v=<%=plugin_version%>"></script>
<%
	local fs = require "luci.openclash"
	local val = self:cfgvalue(section)
	local filename = fs.filename(val)
	local idname = math.random(1000)..(string.match(filename, "[%w_]+") or "")
%>

<div class="sub_div oc">
    <span id='<%=idname%>' class="sub_tab"></span>
    <button type="button" class="sub_setting" title='<%:Refresh%>' alt='<%:Refresh%>' onclick='return sub_info_refresh_<%=idname%>(true)'>
        <svg viewBox="0 0 24 24"><use href="#oc-icon-refresh"/></svg>
    </button>
    <button type="button" class="sub_setting" title='<%:Specify URL%>' alt='<%:Specify URL%>' onclick='return setUrlConfig_<%=idname%>()'>
        <svg viewBox="0 0 48 48"><use href="#oc-icon-chat"/></svg>
    </button>
    <button type="button" class="sub_setting" title='<%:Edit Subscription%>' alt='<%:Edit Subscription%>' onclick='return uploadConfig_<%=idname%>()'>
        <svg width="14" height="14"><use href="#oc-icon-settings"/></svg>
    </button>
</div>

<script type="text/javascript">//<![CDATA[

var retry_<%=idname%> = 0;
var s_<%=idname%>;
sub_info_refresh_<%=idname%>(false);

function progressbar_<%=idname%>(v, m, pc, np, f, t, tr) {
    var screenWidth = window.innerWidth || document.documentElement.clientWidth;
    var fontSize = '12px';

    if (screenWidth <= 320) {
        fontSize = '8px';
    } else if (screenWidth <= 480) {
        fontSize = '9px';
    } else if (screenWidth <= 768) {
        fontSize = '10px';
    } else if (screenWidth <= 1024) {
        fontSize = '11px';
    }

    // Build title for native tooltip (format: "v / m (pc%)\nt (Remaining tr days)")
    var titleText = v + ' / ' + m + ' (' + pc + '%%)';
    if (t && t !== 'null' && tr && tr !== 'null' && parseInt(tr) > 0) {
        titleText += '\n' + t + ' (<%:Remaining%> ' + tr + ' <%:days%>)';
    }

    return String.format(
        '<div class="progress_bar_bg" title="' + titleText + '" style="position:relative; border-radius: 6px; display: flex; align-items: center;">' +
        (pc >= 50 ? '<div class="progress_bar_high" style="width:%d%%; height:34px; border-radius: 6px">' :
        (pc < 50 && pc >= 20 ? '<div class="progress_bar_medium" style="width:%d%%; height:34px; border-radius: 6px">' :
        '<div class="progress_bar_low" style="width:%d%%; height:34px; border-radius: 6px">')) +
        '<div style="position:absolute; left:0; top:50%%; transform: translateY(-50%%); text-align:center; width:100%%; padding:0 4px; box-sizing:border-box; line-height:1.2;">' +
        '<small class="text_show" style="font-size:%s; line-height:1.2;">%s '+ (f ? f : '/') +' %s ' + (np ? "" : '(%s%%)') +
        (tr == "null" ? '<div style="visibility: hidden; line-height:1.2;">' : '<div style="visibility: visible; line-height:1.2;">') +
        '%s (<%:Remaining%> %s <%:days%>)</small>' +
        '</div>' +
        '</div>' +
        '</div>',
        pc, fontSize, v, m, pc, t, tr
    );
};

function progressbar_multi_<%=idname%>(providers) {
    var providerCount = providers.length;
    var itemWidth;
    var containerClass = 'sub_providers_container';

    if (providerCount === 2) {
        itemWidth = 'calc(50% - 2px)';
        containerClass += ' no-scroll';
    } else if (providerCount === 3) {
        itemWidth = 'calc(33.33% - 2.67px)';
        containerClass += ' no-scroll';
    } else {
        itemWidth = '100px';
    }

    var container = '<div class="' + containerClass + '" id="sub_providers_<%=idname%>">';

    providers.forEach(function(provider) {
        var percent = parseFloat(provider.percent) || 0;
        var providerName = provider.provider_name || 'Unknown';
        var used = provider.used || '0 B';
        var total = provider.total || 'N/A';
        var surplus = provider.surplus || used;
        var expire = provider.expire || 'null';
        var dayLeft = parseInt(provider.day_left) || 0;

        // Determine background color based on percentage
        var bgColorClass = percent >= 50 ? 'progress_bar_high' :
                          (percent >= 20 ? 'progress_bar_medium' : 'progress_bar_low');

        // Build title for native tooltip (format: "surplus / total (percent%)\nexpire (Remaining dayLeft days)")
        var titleText = surplus + ' / ' + total + ' (' + percent + '%)';
        if (expire !== 'null' && dayLeft > 0) {
            titleText += '\n' + expire + ' (<%:Remaining%> ' + dayLeft + ' <%:days%>)';
        }

        container += '<div class="sub_provider_item" style="width: ' + itemWidth + '" title="' + titleText + '">' +
                    '<div class="sub_provider_fill ' + bgColorClass + '" style="width: ' + percent + '%"></div>' +
                    '<span class="sub_provider_name">' + providerName + '</span>' +
                    '<span class="sub_provider_percent">' + ' (' + percent + '%)' + '</span>' +
                    '</div>';
    });

    container += '</div>';

    if (providerCount > 3) {
        setTimeout(function() {
            initDragScroll_<%=idname%>();
        }, 100);
    }

    return container;
};

function initDragScroll_<%=idname%>() {
    var container = document.getElementById('sub_providers_<%=idname%>');
    if (!container) return;

    var isDragging = false;
    var startX;
    var scrollLeft;
    var hasMoved = false;

    container.addEventListener('mousedown', function(e) {
        if (e.target.tagName === 'A' || e.target.tagName === 'BUTTON') {
            return;
        }

        isDragging = true;
        hasMoved = false;
        startX = e.pageX - container.offsetLeft;
        scrollLeft = container.scrollLeft;
        container.classList.add('dragging');
    });

    container.addEventListener('mousemove', function(e) {
        if (!isDragging) return;

        var x = e.pageX - container.offsetLeft;
        var walk = (x - startX) * 2;

        if (Math.abs(walk) > 5) {
            hasMoved = true;
            e.preventDefault();
            container.scrollLeft = scrollLeft - walk;
        }
    });

    container.addEventListener('mouseup', function() {
        isDragging = false;
        container.classList.remove('dragging');
    });

    container.addEventListener('mouseleave', function() {
        isDragging = false;
        container.classList.remove('dragging');
    });

    container.addEventListener('dragstart', function(e) {
        e.preventDefault();
    });
};

function dispaly_progressbar(id, status) {
    document.getElementById(id).className = "sub_tab_show";
    if (status && status.providers && status.providers.length > 0) {
        if (status.providers.length === 1) {
            var provider = status.providers[0];
            document.getElementById(id).innerHTML = window["progressbar_" + id](
                (provider.surplus ? provider.surplus : provider.used),
                (provider.total),
                (provider.percent),
                false, false,
                (provider.expire),
                (provider.day_left)
            );
        } else {
            document.getElementById(id).innerHTML = window["progressbar_multi_" + id](status.providers);
        }
    } else {
        document.getElementById(id).innerHTML = "<span><%:No Sub Info Found%></span>";
    }
};

function sub_info_refresh_<%=idname%>(force) {
	if (s_<%=idname%>) { clearTimeout(s_<%=idname%>);};

    if (force) {
        localStorage.removeItem("sub_info_<%=filename%>");
    }

    var save_info = (localStorage.getItem("sub_info_<%=filename%>")) ? JSON.parse(localStorage.getItem("sub_info_<%=filename%>")) : null;
    var shouldFetchNew = true;
    if (!force) {
        dispaly_progressbar('<%=idname%>', save_info);
        if (save_info && save_info.get_time) {
            var currentTime = Math.floor(Date.now() / 1000);
            var cacheTime = parseInt(save_info.get_time);
            var timeDiff = currentTime - cacheTime;
            var halfHourInSeconds = 30 * 60;

            if (timeDiff <= halfHourInSeconds) {
                shouldFetchNew = false;
            }
        }
    }

    if (!shouldFetchNew) {
        s_<%=idname%> = setTimeout("sub_info_refresh_<%=idname%>(false)", 60000*15);
        return;
    }

    if (!save_info) {
        document.getElementById('<%=idname%>').className = "sub_tab_show";
        document.getElementById('<%=idname%>').innerHTML = "<span><%:Collecting data...%></span>";
    }

	XHR.get('<%=luci.dispatcher.build_url("admin", "services", "openclash", "sub_info_get")%>', {filename: "<%=filename%>"}, function(x, status) {
        var needsErrorHandling = false;
        if (x && x.status == 200 && status.providers.length > 0) {
            var save_info_length = (save_info && save_info.providers) ? save_info.providers.length : 0;
            var newProvidersLength = status.providers.length;
            if (save_info_length !== newProvidersLength && save_info_length > newProvidersLength) {
                needsErrorHandling = true;
            }

            if (!needsErrorHandling) {
                retry_<%=idname%> = 0;
                (window.requestIdleCallback || function(cb) { setTimeout(cb, 1); })(function() { localStorage.setItem("sub_info_<%=filename%>", JSON.stringify(status)); });
                dispaly_progressbar('<%=idname%>', status);
            }
		} else {
            needsErrorHandling = true;
		};

        if (needsErrorHandling && retry_<%=idname%> <= 2) {
            retry_<%=idname%>++;
            s_<%=idname%> = setTimeout("sub_info_refresh_<%=idname%>(false)", 5000);
        } else {
            retry_<%=idname%> = 0;
            dispaly_progressbar('<%=idname%>', status);
            if (status && status.providers) {
                (window.requestIdleCallback || function(cb) { setTimeout(cb, 1); })(function() { localStorage.setItem("sub_info_<%=filename%>", JSON.stringify(status)); });
            }
            s_<%=idname%> = setTimeout("sub_info_refresh_<%=idname%>(false)", 60000*15);
        };
	});
};

function setUrlConfig_<%=idname%>() {
    SubscriptionUrlSetter.show("<%=filename%>", "sub_info_refresh_<%=idname%>(true)");
    return false;
}

function uploadConfig_<%=idname%>() {
    if (typeof ConfigUploader === 'undefined') return false;

    var filename = "<%=filename%>";
    var cb = "sub_info_refresh_<%=idname%>(true)";
    XHR.get('<%=luci.dispatcher.build_url("admin", "services", "openclash", "get_subscribe_data")%>', {
        filename: filename
    }, function(x, status) {
        if (ConfigUploader.showEditSubscribe) {
            ConfigUploader.showEditSubscribe((x && x.status == 200) ? status : null, filename, cb);
        } else {
            ConfigUploader.show(cb);
        }
    });
    return false;
}

//]]></script>
<%+cbi/valuefooter%>
