
//外部文件调用，根据程序返回值来决定是否显示wifi和4g页面
window.addEventListener('DOMContentLoaded', () => {
  const langPara = Array.from(document.querySelectorAll('div > p')).find(p =>
    getComputedStyle(p.parentElement).float === 'right' &&
    (p.textContent.includes('Language') || p.textContent.includes('语言'))
  );

  if (langPara) {
    for (let node of langPara.childNodes) {
      if (node.nodeType === Node.TEXT_NODE && /(Language|语言)/.test(node.textContent)) {
        node.textContent = node.textContent.replace(/(Language|语言)/, 'Language (语言)');
        break;
      }
    }
  }
});

function updatePageTitle() {
    const titleMap = {
        "编码器": "H265/H264编码器",
        "H.264 Encoder": "H.265/H.264 Encoder",
        "Encoder": "H.265/H.264 Encoder"
        // 可以继续添加其他映射关系
    };

    if (titleMap[document.title]) {
        document.title = titleMap[document.title];
    }
}

document.addEventListener('DOMContentLoaded', updatePageTitle);

function ShowWifi()
{
    $.ajax({
        type:"GET",
        url: "/get_sys",
        dataType:"xml",
        cache:false,
        success:function(data){
            var wifi_dev_exist=$(data).find("sys").children("wifi_dev_exist").text();
            var g4_dev_exist=$(data).find("sys").children("g4_dev_exist").text();
            if(wifi_dev_exist==0) {
                $("#wifi").hide();
            }
            else {
                $("#wifi").show();
            }
            if(g4_dev_exist==0){
                $("#g4").hide();
            }
            else{
                $("#g4").show();
            }
        }
    });
}

var max_input = 1;
var max_output = 4;
var port_names = [];
var port_names_raw = [];
var portContextPromise = null;

function getDefaultPortName(index) {
    if (typeof i18n !== 'undefined' && typeof i18n.t === 'function') {
        var text = i18n.t('menu.port', [index + 1]);
        if (text && text !== 'menu.port') {
            return text;
        }
    }
    return 'Port ' + (index + 1);
}

function getPortName(index) {
    if (port_names[index]) {
        return port_names[index];
    }
    return getDefaultPortName(index);
}

function getPortNameRaw(index) {
    if (index >= 0 && index < port_names_raw.length) {
        return port_names_raw[index];
    }
    return "";
}

function fillPortNamesFromXml(xmlData) {
    port_names = [];
    port_names_raw = [];
    for (var i = 0; i < max_input; i++) {
        var name = $(xmlData).find('web_port_name' + i).text();
        port_names_raw.push(name);
        if (!name) {
            name = getDefaultPortName(i);
        }
        port_names.push(name);
    }
}

function fillPortNamesDefault() {
    port_names = [];
    port_names_raw = [];
    for (var i = 0; i < max_input; i++) {
        port_names_raw.push("");
        port_names.push(getDefaultPortName(i));
    }
}

function parseIntSafe(value, fallback) {
    var num = parseInt(value, 10);
    if (isNaN(num)) return fallback;
    return num;
}

function getCurrentInput() {
    var params = new URLSearchParams(window.location.search);
    var input = parseIntSafe(params.get('input'), null);
    if (input === null) {
        input = parseIntSafe(localStorage.getItem('ajax_input'), 0);
    }
    if (input < 0 || input >= max_input) {
        input = 0;
    }
    try {
        localStorage.setItem('ajax_input', input.toString());
    } catch (e) {}
    return input;
}

function getCurrentOutput(paramName) {
    var params = new URLSearchParams(window.location.search);
    var name = paramName || 'output';
    var output = parseIntSafe(params.get(name), null);
    if (output === null) {
        output = parseIntSafe(localStorage.getItem('ajax_output'), 0);
    }
    if (output < 0 || output >= max_output) {
        output = 0;
    }
    try {
        localStorage.setItem('ajax_output', output.toString());
    } catch (e) {}
    return output;
}

