(function () {
  const progressFill = document.getElementById('progressFill');
  const percent = document.getElementById('percent');
  const status = document.getElementById('status');
  const detail = document.getElementById('detail');
  const stageName = document.getElementById('stageName');
  const stateDot = document.getElementById('stateDot');
  const closeButton = document.getElementById('closeButton');

  let currentProgress = 0;
  let targetProgress = 0;
  let reducedMotion = false;
  let frame = 0;

  function clamp(value, min, max) {
    return Math.max(min, Math.min(max, Number.isFinite(value) ? value : min));
  }

  function setProgress(value) {
    targetProgress = clamp(value, 0, 100);
    if (reducedMotion) {
      currentProgress = targetProgress;
      renderProgress();
      return;
    }

    if (!frame) {
      frame = requestAnimationFrame(tick);
    }
  }

  function tick() {
    const diff = targetProgress - currentProgress;
    if (Math.abs(diff) > 0.15) {
      currentProgress += diff * 0.12;
      renderProgress();
      frame = requestAnimationFrame(tick);
      return;
    }

    currentProgress = targetProgress;
    renderProgress();
    frame = 0;
  }

  function renderProgress() {
    const value = clamp(currentProgress, 0, 100);
    progressFill.style.width = `${value}%`;
    percent.textContent = `${Math.floor(value)}%`;
  }

  function applySeverity(severity) {
    stateDot.classList.remove('warning', 'danger');
    if (severity === 'critical' || severity === 'danger' || severity === 'error') {
      stateDot.classList.add('danger');
    } else if (severity === 'warning') {
      stateDot.classList.add('warning');
    }
  }

  function applyTheme(theme) {
    const normalized = String(theme || '').toLowerCase();
    if (normalized === 'dark' || normalized === 'light') {
      document.body.dataset.theme = normalized;
    }
  }

  function handleMessage(message) {
    if (!message || typeof message !== 'object') {
      return;
    }

    if (message.theme) {
      applyTheme(message.theme);
    }

    if (typeof message.reducedMotion === 'boolean') {
      reducedMotion = message.reducedMotion;
      document.body.classList.toggle('reducedMotion', reducedMotion);
    }

    switch (message.type) {
      case 'progress':
        stageName.textContent = message.stageName || '启动自检';
        status.textContent = message.status || message.stageName || '正在检查...';
        detail.textContent = message.detail || `${message.stepIndex || 0}/${message.stepCount || 0}`;
        applySeverity(message.severity);
        setProgress(message.isIndeterminate ? targetProgress : message.progress);
        break;
      case 'complete':
        stageName.textContent = '启动自检完成';
        status.textContent = message.hasIssues ? '发现问题' : '未发现问题';
        detail.textContent = message.hasIssues
          ? `发现 ${message.visibleIssueCount || 0} 个需要关注的问题，详情可在结果页查看。`
          : '本次启动预检未发现需要处理的问题。';
        applySeverity(message.hasIssues ? 'warning' : 'info');
        setProgress(100);
        break;
      case 'fatal':
        stageName.textContent = '启动失败';
        status.textContent = message.status || '启动初始化失败';
        detail.textContent = message.detail || '请查看启动日志或重新安装。';
        applySeverity('critical');
        setProgress(100);
        closeButton.classList.add('visible');
        break;
      case 'themeChanged':
        applyTheme(message.theme);
        break;
      case 'showClose':
        closeButton.classList.add('visible');
        break;
      default:
        break;
    }
  }

  window.chrome?.webview?.addEventListener('message', event => handleMessage(event.data));
  closeButton.addEventListener('click', () => {
    window.chrome?.webview?.postMessage({ type: 'closeRequested' });
  });

  const prefersReduced = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
  reducedMotion = prefersReduced;
  renderProgress();
  window.chrome?.webview?.postMessage({ type: 'ready' });
})();
