// admin-routing.jsx — Manager roster + timecard routing.
//
// The dispatch schedule is the source of truth: each posted job is owned by
// a field/ops MANAGER. When an RWIC submits a timecard, it routes to the
// manager who owns that job on the schedule. Managers are the FIRST approval
// step; accounting is the second.
//
// Also handles ingest of timecards submitted from the field tablet (written
// to localStorage by the tablet app) so they appear live in the Ops queue.

// ── Manager roster (ops supervisors who approve crews) ───────
const MANAGERS = [
  { id: 'mgr-cw', name: 'Carl Whitehorse', initials: 'CW', title: 'Field Supervisor — Northern',  region: 'MT / ND',      phone: '(406) 555-9911', empId: 'e-6601' },
  { id: 'mgr-lp', name: 'Lena Park',       initials: 'LP', title: 'Field Supervisor — Pacific',   region: 'WA / OR',      phone: '(206) 555-3380', empId: null },
  { id: 'mgr-av', name: 'Aaron Vance',     initials: 'AV', title: 'Field Supervisor — Mountain',  region: 'UT / NV / CA', phone: '(801) 555-6642', empId: null },
];

// ── Assign each posted job to a manager by region/railroad ───
// (deterministic — mirrors how a dispatcher would carve the territory)
const JOB_MANAGER = {
  'JOB-24179': 'mgr-lp', // Cascade Sub, WA
  'JOB-24166': 'mgr-lp', // Stampede, WA
  'JOB-24201': 'mgr-av', // Feather River, CA
  'JOB-24210': 'mgr-av', // Salt Lake, UT
  'JOB-24208': 'mgr-av', // Sierra, NV
  'JOB-24155': 'mgr-cw', // Hi-Line, MT
  'JOB-24225': 'mgr-cw', // Cumberland, MD (East — temp under CW)
};
if (typeof JOBS !== 'undefined') {
  JOBS.forEach(j => { j.managerId = JOB_MANAGER[j.id] || 'mgr-cw'; });
}

const managerById = (id) => MANAGERS.find(m => m.id === id) || null;
const managerForJob = (jobId) => managerById(JOB_MANAGER[jobId] || 'mgr-cw');
function managerForTimecard(tc) { return managerForJob(tc.jobId); }

// ── Tablet → console ingest ──────────────────────────────────
// The field tablet writes submitted timecards to this localStorage key.
const TABLET_TC_KEY = 'rfp_submitted_timecards';

// Map a tablet payload onto an admin timecard record.
function ingestTabletTimecard(payload) {
  // Match employee by badge, job by projectNumber.
  const emp = (typeof EMPLOYEES !== 'undefined')
    ? EMPLOYEES.find(e => e.badge === payload.employeeBadge) : null;
  const job = (typeof JOBS !== 'undefined')
    ? JOBS.find(j => j.projectNumber === payload.projectNumber) : null;
  const blocks = (payload.blocks || []).map(b => ({
    code: b.code, hrs: +(+b.hrs).toFixed(2),
    state: b.state || job?.state || emp?.resident || '—',
  }));
  const total = blocks.reduce((s, b) => s + b.hrs, 0);
  return {
    id: payload.id || `tc-tablet-${payload.employeeBadge}-${payload.date}`,
    employeeId: emp?.id || 'e-2241',
    jobId: job?.id || 'JOB-24179',
    date: payload.date,
    blocks,
    total,
    regular: Math.min(8, total),
    overtime: Math.max(0, total - 8),
    status: 'pending-ops',
    submitted: true,
    gpsVerified: true,
    flags: total - 8 > 4 ? ['extreme-ot'] : [],
    fromTablet: true,       // badge it as freshly arrived
  };
}

function readTabletTimecards() {
  try {
    const raw = localStorage.getItem(TABLET_TC_KEY);
    if (!raw) return [];
    const arr = JSON.parse(raw);
    return Array.isArray(arr) ? arr.map(ingestTabletTimecard) : [];
  } catch (e) { return []; }
}

// ── Briefing + Field Report ingest (→ Safety/Compliance queue) ──
const TABLET_BRIEFING_KEY = 'rfp_submitted_briefings';
const TABLET_REPORT_KEY   = 'rfp_submitted_reports';

function _matchEmpJob(payload) {
  const emp = (typeof EMPLOYEES !== 'undefined') ? EMPLOYEES.find(e => e.badge === payload.employeeBadge) : null;
  const job = (typeof JOBS !== 'undefined') ? JOBS.find(j => j.projectNumber === payload.projectNumber) : null;
  return { emp, job };
}

function ingestBriefing(p) {
  const { emp, job } = _matchEmpJob(p);
  const expiredCrew = 0; // crew expiry computed on tablet; placeholder
  const flagged = (p.riskFlags && p.riskFlags.length > 3) || (p.sigCount < p.crewTotal);
  return {
    id: p.id, kind: 'briefing',
    employeeId: emp?.id || 'e-2241', jobId: job?.id || 'JOB-24179',
    date: p.date, submittedAt: p.submittedAt,
    sigCount: p.sigCount, crewTotal: p.crewTotal,
    riskFlags: p.riskFlags || [], otsTypes: p.otsTypes || [],
    status: 'pending-review',
    autoFlag: flagged ? (p.sigCount < p.crewTotal ? 'Incomplete signatures' : 'Multiple red-zone risks') : null,
    fromTablet: true,
  };
}
function ingestReport(p) {
  const { emp, job } = _matchEmpJob(p);
  const flagged = p.photoCount < 4 || p.violations;
  return {
    id: p.id, kind: 'report',
    employeeId: emp?.id || 'e-2241', jobId: job?.id || 'JOB-24179',
    date: p.date, submittedAt: p.submittedAt,
    photoCount: p.photoCount, trainCount: p.trainCount, hours: p.hours, violations: p.violations,
    status: 'pending-review',
    autoFlag: p.violations ? 'Rules violation reported' : (p.photoCount < 4 ? 'Below photo minimum' : null),
    fromTablet: true,
  };
}
function readTabletSubmissions() {
  const out = [];
  try {
    const b = JSON.parse(localStorage.getItem(TABLET_BRIEFING_KEY) || '[]');
    if (Array.isArray(b)) out.push(...b.map(ingestBriefing));
  } catch (e) {}
  try {
    const r = JSON.parse(localStorage.getItem(TABLET_REPORT_KEY) || '[]');
    if (Array.isArray(r)) out.push(...r.map(ingestReport));
  } catch (e) {}
  return out;
}

Object.assign(window, {
  MANAGERS, JOB_MANAGER, managerById, managerForJob, managerForTimecard,
  TABLET_TC_KEY, ingestTabletTimecard, readTabletTimecards,
  TABLET_BRIEFING_KEY, TABLET_REPORT_KEY, ingestBriefing, ingestReport, readTabletSubmissions,
});