function ensurePortContext() {
    if (portContextPromise) return portContextPromise;

    var deferred = $.Deferred();
    portContextPromise = deferred.promise();

    $.ajax({
        type: 'GET',
        url: '/get_status',
        dataType: 'xml',
        cache: false,
        success: function (statusData) {
            var viNodes = $(statusData).find('vi');
            max_input = viNodes.length || 1;
            var vencNodes = viNodes.first().find('venc');
            max_output = vencNodes.length || 1;

            $.ajax({
                type: 'GET',
                url: '/get_adv',
                dataType: 'xml',
                cache: false,
                success: function (advData) {
                    fillPortNamesFromXml(advData);
                    deferred.resolve();
                },
                error: function () {
                    fillPortNamesDefault();
                    deferred.resolve();
                }
            });
        },
        error: function () {
            max_input = 1;
            max_output = 1;
            fillPortNamesDefault();
            deferred.resolve();
        }
    });

    return portContextPromise;
}

// SVG 图标定义
const menuIcons = {
    status: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M5 12l-2 0l9 -9l9 9l-2 0" /><path d="M5 12v7a2 2 0 0 0 2 2h10a2 2 0 0 0 2 -2v-7" /><path d="M9 21v-6a2 2 0 0 1 2 -2h2a2 2 0 0 1 2 2v6" /></svg>',
    encoder: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M4 4m0 2a2 2 0 0 1 2 -2h12a2 2 0 0 1 2 2v12a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2z" /><path d="M8 4l0 16" /><path d="M16 4l0 16" /><path d="M4 8l4 0" /><path d="M4 16l4 0" /><path d="M4 12l16 0" /><path d="M16 8l4 0" /><path d="M16 16l4 0" /></svg>',
    allPorts: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22.4 12.4c0-0.2 0-0.3 0-0.5C22.4 6.2 17.7 1.5 12 1.5 9.1 1.5 6.5 2.7 4.6 4.6l1.1 1.1C7 4.0 9.5 3.0 12 3.0c5 0 9 4 9 9 0 0.2 0 0.3 0 0.5h-1.9l2.5 3.5 2.5-3.5h-1.5v0zM14.2 20.6l-0.5 0.1c-0.6 0.1-1.2 0.2-1.8 0.2-5 0-9-4-9-9 0-0.2 0-0.3 0-0.5h1.9L2.3 7.9 0 11.5h1.5c0 0.2 0 0.3 0 0.5 0 5.8 4.7 10.5 10.5 10.5 2.9 0 5.5-1.2 7.4-3.1l-1.1-1.1c-1.1 1.1-2.5 1.9-4.1 2.3z" /><text x="7.1" y="17" font-size="14" stroke-width="2">A</text></svg>',
    osd: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M13 15c-2 0 -5 1 -5 5" /><path d="M4 11m0 2a2 2 0 0 1 2 -2h5a2 2 0 0 1 2 2v5a2 2 0 0 1 -2 2h-5a2 2 0 0 1 -2 -2z" /><path d="M4 7v-2a1 1 0 0 1 1 -1h2" /><path d="M11 4h2" /><path d="M17 4h2a1 1 0 0 1 1 1v2" /><path d="M20 11v2" /><path d="M20 17v2a1 1 0 0 1 -1 1h-2" /></svg>',
    system: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10.325 4.317c.426 -1.756 2.924 -1.756 3.35 0a1.724 1.724 0 0 0 2.573 1.066c1.543 -.94 3.31 .826 2.37 2.37a1.724 1.724 0 0 0 1.065 2.572c1.756 .426 1.756 2.924 0 3.35a1.724 1.724 0 0 0 -1.066 2.573c.94 1.543 -.826 3.31 -2.37 2.37a1.724 1.724 0 0 0 -2.572 1.065c-.426 1.756 -2.924 1.756 -3.35 0a1.724 1.724 0 0 0 -2.573 -1.066c-1.543 .94 -3.31 -.826 -2.37 -2.37a1.724 1.724 0 0 0 -1.065 -2.572c-1.756 -.426 -1.756 -2.924 0 -3.35a1.724 1.724 0 0 0 1.066 -2.573c-.94 -1.543 .826 -3.31 2.37 -2.37c1 .608 2.296 .07 2.572 -1.065z"/><path d="M9 12a3 3 0 1 0 6 0a3 3 0 0 0 -6 0"/></svg>'
};

