// shared-docs.jsx — Document generation engine shared by the Operations
// Console and the Employee Portal. Provides:
//   • injectDocPrintCSS()  — print isolation so a doc prints alone
//   • <DocViewer>          — in-app overlay that shows a doc + Print/Download
//   • downloadBlob()       — real file download (CSV / IIF / TXT)
//   • formatting helpers   — self-contained (no dependency on admin-state)
//
// Document TEMPLATES (the React components) live in doc-templates.jsx.

const D_money = (n) => {
  const v = +n || 0;
  return (v < 0 ? '-$' : '$') + Math.abs(v).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
};
const D_num = (n, d = 2) => (+n || 0).toLocaleString('en-US', { minimumFractionDigits: d, maximumFractionDigits: d });
const D_date = (iso) => iso ? new Date(iso.length === 10 ? iso + 'T00:00' : iso).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }) : '—';

// ── Print isolation ──────────────────────────────────────────
// Anything inside .rfp-doc-sheet prints; everything else is hidden.
function injectDocPrintCSS() {
  if (document.getElementById('rfp-doc-print-css')) return;
  const s = document.createElement('style');
  s.id = 'rfp-doc-print-css';
  s.textContent = `
    @media print {
      body * { visibility: hidden !important; }
      .rfp-doc-sheet, .rfp-doc-sheet * { visibility: visible !important; }
      .rfp-doc-sheet {
        position: absolute !important; left: 0 !important; top: 0 !important;
        width: 100% !important; margin: 0 !important; box-shadow: none !important;
        border: none !important; border-radius: 0 !important;
      }
      .rfp-doc-noprint { display: none !important; }
      @page { margin: 0.5in; size: letter; }
    }
    .rfp-doc-sheet {
      background: #fff; color: #111; width: 760px; margin: 0 auto;
      font-family: var(--font-sans, 'Inter', system-ui, sans-serif);
      box-shadow: 0 10px 40px rgba(0,0,0,0.22); border-radius: 4px;
    }
    .rfp-doc-mono { font-family: var(--font-mono, 'JetBrains Mono', monospace); font-variant-numeric: tabular-nums; }
    .rfp-form-grid { border: 1.5px solid #111; }
    .rfp-form-box { border: 1px solid #111; padding: 5px 8px; }
    .rfp-form-label { font-size: 8.5px; text-transform: uppercase; letter-spacing: 0.4px; color: #333; font-weight: 600; }
    .rfp-form-val { font-size: 13px; font-weight: 600; margin-top: 2px; }
  `;
  document.head.appendChild(s);
}

