// daygig-reports.js — Report sub-tabs, P&L / spending summary, balance sheet, tax worksheet

// ── Profile helpers ───────────────────────────────────────────────────────
  function dgSettings() {
    if (typeof getDaygigSettings === 'function') return getDaygigSettings();
    if (window.DAYGIG_SETTINGS) return window.DAYGIG_SETTINGS;
    if (typeof settings === 'object' && settings) return settings;
    return {};
  }

  function isPersonalMode() {
    const s = dgSettings();
    return (s.user_profile || s.profile || '').toLowerCase() === 'personal';
  }

  function reportLabels(data) {
    const personal = isPersonalMode() || data?.is_personal || data?.user_profile === 'personal';
    const fromData = data?.labels || {};
    return {
      reportsTitle:    fromData.reports_title    || (personal ? 'Spending Reports' : 'Reports'),
      pnlTitle:        fromData.pnl_title        || (personal ? 'Spending Summary' : 'Profit & Loss'),
      income:          fromData.income           || (personal ? 'Money In' : 'Revenue'),
      expenses:        fromData.expenses         || (personal ? 'Money Out' : 'Operating Expenses'),
      cogs:            fromData.cogs             || 'Cost of Goods Sold',
      grossProfit:     fromData.gross_profit     || 'Gross Profit',
      net:             fromData.net              || (personal ? 'Left Over' : 'Net Income'),
      balanceTitle:    fromData.balance_title    || (personal ? 'Net Worth Snapshot' : 'Balance Sheet'),
      taxTitle:        fromData.tax_title        || 'Sales Tax Worksheet',
    };
  }

  function setTextIfExists(id, text) {
    const el = document.getElementById(id);
    if (el) el.textContent = text;
  }

  function applyReportProfileUi() {
    const labels = reportLabels();
    const personal = isPersonalMode();
    setTextIfExists('topbarTitle', labels.reportsTitle);

    document.querySelectorAll('.rpt-tab').forEach(btn => {
      const name = btn.dataset.rpt;
      if (name === 'pl') btn.textContent = labels.pnlTitle;
      if (name === 'balance') btn.textContent = labels.balanceTitle;
      if (name === 'trial') btn.textContent = 'Trial Balance';
      if (name === 'exports') btn.textContent = personal ? 'Exports' : 'Year-End Exports';
      if (name === 'tax') {
        btn.style.display = personal ? 'none' : '';
        btn.textContent = labels.taxTitle;
      }
    });

    const taxPanel = document.getElementById('rpt-tax');
    if (taxPanel && personal) taxPanel.style.display = 'none';
  }

