<%+cbi/valueheader%>
<style>
.sub_div {
    display: flex;
    align-items: center;
    gap: 8px;
    flex-wrap: nowrap;
    width: calc(100% - 24px);
    box-sizing: border-box;
    min-width: 280px;
    max-width: 350px;
    margin: 0 auto;
}

.sub_div > span:first-child {
    flex: 1;
    min-width: 0;
}

.sub_tab {
    display: block;
    white-space: nowrap;
    font-size: 12px;
    margin: 0;
    opacity: 0;
    width: 100%;
    max-width: 100%;
    overflow: hidden;
    box-sizing: border-box;
}

.sub_tab_show {
    display: block;
    white-space: nowrap;
    font-size: 12px;
    margin: 0;
    -webkit-transition: all 1s;
    -moz-transition: all 1s;
    -ms-transition: all 1s;
    -o-transition: all 1s;
    transition: all 1s;
    opacity: 1;
    width: 100%;
    max-width: 100%;
    overflow: hidden;
    box-sizing: border-box;
}

.sub_setting {
    display: inline-block;
    white-space: nowrap;
    margin: 0;
    opacity: 1;
    vertical-align: middle;
    line-height: 0;
    flex-shrink: 0;
    cursor: pointer;
}

.sub_setting img {
    vertical-align: middle;
    display: inline-block;
    transition: opacity 0.3s ease;
}

.sub_setting:hover img {
    opacity: 0.7;
}

.text_show {
    color: #333333;
    line-height: 1.2;
}

.progress_bar_bg {
    border: 1px solid #999999;
    background-color: #f5f5f5;
    width: 100% !important;
    max-width: 100% !important;
    min-width: 220px;
    box-sizing: border-box;
    border-radius: 6px;
    height: 36px;
}

.progress_bar_high {
    background-color: #9edd9e;
}

.progress_bar_medium {
    background-color: #ffc99f;
}

.progress_bar_low {
    background-color: #ffb9b9;
}

:root[data-darkmode="true"] #icon_wrench {
    -webkit-filter: invert(1);
    filter: invert(1);
}

:root[data-darkmode="true"] #icon_arrow {
    -webkit-filter: invert(1);
    filter: invert(1);
}

:root[data-darkmode="true"] .text_show {
    color: #e0e0e0;
    line-height: 1.2;
}

:root[data-darkmode="true"] .progress_bar_bg {
    border: 1px solid #666666;
    background-color: #333333;
}

:root[data-darkmode="true"] .progress_bar_high {
    background-color: #5da05d;
}

:root[data-darkmode="true"] .progress_bar_medium {
    background-color: #cc8550;
}

:root[data-darkmode="true"] .progress_bar_low {
    background-color: #cc6262;
}

@media (max-width: 1024px) {
    .sub_tab, .sub_tab_show {
        font-size: 11px;
    }

    .progress_bar_bg {
        min-width: 220px;
    }

    .sub_div {
        gap: 6px;
        width: calc(100% - 20px);
        margin: 0 10px;
    }
}

@media (max-width: 768px) {
    .sub_tab, .sub_tab_show {
        font-size: 10px;
    }

    .progress_bar_bg {
        min-width: 200px;
    }

    .sub_setting img {
        height: 18px !important;
    }

    .sub_div {
        gap: 4px;
        width: calc(100% - 16px);
        margin: 0 8px;
    }
}

@media (max-width: 480px) {
    .sub_tab, .sub_tab_show {
        font-size: 9px;
    }

    .progress_bar_bg {
        min-width: 180px !important;
    }

    .sub_setting img {
        height: 16px !important;
    }

    .sub_div {
        gap: 2px;
        width: calc(100% - 12px);
        margin: 0 6px;
    }
}

@media (max-width: 320px) {
    .sub_tab, .sub_tab_show {
        font-size: 8px;
    }

    .progress_bar_bg {
        min-width: 160px !important;
    }

    .sub_setting img {
        height: 14px !important;
    }

    .sub_div {
        width: calc(100% - 8px);
        margin: 0 4px;
    }
}

.sub_div * {
    flex-shrink: 0;
}

.sub_div > span:first-child {
    flex-shrink: 1;
}

/* Multiple providers container */
.sub_providers_container {
    display: flex;
    gap: 4px;
    flex: 1;
    min-width: 0;
    overflow-x: auto;
    scrollbar-width: thin;
    cursor: grab;
    user-select: none;
}

.sub_providers_container.no-scroll {
    overflow-x: hidden;
    cursor: default;
}

.sub_providers_container::-webkit-scrollbar {
    height: 4px;
}

.sub_providers_container::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 2px;
}

.sub_providers_container::-webkit-scrollbar-thumb {
    background: #888;
    border-radius: 2px;
}

.sub_providers_container::-webkit-scrollbar-thumb:hover {
    background: #555;
}

