/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable prefer-const */

const resources = {
  en: {
    connected: 'Connected',
    bitrate: 'Bitrate',
    button_text_download_diagnosis_report: 'Export diagnosis report',
    button_text_get_diagnosis_report: 'Start diagnosis',
    button_text_get_diagnosis_report_loading: 'Starting diagnosis...',
    create_local_audio_track_failed: 'Failed to create local audio track',
    create_local_audio_track_success: 'Successfully created local audio track',
    destroy_local_audio_track_failed: 'Failed to destroy local audio track',
    destroy_local_audio_track_success: 'Successfully destroyed local audio track',
    diagnosis_report_card_title_overview: 'Diagnosis overview',
    diagnosis_report_card_title_stream: 'Diagnosis for video stream {{streamId}}',
    diagnosis_report_diag_error: 'Error in diagnosis',
    diagnosis_report_field_mqtt_connect: 'Field device MQTT connection checking result',
    diagnosis_report_field_pid: 'Field device PID',
    diagnosis_report_license_check: 'Field device license checking result',
    diagnosis_report_media_connect: 'Media connection checking result',
    diagnosis_report_remote_mqtt_connect: 'Remote device MQTT connection checking result',
    diagnosis_report_service_mode: 'Service mode',
    diagnosis_report_signal_connect: 'Signal connection checking result',
    diagnosis_report_video_capture: 'Video capture checking result',
    diagnosis_report_video_encode: 'Video encoding checking result',
    diagnosis_report_video_decode: 'Video decoding checking result',
    diagnosis_report_video_transfer: 'Video transfering checking result',
    end_connection_failed: 'Failed to disconnect from the field devices',
    end_connection_success: 'Successfully disconnected from the field devices',
    error_description_already_created_audio_track: 'Audio track already created',
    error_description_already_published_audio_track: 'Audio track already published',
    error_description_empty_field_device_id_input: 'Please input field device id(s)',
    error_description_empty_messages: 'Please input message',
    error_description_empty_stream_id_input: 'Please input video stream id(s)',
    error_description_no_audio_track: 'No available audio track',
    error_description_no_connected_devices: 'Please connect to field devices first',
    error_description_no_master_permission: 'Please request master permission first',
    error_description_no_subscibed_video_stream: 'Please subscribe video stream(s) first',
    error_description_no_published_audio_stream: 'Please publish audio stream first',
    error_description_not_logged_in: 'Please login first',
    error_title: 'Error',
    error_code_20101: 'Username or password incorrect',
    error_code_20102: 'Same user login rejected',
    error_code_20199: 'Connection failed',
    error_code_unknown: 'Unknown error ({{code}})',
    field_device: 'Field device',
    frame_rate: 'Frame rate',
    gateway_status: 'Status',
    gateway_status_online: 'Online',
    gateway_status_unknown: 'Unknown',
    gateway_stream_count: 'Streams',
    gateway_version: 'Version',
    generate_temp_credentials_error_empty_shared_key: 'Please input project shared key',
    generate_temp_credentials_error_empty_project_id:
      'Project ID is required in public cloud mode. Please input project ID in the generator or the login form.',
    generate_temp_credentials_error_empty_field_device_id: 'Please input field device ID',
    generate_temp_credentials_error_empty_remote_device_id: 'Please input remote device ID',
    generate_temp_credentials_error_invalid_expire_time: 'Please input valid expiration time',
    generate_temp_credentials_failed: 'Failed to generate temporary credentials: {{error}}',
    generate_temp_credentials_success:
      'Temporary credentials generated and synced to input fields<br/>Expiration time: {{expireTime}}',
    get_audio_device_list_failed: 'Failed to get local audio device list',
    get_audio_device_list_success: 'Successfully got local audio device list',
    get_diagnosis_report_failed: 'Failed to get diagnosis report',
    get_diagnosis_report_success: 'Successfully got diagnosis report',
    lag_k100: '100ms lag rate',
    lag_k150: '150ms lag rate',
    latency: 'Latency',
    login_error_auth: 'Wrong username or password',
    login_error_multisession: 'This user already has a session by other device',
    login_failed: 'Login failed',
    login_success: 'Login success',
    login_status_closed: 'Not logged in',
    login_status_failed: 'Login failed',
    login_status_kicked: 'Kicked out',
    login_status_loading: 'Logging in...',
    login_status_success: 'Logged in',
    lost_rate: 'Lost rate',
    mute_local_audio_track_failed: 'Failed to mute local audio track',
    mute_local_audio_track_success: 'Successfully muted local audio track',
    not_connected: 'Not connected',
    publish_local_audio_track_failed: 'Failed to publish local audio track',
    publish_local_audio_track_success: 'Successfully published local audio track',
    query_gateway_info_failed: 'Failed to query gateway info',
    query_gateway_info_loading: 'Querying...',
    query_gateway_info_success: 'Successfully queried gateway info',
    remote_device: 'Remote device',
    set_session_permission_token_error_empty: 'Please input session permission token',
    set_session_permission_token_success: 'Session permission token set successfully',
    remote_media_video_stream_title: 'Video stream {{streamId}}',
    remote_media_video_stream_title_with_latency: 'Video stream {{streamId}} | Latency: {{latency}}ms',
    request_permission_failed: 'Failed to request permission',
    request_permission_success: 'Successfully requested permission',
    send_message_failed: 'Failed to send message',
    send_message_success: 'Successfully sent message',
    start_connection_failed: 'Failed to connect to the field devices',
    start_connection_success: 'Successfully connected to the field devices',
    success_title: 'Success',
    unmute_local_audio_track_failed: 'Failed to unmute local audio track',
    unmute_local_audio_track_success: 'Successfully unmuted local audio track',
    unpublish_local_audio_track_failed: 'Failed to unpublish local audio track',
    unpublish_local_audio_track_success: 'Successfully unpublished local audio track',
    update_gateway_list_failed: 'Failed to update gateway list',
    video_buffer_control_title: 'Video Buffer Settings (Global)',
    video_buffer_method_label: 'Control Method:',
    video_buffer_target_label: 'Target (ms):',
    video_buffer_target_placeholder: 'Leave blank to use default',
    video_buffer_hint:
      'After setting, it will apply to all video streams of field devices. Leave the input box blank to restore the default value.',
    video_buffer_status_waiting: 'Waiting for input...',
    video_buffer_status_default: 'Using default value',
    video_buffer_status_invalid: 'Invalid value',
    video_buffer_status_no_devices: 'No connected devices',
    video_buffer_status_no_streams: 'No video streams',
    video_buffer_status_restored: '✓ Restored {{count}} stream(s)',
    video_buffer_status_partial_restored: 'Partially restored {{success}}/{{total}}',
    video_buffer_status_applied: '✓ Applied to {{count}} stream(s)',
    video_buffer_status_partial_success: 'Partially successful {{success}}/{{total}}',
    video_buffer_status_failed: 'Failed to apply (browser not supported)',
    error_description_mqtt_channel_error: 'This error should not occur on MQTT channel: {{message}}',
    error_field_device_id_required: 'Please enter field device ID first',
    video_buffer_method_chrome_recommended: 'Recommended for Chrome',
    log_collector_title: 'Log Collector',
    log_collector_session_id: 'Session ID',
    log_collector_log_count: 'Logs',
    log_collector_description_1: 'This tool automatically collects all console logs (including SDK logs)',
    log_collector_description_2: 'Logs are stored in browser IndexedDB, each page session is stored independently',
    log_collector_description_3: 'Logs will be automatically cleared when the page is closed',
    log_collector_button_export: 'Export Logs',
    log_collector_button_clear: 'Clear Logs',
    log_collector_button_refresh: 'Refresh Count',
    log_collector_hint: 'Tip: If you encounter a problem, click "Export Logs" to save the log file for debugging',
    log_collector_export_no_logs: 'No logs to export',
    log_collector_export_success: 'Successfully exported {{count}} logs',
    log_collector_export_failed: 'Failed to export logs: {{error}}',
    log_collector_clear_confirm: 'Are you sure you want to clear all logs for the current session?',
    log_collector_clear_success: 'Logs cleared',
    log_collector_clear_failed: 'Failed to clear logs: {{error}}',
    stream_stats_card_title: 'Per-Stream Stats',
    stream_stats_waiting: 'Waiting for stats...',
    stream_stats_col_stream_id: 'streamId',
    stream_stats_col_jitter_buffer: 'current jitterBuffer(ms)',
    stream_stats_col_jitter_buffer_target: 'jitterBufferTarget(ms)',
    stream_stats_col_rtt: 'rtt(ms)',
    stream_stats_col_lost: 'packet loss',
    stream_stats_col_fps: 'fps',
    stream_stats_col_set_target: 'Update target(ms)',
    stream_stats_btn_apply: 'Apply',
    stream_stats_set_success: 'Apply ok',
    stream_stats_set_failed: 'Apply failed',
    stream_stats_method_label: 'Method:',
    stream_stats_method_hint: 'Switch API used by row-level Apply buttons',
    stream_stats_input_placeholder: 'input value',
    stream_stats_input_empty: 'Please input a target value first',
    stream_stats_apply_all_label: 'Apply to all streams:',
    stream_stats_btn_apply_all: 'Apply to all',
    stream_stats_apply_all_hint: 'Batch-apply the input value to every video stream of this field device',
    stream_stats_apply_all_no_streams: 'No subscribed video streams yet',
  },
  zh: {
    connected: '已连接',
    bitrate: '码率',
    button_text_download_diagnosis_report: '导出诊断报告',
    button_text_get_diagnosis_report: '开始诊断',
    button_text_get_diagnosis_report_loading: '正在进行诊断...',
    create_local_audio_track_failed: '创建本地音频轨道失败',
    create_local_audio_track_success: '成功创建本地音频轨道',
    destroy_local_audio_track_failed: '销毁本地音频轨道失败',
    destroy_local_audio_track_success: '成功销毁本地音频轨道',
    diagnosis_report_card_title_overview: '诊断概览',
    diagnosis_report_card_title_stream: '视频流 {{streamId}} 诊断结果',
    diagnosis_report_diag_error: '诊断异常',
    diagnosis_report_field_mqtt_connect: '现场设备 MQTT 连接检查结果',
    diagnosis_report_field_pid: '现场设备 PID',
    diagnosis_report_license_check: '现场设备授权检查结果',
    diagnosis_report_media_connect: '媒体连接检查结果',
    diagnosis_report_remote_mqtt_connect: '远程设备 MQTT 连接检查结果',
    diagnosis_report_service_mode: '服务模式',
    diagnosis_report_signal_connect: '信令连接检查结果',
    diagnosis_report_video_capture: '视频采集检查结果',
    diagnosis_report_video_encode: '视频编码检查结果',
    diagnosis_report_video_decode: '视频解码检查结果',
    diagnosis_report_video_transfer: '视频传输检查结果',
    end_connection_failed: '无法与现场设备断开连接',
    end_connection_success: '成功断开与现场设备的连接',
    error_description_already_created_audio_track: '本地音频轨道已创建',
    error_description_already_published_audio_track: '本地音频轨道已推流',
    error_description_empty_field_device_id_input: '请输入现场设备 ID',
    error_description_empty_messages: '请输入消息',
    error_description_empty_stream_id_input: '请输入视频流 ID',
    error_description_no_audio_track: '没有可用的音频轨道',
    error_description_no_connected_devices: '请先连接到现场设备',
    error_description_no_master_permission: '请先请求 Master 权限',
    error_description_no_subscibed_video_stream: '请先订阅视频流',
    error_description_no_published_audio_stream: '请先发布音频流',
    error_description_not_logged_in: '请先登录',
    error_title: '错误',
    error_code_20101: '用户名或密码错误',
    error_code_20102: '同名登录被拒绝',
    error_code_20199: '连接失败',
    error_code_unknown: '未知错误 ({{code}})',
    field_device: '现场设备',
    frame_rate: '帧率',
    gateway_status: '状态',
    gateway_status_online: '在线',
    gateway_status_unknown: '未知',
    gateway_stream_count: '流数',
    gateway_version: '版本',
    generate_temp_credentials_error_empty_shared_key: '请输入项目共享密钥',
    generate_temp_credentials_error_empty_project_id: '公有云模式下需要项目 ID，请在生成工具或登录表单中输入项目 ID',
    generate_temp_credentials_error_empty_field_device_id: '请输入现场设备 ID',
    generate_temp_credentials_error_empty_remote_device_id: '请输入远端设备 ID',
    generate_temp_credentials_error_invalid_expire_time: '请输入有效的过期时间',
    generate_temp_credentials_failed: '生成临时凭证失败: {{error}}',
    generate_temp_credentials_success: '临时凭证已生成并同步到对应输入框<br/>过期时间: {{expireTime}}',
    get_audio_device_list_failed: '获取本地音频设备列表失败',
    get_audio_device_list_success: '成功获取本地音频设备列表',
    get_diagnosis_report_failed: '获取诊断报告失败',
    get_diagnosis_report_success: '成功获取诊断报告',
    lag_k100: '100ms 卡顿率',
    lag_k150: '150ms 卡顿率',
    latency: '延迟',
    login_error_auth: '用户名或密码错误',
    login_error_multisession: '该用户已在其他设备登录',
    login_failed: '登录失败',
    login_success: '登录成功',
    login_status_closed: '未登录',
    login_status_failed: '登录失败',
    login_status_kicked: '已被踢出',
    login_status_loading: '登录中...',
    login_status_success: '已登录',
    lost_rate: '丢包率',
    mute_local_audio_track_failed: '静音本地音频轨道失败',
    mute_local_audio_track_success: '成功静音本地音频轨道',
    publish_local_audio_track_failed: '发布本地音频轨道失败',
    publish_local_audio_track_success: '成功发布本地音频轨道',
    not_connected: '未连接',
    query_gateway_info_failed: '查询设备信息失败',
    query_gateway_info_loading: '查询中...',
    query_gateway_info_success: '查询设备信息成功',
    remote_device: '远程设备',
    set_session_permission_token_error_empty: '请输入临时授权码',
    set_session_permission_token_success: '临时授权码设置成功',
    remote_media_video_stream_title: '视频流 {{streamId}}',
    remote_media_video_stream_title_with_latency: '视频流 {{streamId}} | 延迟: {{latency}}ms',
    request_permission_failed: '请求权限失败',
    request_permission_success: '请求权限成功',
    send_message_failed: '发送消息失败',
    send_message_success: '发送消息成功',
    start_connection_failed: '连接现场设备失败',
    start_connection_success: '成功连接到现场设备',
    success_title: '成功',
    update_gateway_list_failed: '更新网关列表失败',
    unmute_local_audio_track_failed: '取消静音本地音频轨道失败',
    unmute_local_audio_track_success: '成功取消静音本地音频轨道',
    unpublish_local_audio_track_failed: '取消发布本地音频轨道失败',
    unpublish_local_audio_track_success: '成功取消发布本地音频轨道',
    video_buffer_control_title: '视频流缓冲区设置（全局）',
    video_buffer_method_label: '控制方式：',
    video_buffer_target_label: '目标值(ms)：',
    video_buffer_target_placeholder: '留空使用默认值',
    video_buffer_hint: '设置后对所有现场设备的视频流生效，留空输入框可还原为默认值',
    video_buffer_status_waiting: '等待输入...',
    video_buffer_status_default: '使用默认值',
    video_buffer_status_invalid: '无效的数值',
    video_buffer_status_no_devices: '无连接的设备',
    video_buffer_status_no_streams: '无视频流',
    video_buffer_status_restored: '✓ 已还原 {{count}} 个流',
    video_buffer_status_partial_restored: '部分还原 {{success}}/{{total}}',
    video_buffer_status_applied: '✓ 已应用到 {{count}} 个流',
    video_buffer_status_partial_success: '部分成功 {{success}}/{{total}}',
    video_buffer_status_failed: '应用失败（浏览器不支持）',
    error_description_mqtt_channel_error: 'MQTT 通道不应该出现此错误：{{message}}',
    error_field_device_id_required: '请先输入现场设备 ID',
    video_buffer_method_chrome_recommended: 'Chrome 推荐',
    log_collector_title: '日志收集工具',
    log_collector_session_id: '会话ID',
    log_collector_log_count: '日志数',
    log_collector_description_1: '本工具会自动收集页面的所有 console 日志（包括 SDK 日志）',
    log_collector_description_2: '日志存储在浏览器 IndexedDB 中，每个页面会话独立存储',
    log_collector_description_3: '关闭页面时会自动清除该会话的日志',
    log_collector_button_export: '导出日志',
    log_collector_button_clear: '清除日志',
    log_collector_button_refresh: '刷新计数',
    log_collector_hint: '提示：如果遇到问题，可以点击"导出日志"保存日志文件以供调试使用',
    log_collector_export_no_logs: '没有可导出的日志',
    log_collector_export_success: '成功导出 {{count}} 条日志',
    log_collector_export_failed: '导出日志失败: {{error}}',
    log_collector_clear_confirm: '确定要清除当前会话的所有日志吗？',
    log_collector_clear_success: '日志已清除',
    log_collector_clear_failed: '清除日志失败: {{error}}',
    stream_stats_card_title: '每路视频流状态',
    stream_stats_waiting: '等待统计数据...',
    stream_stats_col_stream_id: '流号',
    stream_stats_col_jitter_buffer: '当前抖动缓冲(ms)',
    stream_stats_col_jitter_buffer_target: '目标抖动缓冲(ms)',
    stream_stats_col_rtt: 'RTT(ms)',
    stream_stats_col_lost: '丢包率',
    stream_stats_col_fps: '帧率',
    stream_stats_col_set_target: '更新目标值(ms)',
    stream_stats_btn_apply: '应用',
    stream_stats_set_success: '设置成功',
    stream_stats_set_failed: '设置失败',
    stream_stats_method_label: '控制方式：',
    stream_stats_method_hint: '切换每行"应用"按钮调用的 API',
    stream_stats_input_placeholder: '输入数值',
    stream_stats_input_empty: '请先输入目标值',
    stream_stats_apply_all_label: '应用到所有流：',
    stream_stats_btn_apply_all: '应用到所有流',
    stream_stats_apply_all_hint: '将输入值批量应用到当前现场设备的所有视频流',
    stream_stats_apply_all_no_streams: '当前未订阅任何视频流',
  },
};

let currentLang = 'zh';

function t(key, variables = {}) {
  const languagePack = resources[currentLang];
  let text = languagePack?.[key] || key;

  Object.keys(variables).forEach((varKey) => {
    const placeholder = `{{${varKey}}}`;
    text = text.replace(placeholder, variables[varKey]);
  });

  return text;
}

function updatePageContent() {
  const elements = document.querySelectorAll('[data-i18n]');
  elements.forEach((element) => {
    const key = element.getAttribute('data-i18n');
    element.textContent = t(key);
  });
}

function setLanguage(lang) {
  if (resources[lang]) {
    currentLang = lang;
    updatePageContent();
  }
}

// Export to window for global access
window.t = t;
window.updatePageContent = updatePageContent;
window.setLanguage = setLanguage;
