// pdf.jsx — 公司端一鍵下載真實 PDF（html2pdf）+ 各報告的乾淨列印版型（專業 SaaS 風）
const PC = { ink: '#18212F', ink2: '#586374', ink3: '#8B94A3', line: '#E8EBF0', panel: '#FAFBFC',
  acc: '#C2622B', accD: '#A24E1E', accSoft: '#FBEEE3', blue: '#3B6FE0', teal: '#0E8C97', green: '#2E9E6B',
  good: '#2E9E6B', warn: '#E0A12B', bad: '#D2503C', violet: '#7A5CD0' };

function pdfShell(title, sub, body) {
  return `<div style="width:760px;background:#fff;color:${PC.ink};font-family:'Geist','Noto Sans TC',sans-serif;padding:46px 44px 40px;box-sizing:border-box;">
    <div style="display:flex;align-items:flex-start;justify-content:space-between;border-bottom:2.5px solid ${PC.acc};padding-bottom:16px;margin-bottom:24px;">
      <div>
        <div style="font-size:12px;font-weight:800;color:${PC.accD};letter-spacing:2px;">樂睦 LUMO · 公司端</div>
        <div style="font-size:25px;font-weight:800;margin-top:6px;line-height:1.15;">${title}</div>
        ${sub ? `<div style="font-size:13.5px;color:${PC.ink2};font-weight:600;margin-top:5px;">${sub}</div>` : ''}
      </div>
      <div style="text-align:right;font-size:11.5px;color:${PC.ink3};font-weight:600;line-height:1.7;">平台營運控制台<br/>產出日 2026.06.30</div>
    </div>
    ${window.__SAFE ? `<div style="background:${PC.accSoft};color:${PC.accD};border:1px solid #E8C9B0;border-radius:8px;padding:9px 13px;font-size:12px;font-weight:700;margin-bottom:18px;">原型示意 · 本報告數據為模擬，非實際營運資料</div>` : ''}
    ${body}
    <div style="margin-top:30px;padding-top:14px;border-top:1px solid ${PC.line};font-size:10.5px;color:${PC.ink3};line-height:1.7;">
      ※ 功能三力為感測器硬數據，心理社會三力為參與行為推估值；所有數據用於服務優化與成效溝通，非醫療診斷。AI 報告經機構老師覆核後採用。<br/>© 2026 樂睦有限公司（Lumo）
    </div>
  </div>`;
}
function pdfSection(title, inner) { return `<div style="margin-top:22px;page-break-inside:avoid;"><div style="font-size:15px;font-weight:800;margin-bottom:10px;">${title}</div>${inner}</div>`; }
function pdfMeta(pairs) {
  return `<div style="border:1px solid ${PC.line};border-radius:10px;overflow:hidden;">${pairs.map((p, i) => `<div style="display:flex;${i ? 'border-top:1px solid ' + PC.line + ';' : ''}">
    <div style="width:130px;flex:0 0 auto;background:${PC.panel};padding:9px 13px;font-size:12.5px;color:${PC.ink2};font-weight:700;">${p[0]}</div>
    <div style="padding:9px 13px;font-size:13px;font-weight:500;">${p[1]}</div></div>`).join('')}</div>`;
}
function pdfKpis(items) {
  return `<div style="display:flex;gap:11px;">${items.map((it) => `<div style="flex:1;background:${PC.panel};border:1px solid ${PC.line};border-radius:11px;padding:14px 12px;">
    <div style="font-size:24px;font-weight:800;line-height:1;">${it[1]}</div>
    <div style="font-size:12px;color:${PC.ink3};font-weight:600;margin-top:6px;">${it[0]}</div></div>`).join('')}</div>`;
}
function pdfTable(cols, rows) {
  return `<table style="width:100%;border-collapse:collapse;font-size:12.5px;">
    <thead><tr>${cols.map((c) => `<th style="text-align:left;padding:8px 10px;border-bottom:1.5px solid ${PC.line};color:${PC.ink3};font-weight:700;font-size:11px;letter-spacing:.03em;">${c}</th>`).join('')}</tr></thead>
    <tbody>${rows.map((r) => `<tr>${r.map((cell) => `<td style="padding:8px 10px;border-bottom:1px solid ${PC.line};">${cell}</td>`).join('')}</tr>`).join('')}</tbody></table>`;
}
function pdfImprove(rows) {
  return `<div>${rows.map((row) => {
    const up = row.r - row.b;
    return `<div style="margin:9px 0;"><div style="display:flex;justify-content:space-between;font-size:13px;margin-bottom:4px;">
      <span style="font-weight:700;">${row.k}</span><span style="font-weight:600;">${row.b} → <b>${row.r}</b> <span style="color:${PC.green}">+${up}</span></span></div>
      <div style="height:7px;background:${PC.panel};border-radius:999px;position:relative;overflow:hidden;"><div style="position:absolute;left:0;top:0;height:100%;width:${row.r}%;background:${PC.acc};border-radius:999px;"></div></div></div>`;
  }).join('')}</div>`;
}
const _conf = (c) => c >= 75 ? PC.good : c >= 65 ? PC.warn : PC.bad;