// ── Sub-tab helpers ───────────────────────────────────────────────────────
  function _subTab(cls, prefix, name, onLoad) {
    document.querySelectorAll('.' + cls).forEach(btn => {
      const active = btn.dataset[prefix] === name;
      btn.style.color        = active ? 'var(--accent)'           : 'var(--text-soft)';
      btn.style.borderBottom = active ? '2px solid var(--accent)' : '2px solid transparent';
    });
    document.querySelectorAll('[id^="' + prefix + '-"]').forEach(el => {
      el.style.display = el.id === prefix + '-' + name ? 'block' : 'none';
    });
    if (onLoad) onLoad();
  }

  function rptTab(name) {
    applyReportProfileUi();
    if (isPersonalMode() && name === 'tax') name = 'pl';

    document.querySelectorAll('.rpt-tab').forEach(btn => {
      const active = btn.dataset.rpt === name;
      btn.style.color        = active ? 'var(--accent)'           : 'var(--text-soft)';
      btn.style.borderBottom = active ? '2px solid var(--accent)' : '2px solid transparent';
    });
    ['pl','balance','trial','tax','exports'].forEach(t => {
      const el = document.getElementById('rpt-' + t);
      if (el) el.style.display = t === name ? 'block' : 'none';
    });

    // Set default date ranges on first open.
    const today = new Date().toISOString().split('T')[0];
    const yearStart = today.slice(0,4) + '-01-01';
    if (name === 'pl') {
      const from = document.getElementById('rpt-pl-from');
      const to = document.getElementById('rpt-pl-to');
      if (from && to && !from.value) { from.value = yearStart; to.value = today; }
    }
    if (name === 'tax') {
      const from = document.getElementById('rpt-tax-from');
      const to = document.getElementById('rpt-tax-to');
      if (from && to && !from.value) { from.value = yearStart; to.value = today; }
    }
    if (name === 'balance') {
      const asof = document.getElementById('rpt-bs-asof');
      if (asof && !asof.value) asof.value = today;
    }
    if (name === 'trial') {
      const asof = document.getElementById('rpt-tb-asof');
      if (asof && !asof.value) asof.value = today;
    }
    if (name === 'exports') {
      const yr = document.getElementById('rpt-year-end-year');
      const df = document.getElementById('rpt-ded-from');
      const dt = document.getElementById('rpt-ded-to');
      if (yr && !yr.value) yr.value = String(new Date().getFullYear() - 1);
      if (df && dt && !df.value) { df.value = yearStart; dt.value = today; }
    }

    // Opening a report used to show an empty page with a Run button — the
    // dates are already filled in above, so run it. Changing a date and
    // pressing Run still works exactly as before.
    const RUNNERS = {
      pl: 'rptPlLoad', balance: 'rptBsLoad',
      trial: 'rptTrialLoad', tax: 'rptTaxLoad',
    };
    const runner = RUNNERS[name];
    if (runner && typeof window[runner] === 'function') {
      setTimeout(() => {
        try { window[runner](); } catch (e) { /* report will stay on its Run button */ }
      }, 0);
    }
  }

  function salesTab(name) {
    ['orders','customers','shipments'].forEach(t => {
      const el = document.getElementById('sales-' + t);
      if (el) el.style.display = t === name ? 'block' : 'none';
    });
    document.querySelectorAll('.sales-tab').forEach(btn => {
      const active = btn.dataset.sales === name;
      btn.style.color        = active ? 'var(--accent)'           : 'var(--text-soft)';
      btn.style.borderBottom = active ? '2px solid var(--accent)' : '2px solid transparent';
    });
    if (name === 'orders'    && typeof ordersLoad === 'function')    ordersLoad();
    if (name === 'customers' && typeof customersLoad === 'function') customersLoad();
    if (name === 'shipments' && typeof shipmentsLoad === 'function') shipmentsLoad();
  }

  function projTab(name) {
    ['overview','events','campaigns'].forEach(t => {
      const el = document.getElementById('proj-' + t);
      if (el) el.style.display = t === name ? 'block' : 'none';
    });
    document.querySelectorAll('.proj-tab').forEach(btn => {
      const active = btn.dataset.proj === name;
      btn.style.color        = active ? 'var(--accent)'           : 'var(--text-soft)';
      btn.style.borderBottom = active ? '2px solid var(--accent)' : '2px solid transparent';
    });
    if (name === 'overview'  && typeof loadProjects === 'function')  loadProjects();
    if (name === 'events'    && typeof eventsLoad === 'function')    eventsLoad();
    if (name === 'campaigns' && typeof campaignsLoad === 'function') campaignsLoad();
  }

  // ── Reports ───────────────────────────────────────────────────────────────
  function _fmtMoney(cents) {
    cents = Number(cents || 0);
    const abs = Math.abs(cents);
    const str = window.dgMoneyC ? window.dgMoneyC(abs) : '$' + (abs / 100).toFixed(2);
    return cents < 0 ? '(' + str + ')' : str;
  }
  function _plRow(label, cents, indent, bold) {
    cents = Number(cents || 0);
    // Only subtotals and totals carry the accent. When every line was lime the
    // eye had nowhere to land and the figures that matter did not stand out.
    const color = cents < 0 ? 'var(--neg)'
      : cents === 0 ? 'var(--text-dim)'
      : bold ? 'var(--accent)' : 'var(--text)';
    return `<div style="display:flex;justify-content:space-between;gap:16px;padding:${bold?'9px':'6px'} 0 ${bold?'9px':'6px'} ${indent*18}px;border-bottom:1px solid var(--border);${bold?'font-weight:650;':''}">
      <span style="color:${bold ? 'var(--text)' : 'var(--text-soft)'};">${label}</span>
      <span style="font-family:var(--mono);font-size:12.5px;font-variant-numeric:tabular-nums;color:${color};">${_fmtMoney(cents)}</span>
    </div>`;
  }

  async function rptPlLoad() {
    applyReportProfileUi();
    const fromEl = document.getElementById('rpt-pl-from');
    const toEl   = document.getElementById('rpt-pl-to');
    const from  = fromEl?.value || '';
    const to    = toEl?.value || '';
    const body  = document.getElementById('rpt-pl-body');
    const sub   = document.getElementById('rpt-pl-sub');
    const csvEl = document.getElementById('rpt-pl-csv');
    const pdfEl = document.getElementById('rpt-pl-pdf');
    if (!body) return;
    if (!from || !to) { body.innerHTML = '<p style="color:var(--warn);font-size:13px;">Select a date range first.</p>'; return; }
    body.innerHTML = '<p style="color:var(--text-dim);font-size:13px;">Loading…</p>';
    try {
      const res  = await fetch(`/api/reports/pl?date_from=${from}&date_to=${to}`);
      const data = await res.json();
      if (data.error) { body.innerHTML = `<p style="color:var(--err);">${data.error}</p>`; return; }
      const labels = reportLabels(data);
      if (sub) sub.textContent = `${from} – ${to}`;
      if (csvEl) {
        csvEl.href = `/api/reports/pl.csv?date_from=${from}&date_to=${to}`;
        csvEl.style.display = 'inline-flex';
      }
      if (pdfEl) {
        pdfEl.href = `/api/reports/pl.pdf?date_from=${from}&date_to=${to}`;
        pdfEl.style.display = 'inline-flex';
      }

      const incomeLines = data.income_lines || [];
      const expenseLines = data.expense_lines || data.opex_lines || [];
      const totalExpenses = data.total_expenses_cents ?? data.total_opex_cents ?? 0;
      const totalIncome = data.total_income_cents ?? data.money_in_cents ?? 0;
      const netIncome = data.net_income_cents ?? data.left_over_cents ?? 0;

      let html = '';
      html += _plRow(labels.income, totalIncome, 0, true);
      incomeLines.forEach(l => html += _plRow(l.name || l.label, l.cents, 1, false));

      if (!isPersonalMode() && (data.cogs_lines || []).length) {
        html += _plRow(labels.cogs, data.total_cogs_cents || 0, 0, true);
        data.cogs_lines.forEach(l => html += _plRow(l.name || l.label, l.cents, 1, false));
        html += _plRow(labels.grossProfit, data.gross_profit_cents || 0, 0, true);
      }

      html += _plRow(labels.expenses, totalExpenses, 0, true);
      expenseLines.forEach(l => html += _plRow(l.name || l.label, l.cents, 1, false));

      html += `<div style="display:flex;justify-content:space-between;padding:12px 0;margin-top:4px;border-top:2px solid var(--border-hi);font-weight:700;font-size:15px;">
        <span style="color:var(--text);">${labels.net}</span>
        <span style="font-family:var(--mono);color:${netIncome>=0?'var(--accent)':'var(--err)'};">${_fmtMoney(netIncome)}</span>
      </div>`;
      body.innerHTML = html;
    } catch(e) { body.innerHTML = `<p style="color:var(--err);">Error: ${e.message}</p>`; }
  }

  async function rptBsLoad() {
    applyReportProfileUi();
    const asof = document.getElementById('rpt-bs-asof')?.value || '';
    const body = document.getElementById('rpt-bs-body');
    if (!body) return;
    if (!asof) { body.innerHTML = '<p style="color:var(--warn);font-size:13px;">Select a date first.</p>'; return; }
    body.innerHTML = '<p style="color:var(--text-dim);font-size:13px;">Loading…</p>';
    try {
      const res  = await fetch(`/api/reports/balance-sheet?as_of=${asof}`);
      const data = await res.json();
      if (data.error) { body.innerHTML = `<p style="color:var(--err);">${data.error}</p>`; return; }
      const labels = reportLabels(data);
      const csvEl = document.getElementById('rpt-bs-csv');
      const pdfEl = document.getElementById('rpt-bs-pdf');
      if (csvEl) { csvEl.href = `/api/reports/balance-sheet.csv?as_of=${asof}`; csvEl.style.display = 'inline-flex'; }
      if (pdfEl) { pdfEl.href = `/api/reports/balance-sheet.pdf?as_of=${asof}`; pdfEl.style.display = 'inline-flex'; }
      let html = `<div style="font-family:var(--mono);font-size:11px;color:var(--text-dim);margin-bottom:10px;">${labels.balanceTitle} as of ${asof}</div>`;
      const section = (title, lines, total) => {
        html += _plRow(title, total, 0, true);
        (lines || []).forEach(l => html += _plRow(l.name || l.label, l.cents, 1, false));
      };
      section('Assets',      data.asset_lines,     data.total_assets_cents);
      section('Liabilities', data.liability_lines,  data.total_liabilities_cents);
      section('Equity',      data.equity_lines,     data.total_equity_cents);
      body.innerHTML = html;
    } catch(e) { body.innerHTML = `<p style="color:var(--err);">Error: ${e.message}</p>`; }
  }

  async function rptTaxLoad() {
    applyReportProfileUi();
    const from = document.getElementById('rpt-tax-from')?.value || '';
    const to   = document.getElementById('rpt-tax-to')?.value || '';
    const body = document.getElementById('rpt-tax-body');
    if (!body) return;
    if (isPersonalMode()) {
      body.innerHTML = '<p style="color:var(--text-soft);font-size:13px;">Sales/use tax reports are hidden in personal finance mode.</p>';
      return;
    }
    if (!from || !to) { body.innerHTML = '<p style="color:var(--warn);font-size:13px;">Select a date range first.</p>'; return; }
    body.innerHTML = '<p style="color:var(--text-dim);font-size:13px;">Loading…</p>';
    try {
      const res  = await fetch(`/api/reports/tax?date_from=${from}&date_to=${to}`);
      const data = await res.json();
      if (data.error) { body.innerHTML = `<p style="color:var(--err);">${data.error}</p>`; return; }
      if (data.applicable === false) {
        body.innerHTML = `<p style="color:var(--text-soft);font-size:13px;">${data.message || 'This report is not applicable for the current profile.'}</p>`;
        return;
      }
      const csvEl = document.getElementById('rpt-tax-csv');
      const pdfEl = document.getElementById('rpt-tax-pdf');
      if (csvEl) { csvEl.href = `/api/reports/tax.csv?date_from=${from}&date_to=${to}`; csvEl.style.display = 'inline-flex'; }
      if (pdfEl) { pdfEl.href = `/api/reports/tax.pdf?date_from=${from}&date_to=${to}`; pdfEl.style.display = 'inline-flex'; }
      const rows = [
        ['Sales Tax Collected', data.sales_tax_collected_cents],
        ['Use Tax Owed',        data.use_tax_owed_cents],
        ['Total Tax Due',       data.grand_total_cents ?? ((data.sales_tax_collected_cents||0) + (data.use_tax_owed_cents||0))],
      ];
      body.innerHTML = rows.map(([label, cents]) => _plRow(label, cents||0, 0, label.startsWith('Total'))).join('');
    } catch(e) { body.innerHTML = `<p style="color:var(--err);">Error: ${e.message}</p>`; }
  }


  async function rptTrialLoad() {
    applyReportProfileUi();
    const asof = document.getElementById('rpt-tb-asof')?.value || '';
    const body = document.getElementById('rpt-tb-body');
    if (!body) return;
    if (!asof) { body.innerHTML = '<p style="color:var(--warn);font-size:13px;">Select a date first.</p>'; return; }
    body.innerHTML = '<p style="color:var(--text-dim);font-size:13px;">Loading…</p>';
    try {
      const res = await fetch(`/api/reports/trial-balance?as_of=${asof}`);
      const data = await res.json();
      if (data.error) { body.innerHTML = `<p style="color:var(--err);">${data.error}</p>`; return; }
      const csvEl = document.getElementById('rpt-tb-csv');
      const pdfEl = document.getElementById('rpt-tb-pdf');
      if (csvEl) { csvEl.href = `/api/reports/trial-balance.csv?as_of=${asof}`; csvEl.style.display = 'inline-flex'; }
      if (pdfEl) { pdfEl.href = `/api/reports/trial-balance.pdf?as_of=${asof}`; pdfEl.style.display = 'inline-flex'; }
      const rows = data.rows || [];
      let html = `<div style="font-family:var(--mono);font-size:11px;color:var(--text-dim);margin-bottom:10px;">As of ${asof} · ${rows.length} accounts · ${data.balanced ? 'Balanced' : 'Out of balance'}</div>`;
      html += `<div style="overflow-x:auto;"><table style="width:100%;border-collapse:collapse;font-size:12px;"><thead><tr style="border-bottom:1px solid var(--border);"><th style="text-align:left;padding:7px 10px;">Code</th><th style="text-align:left;padding:7px 10px;">Account</th><th style="text-align:left;padding:7px 10px;">Type</th><th style="text-align:right;padding:7px 10px;">Debit</th><th style="text-align:right;padding:7px 10px;">Credit</th></tr></thead><tbody>`;
      rows.forEach(r => {
        const debit = Number(r.balance_cents || 0) >= 0 ? _fmtMoney(r.balance_cents) : '';
        const credit = Number(r.balance_cents || 0) < 0 ? _fmtMoney(Math.abs(r.balance_cents)) : '';
        html += `<tr style="border-bottom:1px solid var(--border);"><td style="padding:6px 10px;font-family:var(--mono);color:var(--text-dim);">${r.code || ''}</td><td style="padding:6px 10px;color:var(--text);">${r.name || ''}</td><td style="padding:6px 10px;color:var(--text-soft);">${r.account_type || ''}</td><td style="padding:6px 10px;text-align:right;font-family:var(--mono);">${debit}</td><td style="padding:6px 10px;text-align:right;font-family:var(--mono);">${credit}</td></tr>`;
      });
      html += `</tbody></table></div>`;
      html += `<div style="display:flex;justify-content:space-between;margin-top:12px;padding-top:12px;border-top:2px solid var(--border-hi);font-weight:700;"><span>Totals ${data.balanced ? '✓' : dgIcon('warning', 12)}</span><span style="font-family:var(--mono);">Debits ${_fmtMoney(data.total_debits_cents)} · Credits ${_fmtMoney(data.total_credits_cents)}</span></div>`;
      body.innerHTML = html;
    } catch(e) { body.innerHTML = `<p style="color:var(--err);">Error: ${e.message}</p>`; }
  }

  function rptYearEndDownload() {
    const yr = document.getElementById('rpt-year-end-year')?.value || String(new Date().getFullYear() - 1);
    const link = document.getElementById('rpt-year-end-link');
    if (link) link.href = `/api/reports/year-end.zip?year=${encodeURIComponent(yr)}`;
    return true;
  }

  function rptDeductibleDownload() {
    const from = document.getElementById('rpt-ded-from')?.value || '';
    const to = document.getElementById('rpt-ded-to')?.value || '';
    if (!from || !to) { alert('Select a date range first.'); return false; }
    const includeLedger = document.getElementById('rpt-ded-ledger')?.checked ? '1' : '0';
    const link = document.getElementById('rpt-ded-link');
    if (link) link.href = `/api/reports/deductible-expenses.csv?date_from=${encodeURIComponent(from)}&date_to=${encodeURIComponent(to)}&include_ledger=${includeLedger}`;
    return true;
  }

  function _rpt1099kYear() {
    const el = document.getElementById('rpt-1099k-year');
    if (el && !el.value) el.value = String(new Date().getFullYear());
    return (el && el.value) || String(new Date().getFullYear());
  }

  function rpt1099kDownload() {
    const yr = _rpt1099kYear();
    const link = document.getElementById('rpt-1099k-link');
    if (link) link.href = `/api/reports/1099k.csv?year=${encodeURIComponent(yr)}`;
    return true;
  }

  async function rpt1099kView() {
    const yr = _rpt1099kYear();
    const box = document.getElementById('rpt-1099k-result');
    if (box) box.textContent = 'Loading…';
    try {
      const res = await fetch(`/api/reports/1099k?year=${encodeURIComponent(yr)}`);
      const r = await res.json();
      const esc = (s) => String(s == null ? '' : s).replace(/[&<>]/g, m => ({'&':'&amp;','<':'&lt;','>':'&gt;'}[m]));
      const table = (title, groups) => {
        if (!groups || !groups.length) return `<div style="color:var(--text-dim);">${title}: no payments recorded.</div>`;
        const rows = groups.map(g => `<tr>
          <td style="padding:3px 8px;">${esc(g.label)}</td>
          <td style="padding:3px 8px;text-align:right;">${g.order_count}</td>
          <td style="padding:3px 8px;text-align:right;">${dgMoney(g.gross)}</td>
          <td style="padding:3px 8px;text-align:right;color:var(--err);">${g.refunds_cents ? '−' + dgMoney(g.refunds) : '—'}</td>
          <td style="padding:3px 8px;text-align:right;">${dgMoney(g.net)}</td>
        </tr>`).join('');
        return `<div style="margin-bottom:6px;font-weight:600;">${title}</div>
          <table style="width:100%;border-collapse:collapse;font-size:12px;margin-bottom:10px;">
            <thead><tr style="color:var(--text-dim);border-bottom:1px solid var(--border);">
              <th style="text-align:left;padding:3px 8px;">Key</th><th style="text-align:right;padding:3px 8px;">Orders</th>
              <th style="text-align:right;padding:3px 8px;">Gross</th><th style="text-align:right;padding:3px 8px;">Refunds</th>
              <th style="text-align:right;padding:3px 8px;">Net</th></tr></thead>
            <tbody>${rows}</tbody></table>`;
      };
      if (box) box.innerHTML =
        table('By payment processor (who issues the 1099-K)', r.by_processor) +
        table('By sales channel', r.by_channel) +
        `<div style="color:var(--text-dim);font-size:11px;line-height:1.5;">${esc(r.note)}</div>`;
    } catch (e) {
      if (box) box.textContent = 'Could not load: ' + e.message;
    }
  }
  if (typeof window !== 'undefined') {
    window.rpt1099kView = rpt1099kView;
    window.rpt1099kDownload = rpt1099kDownload;
  }

  function _rpt1099necYear() {
    const el = document.getElementById('rpt-1099nec-year');
    if (el && !el.value) el.value = String(new Date().getFullYear());
    return (el && el.value) || String(new Date().getFullYear());
  }

  function rpt1099necDownload() {
    const yr = _rpt1099necYear();
    const link = document.getElementById('rpt-1099nec-link');
    if (link) link.href = `/api/reports/1099nec.csv?year=${encodeURIComponent(yr)}`;
    return true;
  }

  async function rpt1099necView() {
    const yr = _rpt1099necYear();
    const box = document.getElementById('rpt-1099nec-result');
    if (box) box.textContent = 'Loading…';
    try {
      const res = await fetch(`/api/reports/1099nec?year=${encodeURIComponent(yr)}`);
      const r = await res.json();
      const esc = (s) => String(s == null ? '' : s).replace(/[&<>]/g, m => ({'&':'&amp;','<':'&lt;','>':'&gt;'}[m]));
      if (!r.vendors || !r.vendors.length) {
        if (box) box.innerHTML = `<div style="color:var(--text-dim);">No contractor or legal payments recorded for ${esc(yr)}.</div>`;
        return;
      }
      const rows = r.vendors.map(v => `<tr style="${v.needs_1099 ? 'font-weight:600;' : 'color:var(--text-soft);'}">
        <td style="padding:3px 8px;">${v.needs_1099 ? dgIcon('flag', 12) + ' ' : ''}${esc(v.vendor)}</td>
        <td style="padding:3px 8px;text-align:right;">${v.payment_count}</td>
        <td style="padding:3px 8px;text-align:right;">${dgMoney(v.reportable)}</td>
        <td style="padding:3px 8px;text-align:center;">${v.needs_1099 ? 'YES' : 'no'}</td>
      </tr>`).join('');
      if (box) box.innerHTML = `
        <div style="margin-bottom:6px;">${r.flagged_count} vendor${r.flagged_count === 1 ? '' : 's'} likely need a 1099-NEC (threshold $${Number(r.threshold).toFixed(0)}).</div>
        <table style="width:100%;border-collapse:collapse;font-size:12px;margin-bottom:8px;">
          <thead><tr style="color:var(--text-dim);border-bottom:1px solid var(--border);">
            <th style="text-align:left;padding:3px 8px;">Vendor</th><th style="text-align:right;padding:3px 8px;">Payments</th>
            <th style="text-align:right;padding:3px 8px;">Reportable</th><th style="text-align:center;padding:3px 8px;">1099?</th></tr></thead>
          <tbody>${rows}</tbody></table>
        <div style="color:var(--text-dim);font-size:11px;line-height:1.5;">${esc(r.note)}</div>`;
    } catch (e) {
      if (box) box.textContent = 'Could not load: ' + e.message;
    }
  }
  if (typeof window !== 'undefined') {
    window.rpt1099necView = rpt1099necView;
    window.rpt1099necDownload = rpt1099necDownload;
  }
