// Dashboard mock data
const PROJECTS = [
  {
    id: "meridian",
    client: "Meridian Arts Foundation",
    type: "Nonprofit Audit",
    fye: "6/30/2026",
    partner: "J. Harrington",
    manager: "M. Patel",
    phase: "Prelim",
    phaseIdx: 1,
    fee: 48500,
    billed: 19200,
    budgetHours: 280,
    actualHours: 178,
    budgetedToDate: 68,   // % of budget expected by now
    actualToDate: 82,     // % of budget actually burned
    health: "red",        // red | yellow | green
    binderPct: 42,
    suralinkPct: 64,
    dueDate: "May 11, 2026",
    team: [
      { initials: "JH", name: "J. Harrington", role: "Partner", hours: 12 },
      { initials: "MP", name: "M. Patel", role: "Manager", hours: 46 },
      { initials: "MS", name: "M. Singh", role: "Senior", hours: 78 },
      { initials: "RT", name: "R. Tran", role: "Associate", hours: 42 },
    ],
    binders: [
      { id: "A", name: "A · Planning", wps: 18, signed: 12, status: "In review" },
      { id: "B", name: "B · Cash", wps: 14, signed: 14, status: "Complete" },
      { id: "C", name: "C · Investments", wps: 9, signed: 3, status: "In progress" },
      { id: "D", name: "D · Receivables", wps: 12, signed: 5, status: "In progress" },
      { id: "E", name: "E · Grants & Contributions", wps: 22, signed: 7, status: "Behind" },
      { id: "F", name: "F · Fixed Assets", wps: 8, signed: 0, status: "Not started" },
      { id: "G", name: "G · Payroll", wps: 11, signed: 4, status: "In progress" },
      { id: "H", name: "H · Leases & Commitments", wps: 7, signed: 2, status: "In progress" },
    ],
  },
  {
    id: "northpoint",
    client: "Northpoint Medical Group",
    type: "Reviewed Financials",
    fye: "12/31/2025",
    partner: "J. Harrington",
    manager: "D. Chen",
    phase: "Fieldwork",
    phaseIdx: 2,
    fee: 62000,
    billed: 41800,
    budgetHours: 340,
    actualHours: 228,
    budgetedToDate: 70,
    actualToDate: 67,
    health: "green",
    binderPct: 71,
    suralinkPct: 88,
    dueDate: "Apr 30, 2026",
    team: [
      { initials: "JH", name: "J. Harrington", role: "Partner", hours: 14 },
      { initials: "DC", name: "D. Chen", role: "Manager", hours: 52 },
      { initials: "LM", name: "L. Mendes", role: "Senior", hours: 96 },
      { initials: "KB", name: "K. Barlow", role: "Associate", hours: 66 },
    ],
    binders: [
      { id: "A", name: "A · Planning", wps: 16, signed: 16, status: "Complete" },
      { id: "B", name: "B · Cash", wps: 12, signed: 12, status: "Complete" },
      { id: "C", name: "C · AR & Allowance", wps: 18, signed: 14, status: "In review" },
      { id: "D", name: "D · Revenue", wps: 20, signed: 13, status: "In progress" },
      { id: "E", name: "E · Payroll", wps: 10, signed: 7, status: "In progress" },
      { id: "F", name: "F · Debt", wps: 9, signed: 9, status: "Complete" },
    ],
  },
  {
    id: "cascadia",
    client: "Cascadia Logistics LLC",
    type: "Tax + Compilation",
    fye: "12/31/2025",
    partner: "J. Harrington",
    manager: "S. Okonkwo",
    phase: "Wrap",
    phaseIdx: 4,
    fee: 28500,
    billed: 27200,
    budgetHours: 180,
    actualHours: 162,
    budgetedToDate: 95,
    actualToDate: 90,
    health: "green",
    binderPct: 96,
    suralinkPct: 100,
    dueDate: "Mar 15, 2026",
    team: [
      { initials: "JH", name: "J. Harrington", role: "Partner", hours: 8 },
      { initials: "SO", name: "S. Okonkwo", role: "Manager", hours: 42 },
      { initials: "PV", name: "P. Valdez", role: "Senior", hours: 68 },
    ],
    binders: [
      { id: "A", name: "A · Tax Return", wps: 24, signed: 24, status: "Complete" },
      { id: "B", name: "B · Supporting Schedules", wps: 14, signed: 14, status: "Complete" },
      { id: "C", name: "C · Compilation", wps: 12, signed: 10, status: "In review" },
    ],
  },
  {
    id: "sterling",
    client: "Sterling Community Trust",
    type: "Single Audit (Uniform Guidance)",
    fye: "6/30/2026",
    partner: "J. Harrington",
    manager: "M. Patel",
    phase: "Activation",
    phaseIdx: 0,
    fee: 72000,
    billed: 4800,
    budgetHours: 420,
    actualHours: 52,
    budgetedToDate: 10,
    actualToDate: 12,
    health: "yellow",
    binderPct: 8,
    suralinkPct: 14,
    dueDate: "May 18, 2026",
    team: [
      { initials: "JH", name: "J. Harrington", role: "Partner", hours: 4 },
      { initials: "MP", name: "M. Patel", role: "Manager", hours: 10 },
      { initials: "EN", name: "E. Nakamura", role: "Senior", hours: 28 },
      { initials: "RT", name: "R. Tran", role: "Associate", hours: 10 },
    ],
    binders: [
      { id: "A", name: "A · Planning", wps: 18, signed: 2, status: "In progress" },
      { id: "B", name: "B · Risk Assessment", wps: 14, signed: 1, status: "In progress" },
    ],
  },
];

