// ═══════════════════════════════════════════════════════════════
//  report-doc.jsx — the hours-report sheet (studio style)
//  One markup builder feeds both the live preview and the export.
//  Sibling document to the invoice — same A4 portrait paper.
// ═══════════════════════════════════════════════════════════════

// bracket mark as inline SVG string (matches invoice document)
function reportMarkSVG(size, color, accent) {
  return `<svg width="${size}" height="${size}" viewBox="0 0 64 64" fill="none" style="display:block">
    <path d="M22 14 H 14 V 50 H 22" stroke="${color}" stroke-width="4.5" stroke-linecap="round" stroke-linejoin="round"/>
    <path d="M28 22 L 42 32 L 28 42" stroke="${accent}" stroke-width="4.5" stroke-linecap="round" stroke-linejoin="round"/>
  </svg>`;
}

// sum of hours
const sumHours = (items) => items.reduce((s, it) => s + (Number(it.hours) || 0), 0);

// "01.04.2026 – 30.04.2026"
function periodStr(d) {
  const a = fmtDate(d.periodStart), b = fmtDate(d.periodEnd);
  if (a && b) return `${a} \u2013 ${b}`;
  return a || b || "";
}

// ═══════════════════════════════════════════════════════════════
//  reportInner — returns the inner HTML of the sheet (shared)
// ═══════════════════════════════════════════════════════════════
function reportInner(d) {
  const ink = "#0B1F2A", accent = "#2D5BFF", sheet = "#F4F1EA";
  const total = sumHours(d.items);
  const rate = Number(d.rate) || 0;
  const amount = total * rate;
  const cur = d.currency || "EUR";
  const esc = (s) => String(s == null ? "" : s).replace(/&/g, "&amp;").replace(/</g, "&lt;");

  const rows = d.items.map((it, i) => `<tr>
      <td class="idx c">${i + 1}</td>
      <td>${esc(it.desc) || "&mdash;"}</td>
      <td class="hrs r m">${fmtHours(it.hours)}</td>
    </tr>`).join("");

  const fmtRate = `${fmtNum(rate)} ${cur} / ${d.rateUnit || "hour"}`;
  const fmtAmount = `${fmtNum(amount)} ${cur}`;

  return `<div class="head">
    <div class="head-l">
      ${reportMarkSVG(30, ink, accent)}
      <div>
        <div class="wm">shortcut<span class="sl">/</span>studio</div>
        <div class="title">${esc(d.title) || "Hours Report"}</div>
        <div class="orig">${esc(d.subtitle) || "Appendix to Invoice"}</div>
      </div>
    </div>
    <div class="head-r">
      <div class="num-k">Invoice &#8470;</div>
      <div class="num m">${esc(d.num) || "&mdash;"}</div>
      <div class="dates"><div><span>Period</span><b class="m">${periodStr(d) || "&mdash;"}</b></div></div>
    </div>
  </div>

  <div class="parties">
    <div class="party">
      <div class="party-k">Contractor</div>
      <div class="party-name">${esc(d.contractorName) || "&mdash;"}</div>
      <div class="party-lines">${esc(d.contractorNote)}</div>
    </div>
    <div class="party">
      <div class="party-k">Client</div>
      <div class="party-name">${esc(d.clientName) || "&mdash;"}</div>
      <div class="party-lines">${esc(d.clientNote)}</div>
    </div>
  </div>

  <table class="items">
    <thead><tr>
      <th class="c">#</th>
      <th>Activity / Description</th>
      <th class="r">Hours</th>
    </tr></thead>
    <tbody>${rows}</tbody>
  </table>

  <div class="below"><div class="totals">
    <div class="tline"><span>Total hours</span><b class="m">${fmtHours(total)}</b></div>
    <div class="tline"><span>Rate</span><b class="m">${fmtRate}</b></div>
    <div class="tgrand"><span>Total</span><b class="m">${fmtAmount}</b></div>
  </div></div>

  <div class="foot">
    <div>
      <div class="sig-k">Prepared by</div>
      <div class="sig-line"></div>
      <div class="sig-name">${esc(d.preparedName) || "&nbsp;"}</div>
      <div class="sig-org">${esc(d.preparedOrg)}</div>
    </div>
    <div>
      <div class="sig-k">Accepted by</div>
      <div class="sig-line"></div>
      <div class="sig-name">${esc(d.acceptedName) || "&nbsp;"}</div>
      <div class="sig-org">${esc(d.acceptedOrg)}</div>
    </div>
  </div>`;
}

// hours formatting: integer shows plain, fractional shows up to 2 decimals
function fmtHours(n) {
  const v = Number(n) || 0;
  return Number.isInteger(v) ? String(v) : fmtNum(v).replace(/0$/, "");
}