.sub_providers_container.dragging {
    cursor: grabbing;
}

.sub_provider_item {
    flex: 0 0 auto;
    width: 100px;
    position: relative;
    min-height: 36px;
    background-color: #f5f5f5;
    border: 1px solid #999999;
    border-radius: 6px;
    display: flex;
    align-items: center;
    justify-content: center;
    box-sizing: border-box;
}

.sub_provider_fill {
    position: absolute;
    left: 0;
    top: 0;
    bottom: 0;
    transition: width 0.3s ease;
    border-radius: 5px;
}

.sub_provider_fill.progress_bar_high {
    background-color: #9edd9e;
}

.sub_provider_fill.progress_bar_medium {
    background-color: #ffc99f;
}

.sub_provider_fill.progress_bar_low {
    background-color: #ffb9b9;
}

.sub_provider_name {
    position: relative;
    z-index: 1;
    font-size: 12px;
    color: #333;
    font-weight: 500;
    text-align: center;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 100%;
    padding: 0 4px;
}

/* Dark mode support */
:root[data-darkmode="true"] .sub_provider_item {
    background-color: #333333;
    border-color: #666666;
}

:root[data-darkmode="true"] .sub_provider_fill.progress_bar_high {
    background-color: #5da05d;
}

:root[data-darkmode="true"] .sub_provider_fill.progress_bar_medium {
    background-color: #cc8550;
}

:root[data-darkmode="true"] .sub_provider_fill.progress_bar_low {
    background-color: #cc6262;
}

:root[data-darkmode="true"] .sub_provider_name {
    color: #e0e0e0;
}

/* Responsive adjustments for multiple providers */
@media (max-width: 1024px) {
    .sub_providers_container {
        gap: 3px;
    }

    .sub_provider_item {
        width: 90px;
    }

    .sub_provider_name {
        font-size: 11px;
    }
}

@media (max-width: 768px) {
    .sub_providers_container {
        gap: 2px;
    }

    .sub_provider_item {
        width: 80px;
        min-height: 32px;
    }

    .sub_provider_name {
        font-size: 10px;
    }
}

@media (max-width: 480px) {
    .sub_provider_item {
        width: 70px;
        min-height: 30px;
        padding: 0 2px;
    }

    .sub_provider_name {
        font-size: 9px;
    }
}

@media (max-width: 320px) {
    .sub_provider_item {
        width: 60px;
        min-height: 28px;
    }

    .sub_provider_name {
        font-size: 8px;
    }
}
</style>

<%
	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">
    <span id='<%=idname%>' class="sub_tab"></span>
    <span class="sub_setting">
        <img id="icon_arrow" src='/luci-static/resources/openclash/img/arrow-clockwise-light.svg' height="20px" title='<%:Refresh%>' alt='<%:Refresh%>' onclick='return sub_info_refresh_<%=idname%>(this)'>
    </span>
    <span class="sub_setting">
        <img id="icon_wrench" src='/luci-static/resources/openclash/img/wrench-light.svg' height="20px" title='<%:Specify URL%>' alt='<%:Specify URL%>' onclick='return set_subinfo_url_<%=idname%>(this,"<%=filename%>")'>
    </span>
</div>

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

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

setTimeout(function(){
    if (isDarkBackground(document.body)) {
        document.documentElement.setAttribute('data-darkmode', 'true');
    };
}, 300);

function progressbar_<%=idname%>(v, m, pc, np, f, t, tr) {
    var screenWidth = window.innerWidth || document.documentElement.clientWidth;
    var fontSize = '12px';
    var minWidth = '220px';
    var topPosition = tr == "null" ? '6px' : '2px';

    if (screenWidth <= 320) {
        fontSize = '8px';
        minWidth = '160px';
        topPosition = tr == "null" ? '8px' : '4px';
    } else if (screenWidth <= 480) {
        fontSize = '9px';
        minWidth = '180px';
        topPosition = tr == "null" ? '7px' : '3px';
    } else if (screenWidth <= 768) {
        fontSize = '10px';
        minWidth = '200px';
        topPosition = tr == "null" ? '6px' : '3px';
    } else if (screenWidth <= 1024) {
        fontSize = '11px';
        minWidth = '220px';
        topPosition = tr == "null" ? '6px' : '2px';
    }

    // 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; min-width: %s; 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>',
        minWidth, pc, fontSize, v, m, pc, t, tr
    );
};