// —— 報告版型 ——
function buildPlatformOverviewHTML() {
  const kpis = window.KPIS.map((k) => [k.label, (k.fmt === 'big' ? window.fmtK(k.value) : window.fmt(k.value)) + (k.unit || '')]);
  const rows = window.INSTITUTIONS.map((m) => [m.name, m.region, m.members, m.devices, m.online + '%', m.status]);
  const body = `${pdfKpis(kpis)}
    ${pdfSection('合作機構', pdfTable(['機構', '地區', '長者', '裝置', '在線率', '狀態'], rows))}
    ${pdfSection('營運摘要', `<p style="font-size:13.5px;line-height:1.8;margin:0;">目前合作 ${window.INSTITUTIONS.length} 家機構（${window.INSTITUTIONS.filter((m) => m.status === '試辦中').length} 家試辦中、${window.INSTITUTIONS.filter((m) => m.status === '導入中').length} 家導入中），服務長者 ${window.TOTAL_MEMBERS} 位，整合教具 ${window.VENDORS_INT.length} 款（${window.TESTING_COUNT} 款測試中）。2026 年迄今平台活動量穩定成長，跨機構樂齡六力平均改善 +6.4 分。</p>`)}`;
  return pdfShell('平台營運報表', '2026 年迄今 · 全平台概況', body);
}
function buildDocReportHTML(r) {
  const points = ['機構整體六力變化與參與率摘要', '重點個案前後測成效對照', '依' + r.juri + '評鑑指標對應佐證', '次季服務建議'];
  const body = `${pdfMeta([['機構', r.inst], ['期間', r.period], ['轄區格式', r.juri], ['產出者', r.by], ['日期', r.date], ['狀態', r.status]])}
    ${pdfSection('報告內容', `<ul style="margin:0;padding-left:20px;font-size:13.5px;line-height:1.95;color:${PC.ink2};">${points.map((p) => `<li>${p}</li>`).join('')}</ul>`)}`;
  return pdfShell(r.title, r.inst + ' · ' + r.period, body);
}
function buildInstQuarterlyHTML(m) {
  const kpis = [['服務長者', m.members + ' 位'], ['整合裝置', m.devices + ' 台'], ['本月活動', window.fmt(m.monthly) + ' 次'], ['裝置在線率', m.online + '%']];
  const body = `${pdfMeta([['機構類型', m.type], ['地區', m.region], ['導入起', m.since], ['狀態', m.status]])}
    <div style="margin-top:16px;">${pdfKpis(kpis)}</div>
    ${pdfSection('樂齡六力改善（初評 → 近期）', pdfImprove(window.SIX))}
    ${pdfSection('季度結論', `<p style="font-size:13.5px;line-height:1.8;margin:0;">${m.name}本季服務 ${m.members} 位長者，裝置在線率 ${m.online}%，六力平均改善 +${m.sixGain} 分。建議持續鞏固高參與班別，並針對低信心個案安排機構老師加強覆核與陪伴。</p>`)}`;
  return pdfShell('機構季度成效報告', m.name + ' · 2026 Q2', body);
}
function buildModelUsageHTML(focus) {
  const models = window.MODEL_COSTS;
  const total = models.reduce((a, x) => a + x.cost, 0);
  const rows = models.map((x) => [x.model, x.use, window.fmt(x.calls), x.tokIn, x.tokOut, 'NT$' + window.fmt(x.cost), Math.round(x.cost / total * 100) + '%']);
  rows.push(['合計', '', '', '', '', 'NT$' + window.fmt(total), '100%']);
  const body = `${pdfSection('本月模型用量與成本明細', pdfTable(['模型', '用途', '呼叫', '輸入Tok', '輸出Tok', '成本', '占比'], rows))}
    <p style="font-size:12.5px;color:${PC.ink3};line-height:1.7;margin-top:16px;">※ 依用途分工選用最適模型（複雜推理用 Opus、量大報告用 Sonnet、分類用 Haiku），以控管單位成本。${focus && focus.model ? '本次匯出聚焦：' + focus.model + '。' : ''}</p>`;
  return pdfShell('AI 模型用量明細', '2026.06 · NT$', body);
}
function buildAIReportHTML(q) {
  const steps = ['擷取該長者前後測數據與教具互動紀錄', '比對同級別基準與個人歷史趨勢', '生成六力變化敘述與個案建議草稿', '自評信心度並標記需機構老師確認之處'];
  const review = q.status === '待覆核'
    ? pdfMeta([['覆核狀態', '尚未覆核'], ['指派機構', q.inst]])
    : pdfMeta([['覆核老師', (q.by || '機構') + ' 老師'], ['老師評分', ({ up: '認同', edit: '微調沿用', down: '需修正' })[q.rating] || '—'], ['覆核結果', q.status], ['修改重點', q.issue || '直接採用，無需修改']]);
  const body = `${pdfMeta([['長者', q.who], ['機構', q.inst], ['報告類型', q.type], ['模型信心度', '<span style="color:' + _conf(q.conf) + ';font-weight:800">' + q.conf + '%</span>']])}
    ${pdfSection('推理軌跡', `<ol style="margin:0;padding-left:20px;font-size:13.5px;line-height:1.9;color:${PC.ink2};">${steps.map((s) => `<li>${s}</li>`).join('')}</ol>`)}
    ${pdfSection('資料來源', pdfTable(['來源', '筆數'], [['前後測評估', '2 筆'], ['教具互動紀錄', '48 筆'], ['老師觀察紀錄', '3 筆']]))}
    ${pdfSection('機構老師覆核', review)}`;
  return pdfShell('AI 個案報告', q.who + ' · ' + q.type + ' · ' + q.inst, body);
}
function buildApiDocHTML(v) {
  const sample = '{\n  "member_id": "...",\n  "device": "' + v.model + '",\n  "session_at": "2026-06-22T09:14+08",\n  "duration_s": 420,\n  "score": 78,\n  "domain": "' + v.cat + '"\n}';
  const body = `${pdfMeta([['教具型號', v.model], ['廠商', v.vendor], ['類型', v.cat], ['介接狀態', v.api], ['資料格式', v.fmt], ['介接方式', '統一資料閘道 / OAuth2'], ['同步頻率', '即時 / 每 5 分鐘批次']])}
    ${pdfSection('資料欄位（範例）', `<pre style="background:#0F1623;color:#C7D2E0;border-radius:9px;padding:14px 16px;font-size:12px;line-height:1.6;font-family:ui-monospace,Menlo,monospace;white-space:pre-wrap;margin:0;">${sample.replace(/</g, '&lt;')}</pre>`)}`;
  return pdfShell('教具 API 介接文件', v.model + ' · ' + v.vendor, body);
}

