/* ════════════ Daily Report ════════════ */
var dailyReportMd = '';

function showDailyReport() {
  if (!currentProject) return;
  var overlay = document.getElementById('daily-report-overlay');
  var dateInput = document.getElementById('daily-report-date');
  var today = new Date().toISOString().slice(0, 10);
  dateInput.value = today;
  overlay.classList.add('active');
  loadDailyReport();
}

function loadDailyReport() {
  var date = document.getElementById('daily-report-date').value;
  var content = document.getElementById('daily-report-content');
  content.innerHTML = '<div class="analysis-skeleton"><div class="skeleton-line"></div><div class="skeleton-line"></div><div class="skeleton-line"></div></div>';

  fetch(API + '/projects/' + currentProject + '/daily-report?date=' + date)
    .then(function(r) { return r.json(); })
    .then(function(j) {
      if (!j.success) { content.innerHTML = '<p style="color:var(--danger)">加载失败: ' + escHtml(j.error) + '</p>'; return; }
      var d = j.data;
      dailyReportMd = d.markdown || '';
      if (d.node_count === 0) {
        content.innerHTML = '<div class="analysis-empty"><div class="empty-title">本日暂无记录</div><div class="empty-desc">' + d.date + ' 没有添加任何节点。</div></div>';
        return;
      }
      if (typeof marked !== 'undefined' && marked.parse) {
        content.innerHTML = marked.parse(dailyReportMd);
        if (typeof hljs !== 'undefined') {
          content.querySelectorAll('pre code').forEach(function(b) { hljs.highlightElement(b); });
        }
      } else {
        content.innerHTML = '<pre style="white-space:pre-wrap;font-family:var(--font-mono);font-size:13px;color:var(--text-primary);line-height:1.7">' + escHtml(dailyReportMd) + '</pre>';
      }
    })
    .catch(function(e) { content.innerHTML = '<p style="color:var(--danger)">请求失败: ' + escHtml(e.message) + '</p>'; });
}

function copyDailyReport() {
  navigator.clipboard.writeText(dailyReportMd).then(function() {
    toast('已复制到剪贴板');
  });
}

function downloadDailyReport() {
  var date = document.getElementById('daily-report-date').value;
  var blob = new Blob([dailyReportMd], {type:'text/markdown'});
  var a = document.createElement('a');
  a.href = URL.createObjectURL(blob);
  a.download = 'daily-report-' + date + '.md';
  a.click();
  URL.revokeObjectURL(a.href);
}

function hideDailyReport() {
  document.getElementById('daily-report-overlay').classList.remove('active');
}