function progressbar_multi_<%=idname%>(providers) {
    if (!providers || !Array.isArray(providers) || providers.length === 0) {
        return '<span>No Providers</span>';
    }

    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>' +
                    '</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 sub_info_refresh_<%=idname%>()
{
	if (s_<%=idname%>) { clearTimeout(s_<%=idname%>);};
	XHR.get('<%=luci.dispatcher.build_url("admin", "services", "openclash", "sub_info_get")%>', {filename: "<%=filename%>"}, function(x, status) {
		if (x && x.status == 200 && status.sub_info != "" && status.sub_info != "No Sub Info Found") {
			retry_<%=idname%> = 0;
			localStorage.setItem("sub_info_<%=filename%>",JSON.stringify(status));
			document.getElementById('<%=idname%>').className = "sub_tab_show";

			if (status.providers && Array.isArray(status.providers) && status.providers.length > 0) {
				if (status.providers.length === 1) {
					var provider = status.providers[0];
					document.getElementById('<%=idname%>').innerHTML = progressbar_<%=idname%>(
						(provider.surplus ? provider.surplus : provider.used),
						(provider.total),
						(provider.percent),
						false, false,
						(provider.expire),
						(provider.day_left)
					);
				} else {
					document.getElementById('<%=idname%>').innerHTML = progressbar_multi_<%=idname%>(status.providers);
				}
			} else {
				document.getElementById('<%=idname%>').innerHTML = progressbar_<%=idname%>(
					(status.surplus ? status.surplus : status.used),
					(status.total),
					(status.percent),
					false, false,
					(status.expire),
					(status.day_left)
				);
			}
		}
		else if ( x && x.status == 200 && status.sub_info == "No Sub Info Found" ) {
			retry_<%=idname%> = 0;
			localStorage.setItem("sub_info_<%=filename%>",JSON.stringify(status));
			document.getElementById('<%=idname%>').className = "sub_tab_show";
			document.getElementById('<%=idname%>').innerHTML = "<span><%:No Sub Info Found%></span>";
		}
		else {
			if (document.getElementById('<%=idname%>').innerHTML == "" || retry_<%=idname%> > 2) {
				document.getElementById('<%=idname%>').className = "sub_tab_show";
				document.getElementById('<%=idname%>').innerHTML = "<span style=color:red><%:Sub Info Get Error%></span>";
			}
			if (retry_<%=idname%> > 2) {
				retry_<%=idname%> = 0;
				localStorage.removeItem("sub_info_<%=filename%>");
			}
			else {
				retry_<%=idname%> ++;
				s_<%=idname%> = setTimeout("sub_info_refresh_<%=idname%>()",1000*120);
				return
			}

		};
		s_<%=idname%> = setTimeout("sub_info_refresh_<%=idname%>()",1000*1800);
	});
};

function sub_info_get_<%=idname%>()
{
	if (localStorage.getItem("sub_info_<%=filename%>")) {
		var save_info = JSON.parse(localStorage.getItem("sub_info_<%=filename%>"));
		document.getElementById('<%=idname%>').className = "sub_tab_show";
		if (save_info.sub_info == "No Sub Info Found") {
			document.getElementById('<%=idname%>').innerHTML = "<span><%:No Sub Info Found%></span>";
		}
		else {
			if (save_info.providers && Array.isArray(save_info.providers) && save_info.providers.length > 0) {
				if (save_info.providers.length === 1) {
					var provider = save_info.providers[0];
					document.getElementById('<%=idname%>').innerHTML = progressbar_<%=idname%>(
						(provider.surplus ? provider.surplus : provider.used),
						(provider.total),
						(provider.percent ? provider.percent : 0),
						false, false,
						(provider.expire),
						(provider.day_left ? provider.day_left : 0)
					);
				} else {
					document.getElementById('<%=idname%>').innerHTML = progressbar_multi_<%=idname%>(save_info.providers);
				}
			} else {
				document.getElementById('<%=idname%>').innerHTML = progressbar_<%=idname%>(
					(save_info.surplus ? save_info.surplus : save_info.used),
					(save_info.total),
					(save_info.percent ? save_info.percent : 0),
					false, false,
					(save_info.expire),
					(save_info.day_left ? save_info.day_left : 0)
				);
			}
		}
	}
	else {
		sub_info_refresh_<%=idname%>();
	};
	s_<%=idname%> = setTimeout("sub_info_refresh_<%=idname%>()",1000*30);
};

function set_subinfo_url_<%=idname%>(btn, filename) {
	var new_url = prompt("<%:Paste the new url of subscribe infos sources here:%>", "");
	if (filename == null || filename == "") {
		return false;
	}
	if (new_url == null) {
		return false;
	}
	XHR.get('<%=luci.dispatcher.build_url("admin", "services", "openclash", "set_subinfo_url")%>', {filename: filename, url: new_url}, function(x, status) {
		if (x && x.status == 200 && status.info == "Success")
		{
			sub_info_refresh_<%=idname%>();
			alert("<%:Specify subscribe infos sources url successfully!%>");
		}
		else if (x && x.status == 200 && status.info == "Delete success")
		{
			sub_info_refresh_<%=idname%>();
			alert("<%:Delete Specify Subscribe infos sources url successfully!%>");
		}
		else
		{
			alert("<%:Specify subscribe infos sources url failed:%>\n" + status.info);
		}
	});
};

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