async function exportPDF(filename, html) {
  if (!window.html2canvas || !window.jspdf) { window.__toast && window.__toast('PDF 元件載入中，請稍候再試'); return; }
  window.__toast && window.__toast('PDF 產生中…');
  const W = 760;
  const wrap = document.createElement('div');
  wrap.style.cssText = 'position:fixed;left:-10000px;top:0;width:' + W + 'px;z-index:-1;background:#fff;';
  wrap.innerHTML = html;
  document.body.appendChild(wrap);
  const el = wrap.firstElementChild;
  try {
    if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch (e) {} }
    await new Promise((r) => setTimeout(r, 60));
    const canvas = await window.html2canvas(el, { scale: 2, backgroundColor: '#ffffff', useCORS: true, width: W, windowWidth: W, scrollX: 0, scrollY: 0 });
    const Hcss = Math.round(canvas.height * (W / canvas.width));
    const orient = Hcss >= W ? 'p' : 'l';
    const pdf = new window.jspdf.jsPDF({ orientation: orient, unit: 'px', format: [W, Hcss], hotfixes: ['px_scaling'] });
    pdf.addImage(canvas.toDataURL('image/jpeg', 0.97), 'JPEG', 0, 0, W, Hcss);
    pdf.save(filename + '.pdf');
  } catch (e) { console.error('PDF error', e); window.__toast && window.__toast('PDF 產生失敗'); }
  finally { document.body.removeChild(wrap); }
}

Object.assign(window, { exportPDF, buildPlatformOverviewHTML, buildDocReportHTML, buildInstQuarterlyHTML, buildModelUsageHTML, buildAIReportHTML, buildApiDocHTML });