// ── Real file download (CSV / IIF / text / json) ─────────────
function downloadBlob(filename, content, mime = 'text/plain') {
  try {
    const blob = new Blob([content], { type: mime + ';charset=utf-8' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url; a.download = filename;
    document.body.appendChild(a); a.click();
    setTimeout(() => { document.body.removeChild(a); URL.revokeObjectURL(url); }, 200);
    return true;
  } catch (e) { return false; }
}

// CSV helper — escapes fields
function toCSV(rows) {
  return rows.map(r => r.map(cell => {
    const s = cell == null ? '' : String(cell);
    return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
  }).join(',')).join('\r\n');
}

// ── Data export builders ─────────────────────────────────────
// Payroll register CSV — one row per employee
function buildPayrollCSV(runRows, period) {
  const header = ['Employee', 'Badge', 'Resident', 'Reg Hrs', 'OT Hrs', 'Gross', 'State Tax', 'RRTA/FICA EE', 'Net Est', 'Pay Date'];
  const body = runRows.map(r => [
    r.name, r.badge, r.resident, D_num(r.reg, 2), D_num(r.ot, 2),
    (r.gross).toFixed(2), (r.stateTax || 0).toFixed(2), (r.eeTax || 0).toFixed(2),
    (r.net || 0).toFixed(2), r.payDate || '',
  ]);
  return toCSV([['RailFlagsPro Payroll Register', period], [], header, ...body]);
}

// QuickBooks-style IIF (tab-delimited) — timecard/earnings import
function buildPayrollIIF(runRows, period) {
  const lines = [];
  lines.push(['!TIMERHDR', 'VER', 'REL', 'COMPANYNAME', 'IMPORTEDBEFORE', 'FROMTIMER', 'COMPANYCREATETIME'].join('\t'));
  lines.push(['TIMERHDR', '8', '0', 'RailFlagsPro', 'N', 'Y', ''].join('\t'));
  lines.push(['!HDR', 'PROD', 'VER', 'REL', 'IIFVER', 'DATE', 'TIME', 'ACCNTNT', 'ACCNTNTSPLITTIME'].join('\t'));
  lines.push(['HDR', 'QuickBooks', '8', '0', '1', new Date().toLocaleDateString('en-US'), '', 'N', '0'].join('\t'));
  lines.push(['!TIMEACT', 'DATE', 'JOB', 'EMP', 'ITEM', 'PITEM', 'DURATION', 'PROJ', 'NOTE', 'XFERTOPAYROLL', 'BILLINGSTATUS'].join('\t'));
  runRows.forEach(r => {
    const dur = `${Math.floor(r.reg)}:${String(Math.round((r.reg % 1) * 60)).padStart(2, '0')}`;
    lines.push(['TIMEACT', r.payDate || '', r.job || '', r.name, 'RWIC:Regular', 'RWIC Labor', dur, '', `Period ${period}`, 'Y', '1'].join('\t'));
    if (r.ot > 0) {
      const od = `${Math.floor(r.ot)}:${String(Math.round((r.ot % 1) * 60)).padStart(2, '0')}`;
      lines.push(['TIMEACT', r.payDate || '', r.job || '', r.name, 'RWIC:Overtime', 'RWIC OT', od, '', `Period ${period} OT`, 'Y', '1'].join('\t'));
    }
  });
  return lines.join('\r\n');
}

// Multi-state withholding worksheet CSV — one row per employee×state
function buildWithholdingCSV(allocRows, policy, period) {
  const header = ['Employee', 'Resident', 'Work State', 'Taxable Wages', 'Tax Rate', 'Withheld', 'Taxed To', 'Resident Credit', 'Note'];
  const body = [];
  allocRows.forEach(r => {
    r.breakdown.forEach(b => {
      body.push([r.name, r.resident, b.state, b.wage.toFixed(2), (b.taxRate * 100).toFixed(2) + '%', b.taxAmt.toFixed(2), b.taxedBy, (b.credit || 0).toFixed(2), b.note]);
    });
  });
  return toCSV([['RailFlagsPro Multi-State Withholding Worksheet', `Policy: ${policy}`, period], [], header, ...body]);
}

// ── DocViewer overlay ────────────────────────────────────────
// Shows a rendered document (children) with a toolbar. For data files,
// pass file={filename, content, mime} to enable a real download button.
function DocViewer({ open, onClose, title, subtitle, file, children, accent = '#E55B13' }) {
  useEffect(() => { injectDocPrintCSS(); }, []);
  if (!open) return null;
  return (
    <div className="rfp-doc-overlay" style={{
      position: 'fixed', inset: 0, zIndex: 9000,
      display: 'flex', flexDirection: 'column',
      background: 'rgba(15,23,42,0.72)',
    }}>
      {/* Toolbar */}
      <div className="rfp-doc-noprint" style={{
        flexShrink: 0, height: 60, background: '#0F172A', color: '#fff',
        display: 'flex', alignItems: 'center', gap: 16, padding: '0 20px',
      }}>
        <button onClick={onClose} style={{
          width: 36, height: 36, borderRadius: 18, border: 'none',
          background: 'rgba(255,255,255,0.1)', color: '#fff', cursor: 'pointer',
          display: 'grid', placeItems: 'center', fontSize: 18,
        }}>✕</button>
        <div style={{ flex: 1 }}>
          <div style={{ fontWeight: 700, fontSize: 15 }}>{title}</div>
          {subtitle && <div style={{ fontSize: 12, color: 'rgba(255,255,255,0.6)' }}>{subtitle}</div>}
        </div>
        {file && (
          <button onClick={() => downloadBlob(file.filename, file.content, file.mime)} style={{
            background: 'rgba(255,255,255,0.1)', border: '1px solid rgba(255,255,255,0.2)',
            color: '#fff', padding: '9px 16px', borderRadius: 9, cursor: 'pointer',
            fontSize: 13, fontWeight: 600, fontFamily: 'inherit',
            display: 'inline-flex', alignItems: 'center', gap: 7,
          }}>↓ Download {file.filename.split('.').pop().toUpperCase()}</button>
        )}
        <button onClick={() => window.print()} style={{
          background: accent, border: 'none', color: '#fff',
          padding: '9px 18px', borderRadius: 9, cursor: 'pointer',
          fontSize: 13, fontWeight: 700, fontFamily: 'inherit',
          display: 'inline-flex', alignItems: 'center', gap: 7,
        }}>⎙ Print / Save as PDF</button>
      </div>
      {/* Scroll area with the sheet */}
      <div style={{ flex: 1, overflowY: 'auto', padding: '28px 20px 60px', display: 'flex', justifyContent: 'center', alignItems: 'flex-start' }}>
        <div className="rfp-doc-sheet">
          {children}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, {
  D_money, D_num, D_date,
  injectDocPrintCSS, downloadBlob, toCSV,
  buildPayrollCSV, buildPayrollIIF, buildWithholdingCSV,
  DocViewer,
});