const CHAT_SCRIPT = [
  { role: "user", text: "Why are we red on Meridian?" },
  { role: "bot",  text: "Meridian is 14% over budget through Prelim. Two drivers: grants testing (Binder E) took 32 hours vs. 18 budgeted — the client delivered award letters late, which pushed confirmations into a second round. Cash testing was on budget." },
  { role: "user", text: "What can we do to recover?" },
  { role: "bot",  text: "Three options, ranked by impact:\n\n1. Tighten scope on Binder E grants — drop the two low‑dollar federal pass‑throughs under the 5% threshold (saves ~14 hours, no GAAS impact).\n2. Reassign M. Singh's Binder D receivables to R. Tran — Singh bills at a higher rate, Tran has capacity this week.\n3. Push the engagement letter amendment to the client to recover the $3.2K of grant‑related overrun as OOS." },
  { role: "user", text: "Who's signed off on Meridian Binder B?" },
  { role: "bot",  text: "Binder B (Cash) is fully signed off. Prepared by R. Tran on Apr 18, reviewed by M. Singh on Apr 21, manager sign‑off by M. Patel on Apr 22. Ready for partner review." },
  { role: "user", text: "Which projects are at risk right now?" },
  { role: "bot",  text: "One red, one yellow:\n\n• Meridian Arts — red. 14% over budget at Prelim. (details above)\n• Sterling Community Trust — yellow. Just entered Activation; client portal activity is 14% vs. 28% expected at Day 7. Suggest a check‑in call before Friday." },
];

// Users available in the user-switcher
const USERS = [
  { id: "jh", initials: "JH", name: "J. Harrington", role: "Managing Partner", roleKey: "partner" },
  { id: "mp", initials: "MP", name: "M. Patel",     role: "Audit Manager",    roleKey: "manager"  },
  { id: "rt", initials: "RT", name: "R. Tran",       role: "Audit Associate",  roleKey: "associate"},
];

// MANAGER (M. Patel) view data — engagements they manage: Meridian + Sterling
const MANAGER_DATA = {
  user: USERS[1],
  engagementIds: ["meridian", "sterling"],
  // Review queue — sign-off backlog awaiting manager review
  reviewQueue: [
    { id: "rv1", project: "Meridian Arts",     ref: "B-201",  binder: "B · Cash",       prep: "RT", title: "Bank reconciliation walkthrough — Sept",  age: 1, stale: false, prio: "med"  },
    { id: "rv2", project: "Meridian Arts",     ref: "C-104",  binder: "C · Investments", prep: "MS", title: "Endowment fair value memo",               age: 2, stale: false, prio: "med"  },
    { id: "rv3", project: "Meridian Arts",     ref: "E-318",  binder: "E · Grants",     prep: "MS", title: "Federal pass-through schedule (round 2)", age: 6, stale: true,  prio: "high" },
    { id: "rv4", project: "Sterling Trust",    ref: "A-002",  binder: "A · Planning",   prep: "EN", title: "Risk assessment matrix — Title III",      age: 0, stale: false, prio: "med"  },
    { id: "rv5", project: "Meridian Arts",     ref: "D-211",  binder: "D · Receivables",prep: "RT", title: "Pledges receivable confirmations log",    age: 3, stale: false, prio: "low"  },
  ],
  // Team capacity — direct reports + assigned staff
  capacity: [
    { initials: "MS", name: "M. Singh",     role: "Senior",    util: 112, status: "over" },
    { initials: "EN", name: "E. Nakamura",  role: "Senior",    util: 88,  status: "ok"   },
    { initials: "RT", name: "R. Tran",      role: "Associate", util: 96,  status: "warn" },
    { initials: "KB", name: "K. Barlow",    role: "Associate", util: 71,  status: "ok"   },
    { initials: "PV", name: "P. Valdez",    role: "Senior",    util: 64,  status: "ok"   },
  ],
  // Client communication SLA
  clientSLA: [
    { client: "Meridian Arts Foundation", contact: "L. Park, CFO",     openItems: 7, lastReply: "18h", overdue: 2 },
    { client: "Sterling Community Trust", contact: "D. Vasquez, Ctlr.", openItems: 12, lastReply: "3d", overdue: 5 },
  ],
  // Manager-level KPIs
  kpis: {
    reviewBacklog: 5,
    staleNotes: 1,
    teamUtil: 86,
    weekHours: 38,
  },
};

