// admin-docs.jsx — Connects the console to the shared documents engine.
// <DocHost> renders whatever doc is in ctx.activeDoc inside <DocViewer>.
// Builder helpers assemble template payloads from console state, so any view
// can call launchDoc(buildX(...)).

const EMPLOYER_INFO = {
  name: 'RailFlagsPro LLC',
  ein: '84-2207715',
  address: '1200 Rail Yard Rd, Bozeman MT 59715',
};

// Fake-but-stable SSN per employee
const ssnFor = (id) => {
  const n = String(Math.abs(id.split('').reduce((a, c) => a + c.charCodeAt(0), 0)) % 9000 + 1000);
  return `•••-••-${n}`;
};
const ssnFull = (id) => {
  const n = String(Math.abs(id.split('').reduce((a, c) => a + c.charCodeAt(0), 0)) % 9000 + 1000);
  return `541-22-${n}`;
};

// ── Pay stub payload from one employee's period cards ────────
function buildPayStub({ company, employee, cards, taxPolicy, ytdGross }) {
  const reg = cards.reduce((s, t) => s + t.regular, 0);
  const ot = cards.reduce((s, t) => s + t.overtime, 0);
  const regPay = reg * employee.baseRate;
  const otPay = ot * employee.baseRate * 1.5;
  const gross = regPay + otPay;

  const blocks = cards.flatMap(t => t.blocks);
  const alloc = allocateWages(employee, blocks, taxPolicy);
  const stateTax = alloc.reduce((s, b) => s + b.taxAmt, 0);
  const rr = computeRRTA(employee, ytdGross || 0, gross, {});
  const eeLines = rr.lines;
  const erLines = rr.employer;
  const fed = gross * 0.12; // simple federal w/h estimate for the stub

  const taxes = [
    { label: 'Federal income tax', amount: fed },
    { label: `State income tax`, amount: stateTax },
    ...eeLines.map(l => ({ label: l.label, amount: l.amount })),
  ];
  const totalTax = taxes.reduce((s, t) => s + Math.abs(t.amount), 0);
  const net = gross - totalTax;

  return {
    kind: 'paystub',
    title: `Pay stub · ${employee.name}`,
    subtitle: 'Earnings statement',
    payload: {
      company,
      employee: { name: employee.name, badge: employee.badge, address: `${employee.homeBase}`, ssnMasked: ssnFor(employee.id) },
      period: '2026-05-18 — 2026-05-31',
      payDate: '2026-06-05',
      lines: [
        { code: 'F10', desc: 'RWIC — Railroad Flagger (Reg)', hrs: reg, rate: employee.baseRate, amount: regPay },
        ...(ot > 0 ? [{ code: 'F10', desc: 'Overtime (1.5×)', hrs: ot, rate: employee.baseRate * 1.5, amount: otPay }] : []),
      ],
      taxes,
      employer: erLines.map(l => ({ label: l.label, amount: l.amount })),
      gross, net,
      ytd: { gross: (ytdGross || 0) + gross, tax: ((ytdGross || 0) + gross) * 0.27, net: ((ytdGross || 0) + gross) * 0.73 },
    },
  };
}

// ── W-2 payload ──────────────────────────────────────────────
function buildW2({ company, employee, ytdGross }) {
  const gross = ytdGross || 40000;
  const rr = computeRRTA(employee, 0, gross, {});
  const t1 = rr.lines.find(l => l.label.includes('Tier I'));
  const t2 = rr.lines.find(l => l.label.includes('Tier II'));
  const med = rr.lines.find(l => l.label.includes('Medicare'));
  const stateRate = (STATES.find(s => s.code === employee.resident) || { tax: 0 }).tax;
  return {
    kind: 'w2',
    title: `Form W-2 (2025) · ${employee.name}`,
    subtitle: 'Wage and Tax Statement',
    payload: {
      year: 2025,
      control: `RFP-${employee.badge}`,
      employer: EMPLOYER_INFO,
      employee: { name: employee.name, ssn: ssnFull(employee.id), address: employee.homeBase },
      boxes: {
        1: gross, 2: gross * 0.12,
        3: employee.rrbContributor ? 0 : Math.min(gross, 168600),
        4: employee.rrbContributor ? 0 : Math.min(gross, 168600) * 0.062,
        5: gross, 6: gross * 0.0145, 7: 0, 8: 0, 10: 0,
      },
      box14: employee.rrbContributor ? [
        { code: 'RRT1', amount: t1 ? t1.amount : 0 },
        { code: 'RRT2', amount: t2 ? t2.amount : 0 },
        { code: 'RRTM', amount: med ? med.amount : 0 },
      ] : [{ code: 'FICA', amount: gross * 0.0765 }],
      state: { code: employee.resident, id: `${employee.resident}-99-217`, wages: gross, tax: gross * stateRate },
    },
  };
}

