(async () => {
  const jobId = new URL(location.href).searchParams.get('bili_summary_job');
  if (!jobId || sessionStorage.getItem('biliSummaryKimiDismissed') === jobId) return;

  const host = document.createElement('div');
  host.style.cssText = 'all:initial;position:fixed;right:18px;bottom:18px;z-index:2147483647';
  const shadow = host.attachShadow({ mode: 'closed' });
  shadow.innerHTML = `
    <style>
      .popup{box-sizing:border-box;width:min(360px,calc(100vw - 28px));padding:14px 16px;border:1px solid #e3e5e7;border-radius:8px;background:#fff;color:#18191c;box-shadow:0 8px 28px rgba(0,0,0,.18);font:13px/1.55 system-ui,-apple-system,"Segoe UI",sans-serif}
      .header{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:8px;font-weight:700}
      .close{flex:0 0 28px;width:28px;height:28px;padding:0;border:0;border-radius:4px;background:transparent;color:#61666d;font:20px/1 system-ui;cursor:pointer}
      .close:hover{background:#f1f2f3;color:#18191c}.message{overflow-wrap:anywhere}.notice{display:block;margin-top:6px;color:#9499a0;font-size:11px;line-height:1.5}
      .percent{margin-top:4px;color:#9499a0;font-size:12px;text-align:right}
      .track{height:4px;margin-top:7px;overflow:hidden;border-radius:2px;background:#e3e5e7}.fill{height:100%;width:0;background:#00aeec;transition:width .2s ease}
      .instructions{display:none;margin:10px 0 0;padding-top:10px;border-top:1px solid #e3e5e7;color:#61666d}.popup.complete .instructions{display:block}.popup.error .track,.popup.error .percent{display:none}
    </style>
    <section class="popup" role="status" aria-live="polite">
      <div class="header"><span>Kimi总结</span><button class="close" type="button" aria-label="关闭">&times;</button></div>
      <div class="message">正在准备音频下载...</div><div class="percent">0%</div>
      <div class="track"><div class="fill"></div></div>
      <p class="instructions">点击对话框左下角“+”，从收藏夹所在文件夹选择并发送该音频文件；然后在对话框中直接粘贴并发送提示词（提示词已复制到剪贴板）。</p>
    </section>`;
  document.documentElement.appendChild(host);

  const popup = shadow.querySelector('.popup');
  const message = shadow.querySelector('.message');
  const percent = shadow.querySelector('.percent');
  const fill = shadow.querySelector('.fill');
  const close = () => {
    sessionStorage.setItem('biliSummaryKimiDismissed', jobId);
    chrome.storage.onChanged.removeListener(onStorageChanged);
    host.remove();
  };
  const escapeHtml = (value) => String(value ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
  const render = (status) => {
    if (!status || status.jobId !== jobId) return;
    const value = Math.max(0, Math.min(100, Math.round(Number(status.percent || 0))));
    message.innerHTML = escapeHtml(status.message) + (status.notice ? `<span class="notice">${escapeHtml(status.notice)}</span>` : '');
    percent.textContent = `${value}%`;
    fill.style.width = `${value}%`;
    popup.classList.toggle('complete', Boolean(status.complete));
    popup.classList.toggle('error', Boolean(status.error));
  };
  function onStorageChanged(changes, areaName) {
    if (areaName === 'local' && changes.kimiSummaryStatus) render(changes.kimiSummaryStatus.newValue);
  }

  shadow.querySelector('.close').addEventListener('click', close);
  chrome.storage.onChanged.addListener(onStorageChanged);
  const stored = await chrome.storage.local.get({ kimiSummaryStatus: null });
  render(stored.kimiSummaryStatus);
})();