// ═══════════════════════════════════════════════════════════════
//  Sheet CSS (shared by preview + export). Scoped under .sheet.
// ═══════════════════════════════════════════════════════════════
function reportCSS() {
  return `
  .sheet { width:794px; min-height:1123px; background:#F4F1EA; color:#0B1F2A;
    font-family:${MONO}; font-size:12.5px; line-height:1.5; padding:54px 56px 46px;
    box-sizing:border-box; display:flex; flex-direction:column;
    -webkit-print-color-adjust:exact; print-color-adjust:exact; }
  .sheet .m { font-variant-numeric:tabular-nums; letter-spacing:0; }
  .sheet .c { text-align:center; } .sheet .r { text-align:right; }

  .sheet .head { display:flex; justify-content:space-between; align-items:flex-start; margin-bottom:30px; }
  .sheet .head-l { display:flex; gap:14px; align-items:flex-start; }
  .sheet .wm { font-size:15px; font-weight:600; letter-spacing:-0.02em; }
  .sheet .wm .sl { opacity:.45; }
  .sheet .head-l .title { font-size:23px; font-weight:600; letter-spacing:-0.02em; margin-top:7px; color:#2D5BFF; }
  .sheet .head-l .orig { font-size:9px; letter-spacing:0.18em; color:#97A0A5; margin-top:3px; text-transform:uppercase; }
  .sheet .head-r { text-align:right; }
  .sheet .head-r .num-k { font-size:9px; letter-spacing:0.14em; color:#97A0A5; text-transform:uppercase; }
  .sheet .head-r .num { font-size:21px; font-weight:700; letter-spacing:0.02em; }
  .sheet .dates { margin-top:12px; display:flex; flex-direction:column; gap:3px; font-size:10.5px; }
  .sheet .dates > div { display:flex; justify-content:flex-end; gap:8px; }
  .sheet .dates span { color:#5E6B72; }

  .sheet .parties { display:grid; grid-template-columns:1fr 1fr; gap:22px; margin-bottom:26px; }
  .sheet .party { padding:16px 18px; background:rgba(11,31,42,0.045); border-radius:6px; }
  .sheet .party-k { font-size:9px; font-weight:600; letter-spacing:0.14em; color:#2D5BFF; margin-bottom:7px; }
  .sheet .party-name { font-size:14px; font-weight:600; letter-spacing:-0.01em; margin-bottom:6px; }
  .sheet .party-lines { font-size:11px; color:#5E6B72; line-height:1.65; min-height:1em; }

  .sheet table.items { width:100%; border-collapse:collapse; margin-bottom:18px; }
  .sheet table.items th { font-size:9px; font-weight:600; letter-spacing:0.06em; text-transform:uppercase;
    color:#2D5BFF; padding:0 8px 8px; text-align:left; border-bottom:1.5px solid #2D5BFF; }
  .sheet table.items th.c { text-align:center; } .sheet table.items th.r { text-align:right; }
  .sheet table.items td { padding:11px 8px; font-size:11.5px; border-bottom:1px solid rgba(11,31,42,0.16); vertical-align:top; line-height:1.5; }
  .sheet table.items td.idx { color:#97A0A5; width:30px; }
  .sheet table.items td.hrs { width:70px; font-weight:600; }

  .sheet .below { display:flex; justify-content:flex-end; margin-bottom:20px; }
  .sheet .totals { width:300px; flex-shrink:0; }
  .sheet .tline { display:flex; justify-content:space-between; align-items:flex-start; padding:8px 2px;
    border-bottom:1px solid rgba(11,31,42,0.16); font-size:11.5px; }
  .sheet .tline span { color:#5E6B72; padding-top:1px; }
  .sheet .tline b { font-weight:600; font-size:13px; }
  .sheet .tgrand { display:flex; justify-content:space-between; align-items:center; margin-top:9px;
    padding:14px 16px; background:#0B1F2A; color:#F4F1EA; border-radius:6px; }
  .sheet .tgrand span { font-weight:600; font-size:13px; }
  .sheet .tgrand b { font-size:18px; font-weight:700; }

  .sheet .foot { display:grid; grid-template-columns:1fr 1fr; gap:40px; margin-top:auto;
    padding-top:22px; border-top:1px solid rgba(11,31,42,0.16); }
  .sheet .sig-k { font-size:9px; font-weight:600; letter-spacing:0.14em; color:#2D5BFF; text-transform:uppercase; margin-bottom:34px; }
  .sheet .sig-line { height:1px; background:#0B1F2A; opacity:.5; margin-bottom:8px; }
  .sheet .sig-name { font-size:12px; font-weight:600; min-height:1em; }
  .sheet .sig-org { font-size:10.5px; color:#5E6B72; margin-top:2px; min-height:1em; }
  `;
}

// ═══════════════════════════════════════════════════════════════
//  React preview component (scales to fit its container width)
// ═══════════════════════════════════════════════════════════════
function ReportDoc({ d, scale }) {
  const css = React.useMemo(() => reportCSS(), []);
  const inner = React.useMemo(() => reportInner(d), [d]);
  return (
    <div style={{ width: 794 * scale, height: 1123 * scale, overflow: "hidden", flexShrink: 0 }}>
      <div style={{ transform: `scale(${scale})`, transformOrigin: "top left" }}>
        <style>{css}</style>
        <div className="sheet" style={{ boxShadow: "0 1px 3px rgba(0,0,0,0.08), 0 18px 50px rgba(0,0,0,0.13)" }}
          dangerouslySetInnerHTML={{ __html: inner }} />
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════
//  Standalone HTML export (print-ready A4)
// ═══════════════════════════════════════════════════════════════
function buildReportHTML(d) {
  const fname = `Hours Report ${d.num}`;
  return `<!doctype html><html lang="en"><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>${fname} — shortcut/studio</title>
<link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;600;700&display=swap" rel="stylesheet">
<style>
  *{margin:0;padding:0;box-sizing:border-box}
  html,body{background:#e9e6df;-webkit-print-color-adjust:exact;print-color-adjust:exact}
  body{display:flex;justify-content:center;padding:24px;font-family:${MONO}}
  ${reportCSS()}
  .sheet{box-shadow:0 1px 3px rgba(0,0,0,.08),0 18px 50px rgba(0,0,0,.13)}
  @media print{
    html,body{background:#F4F1EA;padding:0;margin:0}
    .sheet{box-shadow:none;width:210mm;min-height:296mm;margin:0 auto}
    @page{size:A4;margin:0}
  }
</style></head><body>
<div class="sheet">${reportInner(d)}</div>
</body></html>`;
}

Object.assign(window, { reportInner, reportCSS, ReportDoc, buildReportHTML, sumHours, fmtHours, periodStr });