function getPortIcon(index) {
    var portLabel = String(index + 1);
    return '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' +
        '<path d="M22.4 12.4c0-0.2 0-0.3 0-0.5C22.4 6.2 17.7 1.5 12 1.5 9.1 1.5 6.5 2.7 4.6 4.6l1.1 1.1C7 4.0 9.5 3.0 12 3.0c5 0 9 4 9 9 0 0.2 0 0.3 0 0.5h-1.9l2.5 3.5 2.5-3.5h-1.5v0zM14.2 20.6l-0.5 0.1c-0.6 0.1-1.2 0.2-1.8 0.2-5 0-9-4-9-9 0-0.2 0-0.3 0-0.5h1.9L2.3 7.9 0 11.5h1.5c0 0.2 0 0.3 0 0.5 0 5.8 4.7 10.5 10.5 10.5 2.9 0 5.5-1.2 7.4-3.1l-1.1-1.1c-1.1 1.1-2.5 1.9-4.1 2.3z" />' +
        '<text x="7.5" y="17.3" font-size="14" stroke-width="2">' + portLabel + '</text>' +
        '</svg>';
}

function getStreamLabel(index) {
    if (index === 0) return i18n.t('menu.mainStream');
    if (index === 1) return i18n.t('menu.subStream1');
    if (index === 2) return i18n.t('menu.subStream2');
    if (index === 3) return i18n.t('menu.subStream3');
    return i18n.t('menu.subStream1');
}

function getStreamKey(prefix, index) {
    if (index === 0) return prefix + 'Main';
    return prefix + 'Sub' + index;
}

/**
 * 显示菜单（统一接口）
 * @param {string} first - 一级菜单标识 (index, port-0.., port-all, system)
 * @param {string} second - 二级菜单标识
 *
 * 注意：为了向后兼容，第一个参数如果是数字则忽略（旧代码传 0/1 表示语言）
 */
function showMenu(first, second) {
    if (typeof first === 'number') {
        first = second;
        second = arguments[2] || '';
    }
    ensurePortContext().done(function () {
        generateMenu(first, second);
    });
}

/**
 * 生成菜单 HTML
 * 使用 i18n.t() 获取翻译文本
 */