// ASSOCIATE (R. Tran) view data
const ASSOCIATE_DATA = {
  user: USERS[2],
  // Today's tasks / work papers assigned to them
  tasks: [
    { id: "t1", title: "Tie out Binder D pledges to subledger",     project: "Meridian Arts",  ref: "D-211", est: 2.5, done: false, prio: "high", due: "Today"     },
    { id: "t2", title: "Send 2nd-round confirmations on grants",     project: "Meridian Arts",  ref: "E-318", est: 1.0, done: false, prio: "high", due: "Today"     },
    { id: "t3", title: "Address review notes on Cash walkthrough",   project: "Meridian Arts",  ref: "B-201", est: 1.5, done: false, prio: "med",  due: "Today"     },
    { id: "t4", title: "Vouch 25 receivable additions to source",    project: "Sterling Trust", ref: "C-080", est: 3.0, done: false, prio: "med",  due: "Tomorrow"  },
    { id: "t5", title: "Update PBC tracker for grants section",      project: "Meridian Arts",  ref: "E-002", est: 0.5, done: true,  prio: "low",  due: "Yesterday" },
    { id: "t6", title: "Read AICPA SAS 145 risk assessment guide",   project: "Learning",       ref: "L&D",   est: 1.0, done: false, prio: "low",  due: "This week" },
  ],
  // Review notes pointed at them (open + recently cleared)
  myNotes: [
    { id: "n1", from: "MS", fromName: "M. Singh",  ref: "B-201", title: "Tie reconciling deposit to bank statement page 4 — note source.", age: "1d", status: "open"     },
    { id: "n2", from: "MP", fromName: "M. Patel", ref: "D-211", title: "Add subsequent receipt evidence for the two large pledges.",       age: "3h", status: "open"     },
    { id: "n3", from: "MS", fromName: "M. Singh",  ref: "B-104", title: "Cleared — good work on the cutoff testing memo.",                  age: "2d", status: "cleared"  },
  ],
  // Time entries for the week (Mon-Sun)
  timeWeek: [
    { day: "Mon", date: "May 4", hours: 8.5, target: 8, state: "ok",    todo: false },
    { day: "Tue", date: "May 5", hours: 9.0, target: 8, state: "over",  todo: false },
    { day: "Wed", date: "May 6", hours: 0.0, target: 8, state: "today", todo: true  },
    { day: "Thu", date: "May 7", hours: 0.0, target: 8, state: "empty", todo: true  },
    { day: "Fri", date: "May 8", hours: 0.0, target: 8, state: "empty", todo: true  },
    { day: "Sat", date: "May 9", hours: 0.0, target: 0, state: "empty", todo: false },
    { day: "Sun", date: "May 10",hours: 0.0, target: 0, state: "empty", todo: false },
  ],
  // Upcoming meetings / commitments
  upcoming: [
    { time: "10:00", title: "Meridian — Daily standup",    where: "Teams", duration: "15m" },
    { time: "11:30", title: "1:1 with M. Singh",            where: "Office 4B", duration: "30m" },
    { time: "2:00",  title: "Grants confirmation walkthru", where: "Teams", duration: "45m" },
  ],
  // Personal feed — wins, learning prompts, feedback
  feed: [
    { kind: "win",  h: "Manager sign-off",  body: "M. Patel signed off Binder B (Cash) on Meridian — your prep, 8h under budget.",      when: "Yesterday" },
    { kind: "note", h: "Coaching",          body: "M. Singh added 3 review notes on D-211. Common theme: tie-out evidence linkage.",      when: "Today"     },
    { kind: "win",  h: "CPE",                body: "1.5 of 4.0 ethics CPE hours logged this quarter. SAS 145 module assigned.",            when: "This week" },
  ],
  kpis: {
    openTasks: 5,
    openNotes: 2,
    weekHours: 17.5,
    targetHours: 40,
    chargeable: 92, // %
  },
};