// ── BA-3 payload (all RRB employees) ─────────────────────────
function buildBA3({ employees, ytdGross }) {
  const rrb = employees.filter(e => e.rrbContributor);
  const rows = rrb.map(e => {
    const g = ytdGross[e.id] || 0;
    const rr = computeRRTA(e, 0, g, {});
    return {
      name: e.name, ssn: ssnFull(e.id),
      tier1: Math.min(g, 168600), tier2: Math.min(g, 125100), medicare: g, comp: g,
    };
  });
  const totals = rows.reduce((a, r) => ({ tier1: a.tier1 + r.tier1, tier2: a.tier2 + r.tier2, medicare: a.medicare + r.medicare }), { tier1: 0, tier2: 0, medicare: 0 });
  return {
    kind: 'ba3',
    title: 'Form BA-3 · Annual Report',
    subtitle: 'RRB Creditable Compensation',
    payload: { year: 2025, employer: EMPLOYER_INFO, baNumber: 'BA-077215', employees: rows, totals },
  };
}

// ── BA-4 payload (sample adjustments) ────────────────────────
function buildBA4({ employees }) {
  return {
    kind: 'ba4',
    title: 'Form BA-4 · Adjustments',
    subtitle: 'RRB Compensation Adjustments',
    payload: {
      year: 2025, employer: EMPLOYER_INFO, baNumber: 'BA-077215',
      adjustments: [
        { name: employees[0].name, ssn: ssnFull(employees[0].id), type: 'Tier II', fromAmt: 45200, toAmt: 46100, reason: 'Late OT from Dec period 26 added' },
        { name: employees[2].name, ssn: ssnFull(employees[2].id), type: 'Tier I',  fromAmt: 32100, toAmt: 31600, reason: 'Duplicate timecard reversed' },
      ],
    },
  };
}

// ── Briefing / Field report payloads (from a submission record) ─
function buildBriefingDoc({ company, sub, employee, job, crew }) {
  return {
    kind: 'briefing',
    title: `Job Briefing · ${job ? job.id : ''}`,
    subtitle: D_date(sub.date),
    payload: {
      company, date: sub.date, time: '06:42',
      projectNumber: job ? job.projectNumber : '—', railroad: job ? job.railroad : '—',
      subdivision: job ? job.subdivision : '—', milepost: job ? job.mp : '—',
      rwic: employee ? employee.name : 'RWIC', badge: employee ? employee.badge : '',
      foreman: job ? job.foreman : '—', people: 8, equip: 3,
      otsTypes: sub.otsTypes || [], ppos: '25 ft north shoulder',
      riskFlags: (sub.riskFlags || []).map(riskLabel), riskPlan: 'Adjacent-track + equipment swing briefed; PPOS confirmed.',
      crew: crew || [], sigCount: sub.sigCount, crewTotal: sub.crewTotal,
    },
  };
}
function buildReportDoc({ company, sub, employee, job }) {
  return {
    kind: 'report',
    title: `Field Report · ${job ? job.id : ''}`,
    subtitle: D_date(sub.date),
    payload: {
      company, date: sub.date,
      projectNumber: job ? job.projectNumber : '—', subdivision: job ? job.subdivision : '—', milepost: job ? job.mp : '—',
      hours: sub.hours, workType: job ? job.name : 'Track work performed within RR right-of-way.',
      trainCount: sub.trainCount, trains: [], photoCount: sub.photoCount,
      switches: false, trackDelays: false, violations: sub.violations,
      rwic: employee ? employee.name : 'RWIC', badge: employee ? employee.badge : '', contractorRep: job ? job.foreman : '',
    },
  };
}

// ── DocHost — renders the active doc ─────────────────────────
function DocHost() {
  const { activeDoc, setActiveDoc } = useAdmin();
  const { tweaks } = useTweakValues();
  if (!activeDoc) return null;
  const { kind, payload, title, subtitle, file } = activeDoc;
  return (
    <DocViewer open={true} onClose={() => setActiveDoc(null)} title={title} subtitle={subtitle} file={file} accent="var(--accent)">
      {kind === 'paystub'  && <PayStubDoc data={payload} />}
      {kind === 'w2'       && <W2Doc data={payload} />}
      {kind === 'ba3'      && <BA3Doc data={payload} />}
      {kind === 'ba4'      && <BA4Doc data={payload} />}
      {kind === 'briefing' && <BriefingDoc data={payload} />}
      {kind === 'report'   && <FieldReportDoc data={payload} />}
      {kind === 'csvpreview' && <CSVPreview content={payload.content} note={payload.note} />}
    </DocViewer>
  );
}

// Simple CSV/IIF preview rendered as a table inside the sheet
function CSVPreview({ content, note }) {
  const rows = content.split(/\r?\n/).slice(0, 40).map(r => r.split(/[,\t]/));
  return (
    <div style={{ padding: 24 }}>
      <div style={{ fontWeight: 700, fontSize: 15, marginBottom: 4 }}>Export preview</div>
      <div style={{ fontSize: 11.5, color: '#666', marginBottom: 12 }}>{note}</div>
      <table style={{ width: '100%', fontSize: 10.5, borderCollapse: 'collapse' }} className="rfp-doc-mono">
        <tbody>
          {rows.map((r, i) => (
            <tr key={i} style={{ borderBottom: '1px solid #eee', background: i === 0 ? '#f3f3f1' : 'transparent', fontWeight: i === 0 ? 700 : 400 }}>
              {r.map((c, j) => <td key={j} style={{ padding: '4px 8px', whiteSpace: 'nowrap' }}>{c}</td>)}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

Object.assign(window, {
  EMPLOYER_INFO, ssnFor, ssnFull,
  buildPayStub, buildW2, buildBA3, buildBA4, buildBriefingDoc, buildReportDoc,
  DocHost, CSVPreview,
});