function generateMenu(first, second) {
    const t = key => i18n.t(key);

    let menu = '<ul class="navbar-nav pt-lg-3">';

    // 状态显示 (无子菜单)
    menu += `<li class="nav-item">
        <a class="nav-link${first === 'index' ? ' active' : ''}" href="index.html">
            <span class="nav-link-icon">${menuIcons.status}</span>
            <span class="nav-link-title">${t('menu.status')}</span>
        </a>
    </li>`;

    // 端口菜单
    for (var i = 0; i < max_input; i++) {
        var groupId = 'port-' + i;
        var isActive = first === groupId;
        var portName = getPortName(i);
        var dropdownClass = isActive ? ' show' : '';
        var menuItems = '';
        var osdPrefix = 'OSD-';
        for (var output = 0; output < max_output; output++) {
            var itemKey = getStreamKey('Output', output);
            var isItemActive = second === itemKey ? ' active' : '';
            menuItems += `<a class="dropdown-item${isItemActive}" href="Output.html?input=${i}&output=${output}">${getStreamLabel(output)}</a>`;
        }
        for (var osdOutput = 0; osdOutput < max_output; osdOutput++) {
            var osdKey = getStreamKey('OutputOsd', osdOutput);
            var osdActive = second === osdKey ? ' active' : '';
            menuItems += `<a class="dropdown-item${osdActive}" href="OutputOsd.html?input=${i}&output=${osdOutput}">${osdPrefix}${getStreamLabel(osdOutput)}</a>`;
        }
        menuItems += `<a class="dropdown-item${second === 'LogoUpload' ? ' active' : ''}" href="LogoUpload.html?input=${i}">${t('menu.logoUpload')}</a>`;
        menuItems += `<a class="dropdown-item${second === 'VideoSet' ? ' active' : ''}" href="VideoSet.html?input=${i}">${t('menu.videoSettings')}</a>`;
        menuItems += `<a class="dropdown-item${second === 'AudioSet' ? ' active' : ''}" href="AudioSet.html?input=${i}">${t('menu.audioSettings')}</a>`;

        if (typeof i18n !== 'undefined' && typeof i18n.isZh === 'function' && i18n.isZh()) {
            menuItems += `<a class="dropdown-item${second === 'GB28181' ? ' active' : ''}" href="GB28181.html?input=${i}">${t('menu.gb28181')}</a>`;
        }

        menu += `<li class="nav-item${isActive ? ' active' : ''} dropdown">
            <a class="nav-link dropdown-toggle${dropdownClass}" href="Output.html?input=${i}&output=0" aria-expanded="${isActive}">
                <span class="nav-link-icon">${getPortIcon(i)}</span>
                <span class="nav-link-title">${portName}</span>
            </a>
            <div class="dropdown-menu${dropdownClass}">
                ${menuItems}
            </div>
        </li>`;
    }

    // 配置所有端口
    var allActive = first === 'port-all';
    var allDropdownClass = allActive ? ' show' : '';
    var allMenuItems = '';
    for (var allOutput = 0; allOutput < max_output; allOutput++) {
        var allKey = getStreamKey('OutputAll', allOutput);
        var allItemActive = second === allKey ? ' active' : '';
        allMenuItems += `<a class="dropdown-item${allItemActive}" href="OutputAll.html?output=${allOutput}">${getStreamLabel(allOutput)}</a>`;
    }
    allMenuItems += `<a class="dropdown-item${second === 'VideoSetAll' ? ' active' : ''}" href="VideoSetAll.html">${t('menu.videoSettings')}</a>`;
    allMenuItems += `<a class="dropdown-item${second === 'AudioSetAll' ? ' active' : ''}" href="AudioSetAll.html">${t('menu.audioSettings')}</a>`;

    menu += `<li class="nav-item${allActive ? ' active' : ''} dropdown">
        <a class="nav-link dropdown-toggle${allDropdownClass}" href="OutputAll.html?output=0" aria-expanded="${allActive}">
            <span class="nav-link-icon">${menuIcons.allPorts}</span>
            <span class="nav-link-title">${t('menu.allPorts')}</span>
        </a>
        <div class="dropdown-menu${allDropdownClass}">
            ${allMenuItems}
        </div>
    </li>`;

    // 系统设置 (有子菜单)
    menu += `<li class="nav-item${first === 'system' ? ' active' : ''} dropdown">
        <a class="nav-link dropdown-toggle${first === 'system' ? ' show' : ''}" href="NetworkSet.html" aria-expanded="${first === 'system'}">
            <span class="nav-link-icon">${menuIcons.system}</span>
            <span class="nav-link-title">${t('menu.system')}</span>
        </a>
        <div class="dropdown-menu${first === 'system' ? ' show' : ''}">
            <a class="dropdown-item${second === 'NetworkSet' ? ' active' : ''}" href="NetworkSet.html">${t('menu.network')}</a>
            <a class="dropdown-item${second === 'AdvancedSet' ? ' active' : ''}" href="AdvancedSet.html">${t('menu.advancedSettings')}</a>
            <a class="dropdown-item${second === 'RecordSet' ? ' active' : ''}" href="RecordSet.html">${t('menu.record')}</a>
            <a class="dropdown-item${second === 'WifiSet' ? ' active' : ''}" id="wifi" href="WifiSet.html" style="display:none;">${t('menu.wifi')}</a>
            <a class="dropdown-item${second === 'G4Set' ? ' active' : ''}" id="g4" href="G4Set.html" style="display:none;">${t('menu.g4')}</a>
            <a class="dropdown-item${second === 'PasswordSet' ? ' active' : ''}" href="PasswordSet.html">${t('menu.password')}</a>
            <a class="dropdown-item${second === 'SerialSet' ? ' active' : ''}" href="SerialSet.html">${t('menu.serial')}</a>
            <a class="dropdown-item${second === 'SystemUpdate' ? ' active' : ''}" href="SystemUpdate.html">${t('menu.update')}</a>
            <a class="dropdown-item${second === 'Reboot' ? ' active' : ''}" href="Reboot.html">${t('menu.reboot')}</a>
            <a class="dropdown-item${second === 'Restart' ? ' active' : ''}" href="Restart.html">${t('menu.timedReboot')}</a>
            <a class="dropdown-item${second === 'Reset' ? ' active' : ''}" href="Reset.html">${t('menu.factoryReset')}</a>
        </div>
    </li>`;

    menu += '</ul>';
    $("#mainnav_div").html(menu);
}

// 保留原函数名以向后兼容（旧页面可能直接调用）
function get_menu_chn(first, second) {
    showMenu(first, second);
}

function get_menu_eng(first, second) {
    showMenu(first, second);
}

function isAppleDevice() {
  const userAgent = navigator.userAgent.toLowerCase();
  return (
    userAgent.includes('mac os x') ||    // macOS
    userAgent.includes('iphone') ||      // iOS (iPhone)
    userAgent.includes('ipad') ||        // iOS (iPad)
    userAgent.includes('ipod')           // iOS (iPod)
  );
}
