// backend-db.jsx — The "backend" layer for the console: a shared account
// directory, company configuration, and a localStorage-backed persistence
// store standing in for the server. In production these reads/writes hit the
// API; the shapes are identical.

// ── Persistence ──────────────────────────────────────────────
const DB_KEY = 'rfp_backend_v1';
function dbLoad() {
  try { return JSON.parse(localStorage.getItem(DB_KEY) || '{}'); } catch (e) { return {}; }
}
function dbSave(patch) {
  try {
    const cur = dbLoad();
    localStorage.setItem(DB_KEY, JSON.stringify({ ...cur, ...patch }));
    return true;
  } catch (e) { return false; }
}

// ── Account directory (identity for all three apps) ──────────
// Every person who can sign in anywhere: field RWICs (tablet PIN), back-office
// staff (console), and the employee portal use the same directory.
const ACCOUNTS = [
  { id: 'u-ofc', name: 'Dana Whitfield',  email: 'dwhitfield@railflagspro.com', role: 'officer',    apps: ['console'],            status: 'active',   mfa: true,  lastLogin: '2026-05-30T06:12', empId: null },
  { id: 'u-ops', name: 'Lena Park',       email: 'lpark@railflagspro.com',      role: 'ops',        apps: ['console'],            status: 'active',   mfa: true,  lastLogin: '2026-05-30T05:48', empId: null },
  { id: 'u-saf', name: 'Ruth Calderon',   email: 'rcalderon@railflagspro.com',  role: 'safety',     apps: ['console'],            status: 'active',   mfa: true,  lastLogin: '2026-05-29T18:02', empId: null },
  { id: 'u-dsp', name: 'Omar Reyes',      email: 'oreyes@railflagspro.com',     role: 'dispatch',   apps: ['console'],            status: 'active',   mfa: false, lastLogin: '2026-05-30T05:30', empId: null },
  { id: 'u-act', name: 'Susan Kessler',   email: 'skessler@railflagspro.com',   role: 'accounting', apps: ['console'],            status: 'active',   mfa: true,  lastLogin: '2026-05-30T06:40', empId: null },
  { id: 'u-mh',  name: 'Marcus Hale',     email: 'mhale@railflagspro.com',      role: 'employee',   apps: ['tablet', 'portal'],   status: 'active',   mfa: false, lastLogin: '2026-05-30T06:42', empId: 'e-2241' },
  { id: 'u-dr',  name: 'Diana Russo',     email: 'drusso@railflagspro.com',     role: 'employee',   apps: ['tablet', 'portal'],   status: 'active',   mfa: false, lastLogin: '2026-05-30T05:58', empId: 'e-1907' },
  { id: 'u-cw',  name: 'Carl Whitehorse', email: 'cwhitehorse@railflagspro.com',role: 'ops',        apps: ['console', 'tablet'],  status: 'active',   mfa: true,  lastLogin: '2026-05-29T17:30', empId: 'e-6601' },
  { id: 'u-tb',  name: 'Tomás Beltrán',   email: 'tbeltran@railflagspro.com',   role: 'employee',   apps: ['tablet', 'portal'],   status: 'suspended', mfa: false, lastLogin: '2026-05-20T07:10', empId: 'e-3025' },
];

// ── Company configuration ────────────────────────────────────
// Add-on modules (sold separately at purchase — NOT part of the base platform).
// Existing payroll/flagging programs don't expose a customer portal, so this
// ships OFF and is enabled per-contract when the client buys the module.
const ADDON_MODULES = [
  { id: 'client-portal', name: 'Client Portal', priceNote: '+$250/mo', enabledByDefault: false,
    desc: 'Branded login for your railroad customers to see their own crews on site, compliance status, and invoices.',
    sells: 'Differentiator — most flagging vendors have nothing like it.' },
  { id: 'api-webhooks', name: 'Outbound API & Webhooks', priceNote: '+$120/mo', enabledByDefault: false,
    desc: 'Push pay-run, timecard, and compliance events to a customer’s own systems.',
    sells: 'For enterprise clients with their own data lake.' },
  { id: 'advanced-analytics', name: 'Advanced Analytics', priceNote: '+$90/mo', enabledByDefault: false,
    desc: 'Trend dashboards, utilization, and margin analysis across clients and railroads.',
    sells: 'Officer-level business intelligence.' },
];

const COMPANY_CONFIG = {
  legalName: 'RailFlagsPro LLC',
  ein: '84-2207715',
  rrbBaNumber: 'BA-077215',
  address: '1200 Rail Yard Rd, Bozeman MT 59715',
  fiscalYear: 'Calendar (Jan–Dec)',
  payFrequency: 'Bi-weekly',
  otThreshold: 8,
  otMultiplier: 1.5,
  mileageRate: 0.67,
  perDiemRate: 79,
  taxPolicy: 'hybrid',
  rrbEnabled: true,
  // Add-on entitlements — default OFF; flipped on when purchased.
  addons: { 'client-portal': false, 'api-webhooks': false, 'advanced-analytics': false },
};

// ── Data model (for the "deeper dive" — what the backend stores) ─
const DATA_MODEL = [
  { entity: 'Account',     count: ACCOUNTS.length, fields: 'id, name, email, role, apps[], status, mfa, empId', source: 'Identity directory' },
  { entity: 'Employee',    count: 8,  fields: 'id, badge, role, baseRate, resident, rrbContributor, certs[]', source: 'HR / payroll' },
  { entity: 'Job',         count: 7,  fields: 'id, projectNumber, client, railroad, mp, managerId, rwicIds[]', source: 'Dispatch' },
  { entity: 'Timecard',    count: 35, fields: 'id, employeeId, jobId, date, blocks[], status, gps', source: 'Field tablet → console' },
  { entity: 'Briefing',    count: '∞', fields: 'id, jobId, date, otsTypes[], riskFlags[], crew[], sigCount', source: 'Field tablet → Safety' },
  { entity: 'FieldReport', count: '∞', fields: 'id, jobId, date, hours, photoCount, trains[], violations', source: 'Field tablet → Safety' },
  { entity: 'PayrollRun',  count: 4,  fields: 'id, period, gross, taxes, rrta, target, status', source: 'Accounting' },
  { entity: 'Invoice',     count: 5,  fields: 'id, clientId, period, lineItems[], amount, status', source: 'Billing' },
  { entity: 'Document',    count: '∞', fields: 'kind, ownerId, payload, generatedAt, signedAt', source: 'Documents engine' },
];

Object.assign(window, { DB_KEY, dbLoad, dbSave, ACCOUNTS, COMPANY_CONFIG, DATA_MODEL, ADDON_MODULES });

// Entitlement check usable from any app: has the company purchased an add-on?
window.RFPaddon = function (id) {
  try {
    const cfg = (dbLoad().company && dbLoad().company.addons) || COMPANY_CONFIG.addons;
    return !!cfg[id];
  } catch (e) { return false; }
};