// Generate additional engagements so the book scales realistically.
// Partner J. Harrington should see ~50 across 5 managers; M. Patel ~12; R. Tran on ~5.
(function generateMoreProjects() {
  const MANAGERS = [
    { initials: "MP", name: "M. Patel" },
    { initials: "DC", name: "D. Chen" },
    { initials: "SO", name: "S. Okonkwo" },
    { initials: "RA", name: "R. Aoki" },
    { initials: "TF", name: "T. Fitzgerald" },
  ];
  const SENIORS = [
    { initials: "MS", name: "M. Singh" },
    { initials: "EN", name: "E. Nakamura" },
    { initials: "LM", name: "L. Mendes" },
    { initials: "PV", name: "P. Valdez" },
    { initials: "JD", name: "J. Donovan" },
    { initials: "HK", name: "H. Kim" },
  ];
  const ASSOCS = [
    { initials: "RT", name: "R. Tran" },
    { initials: "KB", name: "K. Barlow" },
    { initials: "AC", name: "A. Castillo" },
    { initials: "BO", name: "B. Olson" },
    { initials: "NJ", name: "N. Johar" },
    { initials: "FW", name: "F. Wagner" },
  ];
  const NAMES = [
    ["Brookline Hospital System","Nonprofit Audit"],["Hawthorne Charter Schools","Single Audit (UG)"],
    ["Pacific Coast Insurance","SOC 1 / Type 2"],["Maple Ridge Capital","Investment Co. Audit"],
    ["Northstar Bancorp","Bank Audit"],["Greenfield Energy Co-op","Cooperative Audit"],
    ["Saltwater Seafood Imports","Reviewed Financials"],["Vanguard Plumbing Supply","Compilation"],
    ["Cobalt Robotics Inc.","SOC 2 / Type 2"],["Veritas Pharmaceuticals","Reviewed Financials"],
    ["Ironwood Steel Fabricators","Tax + Audit"],["Lakeside Country Club","Nonprofit Audit"],
    ["Aurora Solar Holdings","Reviewed Financials"],["Coastal Marine Logistics","Tax + Compilation"],
    ["Highland Dairy Farms","Tax + Audit"],["Liberty Plaza REIT","Real Estate Audit"],
    ["Riverbend Medical Partners","Reviewed Financials"],["Cedar Grove Senior Living","Nonprofit Audit"],
    ["Apex Construction Group","Construction Audit"],["Summit Aerospace","Defense Contractor Audit"],
    ["Beacon Family Office","Trust & Estate"],["Bluestone Asset Mgmt","Investment Adviser Audit"],
    ["Falcon Telecom","Reviewed Financials"],["Riverside Public Library","Single Audit (UG)"],
    ["Granite State Insurance","Statutory Audit"],["Holloway Foundation","Nonprofit Audit"],
    ["Westgate Realty Trust","Real Estate Audit"],["Olympic Bottling Co.","Tax + Compilation"],
    ["Heritage Title & Escrow","Reviewed Financials"],["Coral Reef Resort Group","Hospitality Audit"],
    ["Tradewinds Shipping","Tax + Audit"],["Magnolia Press","Compilation"],
    ["Atlas Industrial Services","Reviewed Financials"],["Crestwood University","Single Audit (UG)"],
    ["Polaris Tech Ventures","SOC 2 / Type 2"],["Quincy Manufacturing","Reviewed Financials"],
    ["Sutton Place Realty","Real Estate Audit"],["Garrison & Pike LLP","Law Firm Audit"],
    ["Linden Park Conservancy","Nonprofit Audit"],["Mariner Insurance Group","Statutory Audit"],
    ["Birchwood Beverage","Tax + Compilation"],["Continental Freight","Reviewed Financials"],
    ["Tidewater Marina","Compilation"],["Stonebridge Health Plan","Healthcare Audit"],
    ["Evergreen Timber Co.","Tax + Audit"],["Pinnacle Security Group","Reviewed Financials"],
  ];
  const PHASES = [
    ["Activation", 0], ["Prelim", 1], ["Fieldwork", 2], ["Review", 3], ["Wrap", 4],
  ];
  // Deterministic pseudo-random
  let seed = 7;
  const rnd = () => { seed = (seed * 9301 + 49297) % 233280; return seed / 233280; };
  const pick = (arr) => arr[Math.floor(rnd() * arr.length)];

  // Distribution targets: M. Patel = 11 more (so 11 + Meridian + Sterling = 13≈12),
  // D. Chen = 10 (already has Northpoint), S. Okonkwo = 8 (already Cascadia), RA = 9, TF = 8 → ~46 + 4 = 50
  const dist = [
    { mgr: MANAGERS[0], count: 11 },
    { mgr: MANAGERS[1], count: 9  },
    { mgr: MANAGERS[2], count: 8  },
    { mgr: MANAGERS[3], count: 9  },
    { mgr: MANAGERS[4], count: 9  },
  ];
  const queue = [];
  dist.forEach(d => { for (let i = 0; i < d.count; i++) queue.push(d.mgr); });
  // Make sure R. Tran lands on ~5 of these (in addition to Meridian + Sterling = 7 total feels heavy;
  // we'll pick 3 more so they total ~5 across the book)
  const trAssignedIdx = new Set([2, 11, 27]); // arbitrary deterministic positions

  let nameIdx = 0;
  for (let i = 0; i < queue.length && nameIdx < NAMES.length; i++, nameIdx++) {
    const mgr = queue[i];
    const [client, type] = NAMES[nameIdx];
    const [phase, phaseIdx] = pick(PHASES);
    const id = client.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/-+$/, "");
    const fee = 25000 + Math.floor(rnd() * 100) * 1000;
    const budgetHours = 160 + Math.floor(rnd() * 28) * 20;
    const budgetedToDate = [12, 28, 55, 80, 95][phaseIdx] + Math.floor(rnd() * 8) - 4;
    const variance = Math.floor(rnd() * 30) - 12; // -12 .. +18
    const actualToDate = Math.max(5, Math.min(99, budgetedToDate + variance));
    const delta = actualToDate - budgetedToDate;
    const health = delta > 8 ? "red" : delta > 3 ? "yellow" : "green";
    const actualHours = Math.round(budgetHours * (actualToDate / 100));
    const billed = Math.round(fee * (budgetedToDate / 100) / 100) * 100;
    const binderPct = Math.max(2, Math.min(99, actualToDate + Math.floor(rnd() * 14) - 7));
    const suralinkPct = Math.max(5, Math.min(100, binderPct + Math.floor(rnd() * 18) - 4));
    const snr = pick(SENIORS);
    let asc = pick(ASSOCS);
    if (trAssignedIdx.has(i)) asc = ASSOCS[0]; // R. Tran
    const team = [
      { initials: "JH", name: "J. Harrington", role: "Partner",   hours: 4 + Math.floor(rnd() * 16) },
      { initials: mgr.initials, name: mgr.name, role: "Manager",  hours: 8 + Math.floor(rnd() * 40) },
      { initials: snr.initials, name: snr.name, role: "Senior",   hours: 12 + Math.floor(rnd() * 70) },
      { initials: asc.initials, name: asc.name, role: "Associate",hours: 8 + Math.floor(rnd() * 50) },
    ];
    const dueMonths = ["Mar","Apr","May","Jun","Jul","Aug","Sep"];
    const dueDate = `${pick(dueMonths)} ${1 + Math.floor(rnd() * 28)}, 2026`;
    PROJECTS.push({
      id, client, type, fye: pick(["6/30/2026","12/31/2025","9/30/2026","3/31/2026"]),
      partner: "J. Harrington", manager: mgr.name,
      phase, phaseIdx, fee, billed, budgetHours, actualHours, budgetedToDate, actualToDate,
      health, binderPct, suralinkPct, dueDate, team, binders: [],
    });
  }
})();

// Recompute manager + associate engagement scopes against the expanded book
window.MANAGER_ENGAGEMENT_IDS = PROJECTS.filter(p => p.manager === "M. Patel").map(p => p.id);
window.ASSOCIATE_ENGAGEMENT_IDS = PROJECTS.filter(p => p.team.some(t => t.initials === "RT")).map(p => p.id);

window.PROJECTS = PROJECTS;
window.CHAT_SCRIPT = CHAT_SCRIPT;
window.USERS = USERS;
window.MANAGER_DATA = MANAGER_DATA;
window.ASSOCIATE_DATA = ASSOCIATE_DATA;
