// WTS Cyprus — Operations Platform mock data (Build Track model)
// PBC = engagement-aware structured-data collection with a client portal.
// Replaces the earlier email-forwarding / AI-extraction POC model.

// ── Staff users ───────────────────────────────────────────────────────────
const USERS = [
  { id: 'u1', name: 'Andreas Pavlou',         email: 'a.pavlou@wtscy.com',        role: 'admin',   modules: ['pbc', 'tp'] },
  { id: 'u2', name: 'Maria Constantinou',     email: 'm.constantinou@wtscy.com',  role: 'partner', modules: ['pbc', 'tp'] },
  { id: 'u3', name: 'Stelios Hadjikyriakou',  email: 's.hadjikyriakou@wtscy.com', role: 'staff',   modules: ['pbc', 'tp'] },
  { id: 'u4', name: 'Elena Georgiou',         email: 'e.georgiou@wtscy.com',      role: 'staff',   modules: ['pbc'] },
  { id: 'u5', name: 'Christos Ioannou',       email: 'c.ioannou@wtscy.com',       role: 'staff',   modules: ['tp'] },
  { id: 'u6', name: 'Sofia Petrou',           email: 's.petrou@wtscy.com',        role: 'staff',   modules: ['pbc', 'tp'] },
];

// ── Service lines ─────────────────────────────────────────────────────────
const SERVICE_LINES = {
  audit:    { label: 'Audit',          short: 'Audit' },
  tp:       { label: 'Transfer Pricing', short: 'TP' },
  vat:      { label: 'VAT compliance', short: 'VAT' },
  cit:      { label: 'Corporate income tax', short: 'CIT' },
  payroll:  { label: 'Payroll',        short: 'Payroll' },
  accounting:{ label: 'Accounting',    short: 'Accounting' },
  private:  { label: 'Private client', short: 'Private' },
};

// ── Client profile registry (F5) ──────────────────────────────────────────
const CLIENTS = [
  { id: 'c1', legalName: 'Aegean Holdings (Cyprus) Ltd', regId: 'HE 184562', jurisdiction: 'Cyprus', status: 'active',
    serviceLines: ['audit', 'cit', 'vat'],
    contacts: [{ name: 'Elena Markou', email: 'e.markou@aegeanholdings.com.cy', role: 'Financial Controller' },
               { name: 'Andreas Christou', email: 'a.christou@aegeanholdings.com.cy', role: 'Group Accountant' }] },
  { id: 'c2', legalName: 'Cyprus Maritime Group Ltd', regId: 'HE 092311', jurisdiction: 'Cyprus', status: 'active',
    serviceLines: ['cit', 'vat', 'accounting'],
    contacts: [{ name: 'Markos Papadakis', email: 'm.papadakis@cyprusmaritime.com', role: 'CFO' },
               { name: 'Lefki Athanasiou', email: 'l.athanasiou@cyprusmaritime.com', role: 'Tax Manager' }] },
  { id: 'c3', legalName: 'Limassol Properties Ltd', regId: 'HE 210884', jurisdiction: 'Cyprus', status: 'active',
    serviceLines: ['tp', 'audit'],
    contacts: [{ name: 'Christina Iakovou', email: 'c.iakovou@limassolproperties.com.cy', role: 'Group Finance Director' }] },
  { id: 'c4', legalName: 'Nicosia Tech SA', regId: 'HE 331297', jurisdiction: 'Cyprus', status: 'active',
    serviceLines: ['audit', 'vat'],
    contacts: [{ name: 'Petros Loizou', email: 'p.loizou@nicosiatech.com', role: 'Head of Finance' }] },
  { id: 'c5', legalName: 'Larnaca Logistics Ltd', regId: 'HE 145903', jurisdiction: 'Cyprus', status: 'active',
    serviceLines: ['payroll', 'vat'],
    contacts: [{ name: 'Yiota Demetriou', email: 'y.demetriou@larnacalogistics.com.cy', role: 'HR & Payroll Lead' }] },
  { id: 'c6', legalName: 'Paphos Renewables Ltd', regId: 'HE 402176', jurisdiction: 'Cyprus', status: 'inactive',
    serviceLines: ['accounting'],
    contacts: [{ name: 'Marios Stavrou', email: 'm.stavrou@paphosrenewables.com', role: 'Managing Director' }] },
];

// ── Engagement-type templates shipped in V1 (F8) ──────────────────────────
const TEMPLATES = [
  { id: 't-vat', name: 'VAT Quarterly', serviceLine: 'vat',
    items: [
      { label: 'VAT sales ledger for the quarter', type: 'file', required: true },
      { label: 'VAT purchases ledger for the quarter', type: 'file', required: true },
      { label: 'Total output VAT (EUR)', type: 'currency', required: true },
      { label: 'Total input VAT (EUR)', type: 'currency', required: true },
      { label: 'Any intra-EU acquisitions this quarter?', type: 'boolean', required: true },
      { label: 'List of credit notes issued', type: 'table', required: false },
    ] },
  { id: 't-cit', name: 'CIT Annual', serviceLine: 'cit',
    items: [
      { label: 'Audited financial statements', type: 'file', required: true },
      { label: 'Trial balance (final)', type: 'file', required: true },
      { label: 'Accounting framework applied', type: 'multichoice', required: true },
      { label: 'Total dividends declared (EUR)', type: 'currency', required: true },
      { label: 'Financial year-end date', type: 'date', required: true },
      { label: 'Notes on any change in accounting policy', type: 'freetext', required: false },
    ] },
  { id: 't-payroll', name: 'Payroll Onboarding', serviceLine: 'payroll',
    items: [
      { label: 'Employee master data', type: 'file', required: true },
      { label: 'Number of employees at onboarding', type: 'number', required: true },
      { label: 'Standard monthly pay date', type: 'date', required: true },
      { label: 'Pay frequency', type: 'multichoice', required: true },
      { label: 'Schedule of recurring allowances', type: 'table', required: false },
    ] },
  { id: 't-tplf', name: 'TP Local File', serviceLine: 'tp',
    items: [
      { label: 'Group transfer pricing policy', type: 'file', required: true },
      { label: 'Functional analysis worksheets', type: 'file', required: true },
      { label: 'List of intra-group transactions (FY)', type: 'table', required: true },
      { label: 'Segmented P&L by entity', type: 'file', required: true },
      { label: 'Royalty rate applied (%)', type: 'number', required: true },
    ] },
  { id: 't-audit', name: 'Statutory Audit PBC', serviceLine: 'audit',
    items: [
      { label: 'Trial balance FY (final)', type: 'file', required: true },
      { label: 'Signed management accounts', type: 'file', required: true },
      { label: 'Fixed asset register', type: 'file', required: true },
      { label: 'Aged debtor analysis at year-end', type: 'file', required: true },
      { label: 'Closing cash balance (EUR)', type: 'currency', required: true },
      { label: 'Any related-party transactions post year-end?', type: 'boolean', required: true },
    ] },
];

// Multi-choice option sets keyed by label fragment
const CHOICE_SETS = {
  'Accounting framework applied': ['IFRS', 'IFRS for SMEs', 'Cyprus GAAP'],
  'Pay frequency': ['Monthly', 'Bi-weekly', 'Weekly'],
};

// ── Engagements — client × service-line × period (F7) ─────────────────────
const ENGAGEMENTS = [
  { id: 'e1', name: 'Statutory Audit PBC — FY2025', clientId: 'c1', client: 'Aegean Holdings (Cyprus) Ltd', serviceLine: 'audit',   period: 'FY2025',  template: 'Statutory Audit PBC', status: 'active',  deadline: '2025-06-15', createdAt: '2025-04-15', lastActivity: '2 hours ago',  assigned: ['u3', 'u4'], contactEmails: ['e.markou@aegeanholdings.com.cy', 'a.christou@aegeanholdings.com.cy'] },
  { id: 'e2', name: 'CIT Annual — FY2024',          clientId: 'c2', client: 'Cyprus Maritime Group Ltd',   serviceLine: 'cit',     period: 'FY2024',  template: 'CIT Annual',          status: 'active',  deadline: '2025-05-31', createdAt: '2025-03-12', lastActivity: 'Yesterday',    assigned: ['u3'],       contactEmails: ['m.papadakis@cyprusmaritime.com', 'l.athanasiou@cyprusmaritime.com'] },
  { id: 'e3', name: 'TP Local File — FY2024',       clientId: 'c3', client: 'Limassol Properties Ltd',     serviceLine: 'tp',      period: 'FY2024',  template: 'TP Local File',       status: 'active',  deadline: '2025-06-30', createdAt: '2025-03-04', lastActivity: '4 days ago',   assigned: ['u6'],       contactEmails: ['c.iakovou@limassolproperties.com.cy'] },
  { id: 'e4', name: 'VAT Quarterly — Q1 2025',      clientId: 'c4', client: 'Nicosia Tech SA',            serviceLine: 'vat',     period: 'Q1 2025', template: 'VAT Quarterly',       status: 'active',  deadline: '2025-05-10', createdAt: '2025-04-22', lastActivity: '3 hours ago',  assigned: ['u4', 'u6'], contactEmails: ['p.loizou@nicosiatech.com'] },
  { id: 'e5', name: 'Payroll Onboarding — 2025',    clientId: 'c5', client: 'Larnaca Logistics Ltd',      serviceLine: 'payroll', period: '2025',    template: 'Payroll Onboarding',  status: 'on_hold', deadline: '2025-05-20', createdAt: '2025-02-10', lastActivity: '9 days ago',   assigned: ['u3'],       contactEmails: ['y.demetriou@larnacalogistics.com.cy'] },
  { id: 'e6', name: 'VAT Quarterly — Q4 2024',      clientId: 'c1', client: 'Aegean Holdings (Cyprus) Ltd', serviceLine: 'vat',   period: 'Q4 2024', template: 'VAT Quarterly',       status: 'completed', deadline: '2025-01-31', createdAt: '2025-01-05', lastActivity: '3 months ago', assigned: ['u3', 'u4'], contactEmails: ['e.markou@aegeanholdings.com.cy'] },
];

// ── Request items (F9) — structured, 8 item types, per-item lifecycle ─────
// status: pending → submitted → accepted | change_requested → (resubmit) → submitted
const mc = (label) => CHOICE_SETS[label] || [];
const REQUEST_ITEMS = [
  // ── e1 Aegean Holdings · Statutory Audit PBC ──
  { id: 'i-e1-01', engagementId: 'e1', order: 1, label: 'Trial balance FY2024 (final)', type: 'file', required: true, deadline: '2025-05-10', status: 'accepted',
    value: { files: ['FY2024_TrialBalance.xlsx'] },
    versions: [{ v: 1, at: '2025-04-18', by: 'Elena Markou', value: { files: ['FY2024_TrialBalance.xlsx'] }, note: '' }],
    comments: [], description: 'The final, locked trial balance for the financial year under audit.' },
  { id: 'i-e1-02', engagementId: 'e1', order: 2, label: 'Signed FY2024 management accounts', type: 'file', required: true, deadline: '2025-05-12', status: 'submitted',
    value: { files: ['MgmtAccounts_FY2024_signed.pdf'] },
    versions: [{ v: 1, at: '2025-05-14', by: 'Elena Markou', value: { files: ['MgmtAccounts_FY2024_signed.pdf'] }, note: 'Signature page on p.12.' }],
    comments: [{ author: 'Elena Markou', role: 'client', at: '2025-05-14', text: 'Signed copy attached, let me know if the signature page is sufficient.' }],
    description: 'Management accounts with the signature page included.' },
  { id: 'i-e1-03', engagementId: 'e1', order: 3, label: 'Fixed asset register with depreciation', type: 'file', required: true, deadline: '2025-05-12', status: 'change_requested',
    value: { files: ['FAR_2024_draft.xlsx'] }, changeReason: 'Register is missing the additions made in Q4. Please include the full-year movement schedule.',
    versions: [{ v: 1, at: '2025-05-08', by: 'Andreas Christou', value: { files: ['FAR_2024_draft.xlsx'] }, note: '' }],
    comments: [{ author: 'Stelios Hadjikyriakou', role: 'staff', at: '2025-05-09', text: 'Thanks — could you add the Q4 additions and re-upload?' }],
    description: 'Full fixed-asset register including additions, disposals and depreciation.' },
  { id: 'i-e1-04', engagementId: 'e1', order: 4, label: 'Aged debtor analysis at 31 Dec 2024', type: 'file', required: true, deadline: '2025-05-12', status: 'accepted',
    value: { files: ['AgedDebtors_31Dec2024.xlsx'] },
    versions: [{ v: 1, at: '2025-05-02', by: 'Elena Markou', value: { files: ['AgedDebtors_31Dec2024.xlsx'] }, note: '' }],
    comments: [], description: 'Aged receivables at the balance-sheet date.' },
  { id: 'i-e1-05', engagementId: 'e1', order: 5, label: 'Closing cash & bank balance (EUR)', type: 'currency', required: true, deadline: '2025-05-12', status: 'accepted',
    value: { amount: 4286400, currency: 'EUR' },
    versions: [{ v: 1, at: '2025-05-03', by: 'Andreas Christou', value: { amount: 4286400, currency: 'EUR' }, note: '' }],
    comments: [], description: 'Total of all operating and deposit accounts at year-end.' },
  { id: 'i-e1-06', engagementId: 'e1', order: 6, label: 'Any related-party transactions post year-end?', type: 'boolean', required: true, deadline: '2025-05-20', status: 'pending',
    value: null, versions: [], comments: [], description: 'Confirm whether any new related-party transactions occurred after the year-end date.' },
  { id: 'i-e1-07', engagementId: 'e1', order: 7, label: 'List of intercompany loan balances', type: 'table', required: true, deadline: '2025-05-20', status: 'accepted',
    columns: ['Counterparty', 'Type', 'Balance (EUR)'],
    value: { rows: [['Aegean Trading Ltd', 'Loan receivable', '1,200,000'], ['Aegean Shipping SA', 'Loan payable', '850,000'], ['Aegean IP Ltd', 'Loan receivable', '430,000']] },
    versions: [{ v: 1, at: '2025-05-05', by: 'Andreas Christou', value: { rows: 3 }, note: '' }],
    comments: [], description: 'One row per intercompany loan with the current balance.' },
  { id: 'i-e1-08', engagementId: 'e1', order: 8, label: 'Group organisation chart (current)', type: 'file', required: false, deadline: '2025-05-20', status: 'accepted',
    value: { files: ['OrgChart_2025.pdf'] },
    versions: [{ v: 1, at: '2025-04-18', by: 'Elena Markou', value: { files: ['OrgChart_2025.pdf'] }, note: '' }],
    comments: [], description: 'Up-to-date group structure chart.' },
  { id: 'i-e1-09', engagementId: 'e1', order: 9, label: 'Number of employees at year-end', type: 'number', required: true, deadline: '2025-05-20', status: 'submitted',
    value: { number: 148 },
    versions: [{ v: 1, at: '2025-05-15', by: 'Elena Markou', value: { number: 148 }, note: '' }],
    comments: [], description: 'Headcount on payroll at the balance-sheet date.' },
  { id: 'i-e1-10', engagementId: 'e1', order: 10, label: 'Board minutes approving 2024 dividend', type: 'file', required: true, deadline: '2025-05-25', status: 'pending',
    value: null, versions: [], comments: [], description: 'Minutes of the meeting approving the dividend distribution.' },

  // ── e2 Cyprus Maritime · CIT Annual ──
  { id: 'i-e2-01', engagementId: 'e2', order: 1, label: 'Audited financial statements FY2024', type: 'file', required: true, deadline: '2025-04-30', status: 'accepted',
    value: { files: ['AuditedFS_2024.pdf'] }, versions: [{ v: 1, at: '2025-03-12', by: 'Markos Papadakis', value: { files: ['AuditedFS_2024.pdf'] }, note: '' }], comments: [], description: 'Signed audited financial statements.' },
  { id: 'i-e2-02', engagementId: 'e2', order: 2, label: 'Trial balance FY2024 (final)', type: 'file', required: true, deadline: '2025-04-30', status: 'accepted',
    value: { files: ['TB_FY2024_CM.xlsx'] }, versions: [{ v: 1, at: '2025-03-18', by: 'Lefki Athanasiou', value: { files: ['TB_FY2024_CM.xlsx'] }, note: '' }], comments: [], description: '' },
  { id: 'i-e2-03', engagementId: 'e2', order: 3, label: 'Accounting framework applied', type: 'multichoice', required: true, deadline: '2025-04-30', status: 'accepted',
    options: mc('Accounting framework applied'), value: { choice: 'IFRS' }, versions: [{ v: 1, at: '2025-03-18', by: 'Lefki Athanasiou', value: { choice: 'IFRS' }, note: '' }], comments: [], description: '' },
  { id: 'i-e2-04', engagementId: 'e2', order: 4, label: 'Total dividends declared (EUR)', type: 'currency', required: true, deadline: '2025-05-05', status: 'accepted',
    value: { amount: 2500000, currency: 'EUR' }, versions: [{ v: 1, at: '2025-04-02', by: 'Markos Papadakis', value: { amount: 2500000, currency: 'EUR' }, note: '' }], comments: [], description: '' },
  { id: 'i-e2-05', engagementId: 'e2', order: 5, label: 'Financial year-end date', type: 'date', required: true, deadline: '2025-05-05', status: 'accepted',
    value: { date: '2024-12-31' }, versions: [{ v: 1, at: '2025-04-02', by: 'Markos Papadakis', value: { date: '2024-12-31' }, note: '' }], comments: [], description: '' },
  { id: 'i-e2-06', engagementId: 'e2', order: 6, label: 'Tonnage tax election confirmation letter', type: 'file', required: true, deadline: '2025-05-10', status: 'accepted',
    value: { files: ['TonnageTaxElection.pdf'] }, versions: [{ v: 1, at: '2025-04-08', by: 'Lefki Athanasiou', value: { files: ['TonnageTaxElection.pdf'] }, note: '' }], comments: [], description: '' },
  { id: 'i-e2-07', engagementId: 'e2', order: 7, label: 'Withholding tax certificates (foreign interest)', type: 'file', required: true, deadline: '2025-05-15', status: 'submitted',
    value: { files: ['WHT_DE_2024.pdf', 'WHT_NL_2024.pdf'] }, versions: [{ v: 1, at: '2025-05-15', by: 'Markos Papadakis', value: { files: ['WHT_DE_2024.pdf', 'WHT_NL_2024.pdf'] }, note: 'Two of three received; German bank certificate to follow.' }], comments: [{ author: 'Markos Papadakis', role: 'client', at: '2025-05-15', text: 'Awaiting the third certificate from the German bank.' }], description: '' },
  { id: 'i-e2-08', engagementId: 'e2', order: 8, label: 'Notes on any change in accounting policy', type: 'freetext', required: false, deadline: '2025-05-15', status: 'pending',
    value: null, versions: [], comments: [], description: 'Describe any accounting-policy changes versus the prior year.' },

  // ── e3 Limassol Properties · TP Local File ──
  { id: 'i-e3-01', engagementId: 'e3', order: 1, label: 'Group transfer pricing policy', type: 'file', required: true, deadline: '2025-04-15', status: 'accepted',
    value: { files: ['TP_Policy_v3.2.pdf'] }, versions: [{ v: 1, at: '2025-03-04', by: 'Christina Iakovou', value: { files: ['TP_Policy_v3.2.pdf'] }, note: '' }], comments: [], description: '' },
  { id: 'i-e3-02', engagementId: 'e3', order: 2, label: 'Functional analysis worksheets (all entities)', type: 'file', required: true, deadline: '2025-04-15', status: 'accepted',
    value: { files: ['FA_Entity1.xlsx', 'FA_Entity2.xlsx', 'FA_Entity3.xlsx', 'FA_Entity4.xlsx'] }, versions: [{ v: 1, at: '2025-03-18', by: 'Christina Iakovou', value: { files: ['FA_Entity1.xlsx', '+3'] }, note: '' }], comments: [], description: '' },
  { id: 'i-e3-03', engagementId: 'e3', order: 3, label: 'List of intra-group transactions FY2024', type: 'table', required: true, deadline: '2025-05-01', status: 'change_requested',
    columns: ['Counterparty', 'Transaction type', 'Amount (EUR)'], changeReason: 'Please split the management-fee line by quarter and add the IT recharge line that appears in the policy.',
    value: { rows: [['Lux Holdco', 'Management fee', '1,800,000'], ['Cyprus OpCo', 'Royalty', '950,000']] },
    versions: [{ v: 1, at: '2025-04-20', by: 'Christina Iakovou', value: { rows: 2 }, note: '' }],
    comments: [{ author: 'Sofia Petrou', role: 'staff', at: '2025-04-22', text: 'The matrix is missing the IT shared-services recharge — can you add it?' }], description: 'One row per related-party transaction in the year.' },
  { id: 'i-e3-04', engagementId: 'e3', order: 4, label: 'Segmented P&L by entity (FY2024)', type: 'file', required: true, deadline: '2025-05-10', status: 'submitted',
    value: { files: ['SegmentedPL_FY2024.xlsx'] }, versions: [{ v: 1, at: '2025-05-12', by: 'Christina Iakovou', value: { files: ['SegmentedPL_FY2024.xlsx'] }, note: '' }], comments: [], description: '' },
  { id: 'i-e3-05', engagementId: 'e3', order: 5, label: 'Royalty rate applied (%)', type: 'number', required: true, deadline: '2025-05-10', status: 'accepted',
    value: { number: 5 }, versions: [{ v: 1, at: '2025-03-25', by: 'Christina Iakovou', value: { number: 5 }, note: '' }], comments: [], description: 'The arm’s-length royalty rate charged on brand & know-how.' },
  { id: 'i-e3-06', engagementId: 'e3', order: 6, label: 'Benchmarking study supporting the 5% royalty', type: 'file', required: true, deadline: '2025-05-20', status: 'pending',
    value: null, versions: [], comments: [], description: '' },
  { id: 'i-e3-07', engagementId: 'e3', order: 7, label: 'Country-by-country reporting filing (CY)', type: 'file', required: true, deadline: '2025-05-20', status: 'pending',
    value: null, versions: [], comments: [], description: '' },
  { id: 'i-e3-08', engagementId: 'e3', order: 8, label: 'Loan agreements (parent ↔ subsidiaries)', type: 'file', required: true, deadline: '2025-05-25', status: 'accepted',
    value: { files: ['IC_Loans_2024.pdf'] }, versions: [{ v: 1, at: '2025-04-02', by: 'Christina Iakovou', value: { files: ['IC_Loans_2024.pdf'] }, note: '' }], comments: [], description: '' },
  { id: 'i-e3-09', engagementId: 'e3', order: 9, label: 'Master file FY2024 (group level)', type: 'file', required: true, deadline: '2025-06-01', status: 'pending',
    value: null, versions: [], comments: [], description: '' },
  { id: 'i-e3-10', engagementId: 'e3', order: 10, label: 'Local file FY2024 (Cyprus entity)', type: 'file', required: true, deadline: '2025-06-01', status: 'pending',
    value: null, versions: [], comments: [], description: '' },
  { id: 'i-e3-11', engagementId: 'e3', order: 11, label: 'Updated cost-allocation key (IT shared services)', type: 'file', required: false, deadline: '2025-06-05', status: 'pending',
    value: null, versions: [], comments: [], description: '' },
  { id: 'i-e3-12', engagementId: 'e3', order: 12, label: 'Group ownership chart with percentages', type: 'file', required: true, deadline: '2025-05-01', status: 'accepted',
    value: { files: ['OwnershipChart.pdf'] }, versions: [{ v: 1, at: '2025-03-04', by: 'Christina Iakovou', value: { files: ['OwnershipChart.pdf'] }, note: '' }], comments: [], description: '' },

  // ── e4 Nicosia Tech · VAT Quarterly ──
  { id: 'i-e4-01', engagementId: 'e4', order: 1, label: 'VAT sales ledger — Q1 2025', type: 'file', required: true, deadline: '2025-05-05', status: 'accepted',
    value: { files: ['VAT_Sales_Q1_2025.xlsx'] }, versions: [{ v: 1, at: '2025-04-25', by: 'Petros Loizou', value: { files: ['VAT_Sales_Q1_2025.xlsx'] }, note: '' }], comments: [], description: '' },
  { id: 'i-e4-02', engagementId: 'e4', order: 2, label: 'VAT purchases ledger — Q1 2025', type: 'file', required: true, deadline: '2025-05-05', status: 'submitted',
    value: { files: ['VAT_Purchases_Q1_2025.xlsx'] }, versions: [{ v: 1, at: '2025-05-06', by: 'Petros Loizou', value: { files: ['VAT_Purchases_Q1_2025.xlsx'] }, note: '' }], comments: [], description: '' },
  { id: 'i-e4-03', engagementId: 'e4', order: 3, label: 'Total output VAT (EUR)', type: 'currency', required: true, deadline: '2025-05-08', status: 'submitted',
    value: { amount: 184250, currency: 'EUR' }, versions: [{ v: 1, at: '2025-05-06', by: 'Petros Loizou', value: { amount: 184250, currency: 'EUR' }, note: '' }], comments: [], description: '' },
  { id: 'i-e4-04', engagementId: 'e4', order: 4, label: 'Total input VAT (EUR)', type: 'currency', required: true, deadline: '2025-05-08', status: 'submitted',
    value: { amount: 142800, currency: 'EUR' }, versions: [{ v: 1, at: '2025-05-06', by: 'Petros Loizou', value: { amount: 142800, currency: 'EUR' }, note: '' }], comments: [], description: '' },
  { id: 'i-e4-05', engagementId: 'e4', order: 5, label: 'Any intra-EU acquisitions this quarter?', type: 'boolean', required: true, deadline: '2025-05-08', status: 'accepted',
    value: { bool: true }, versions: [{ v: 1, at: '2025-04-25', by: 'Petros Loizou', value: { bool: true }, note: '' }], comments: [], description: '' },
  { id: 'i-e4-06', engagementId: 'e4', order: 6, label: 'List of credit notes issued in Q1', type: 'table', required: false, deadline: '2025-05-08', status: 'pending',
    columns: ['Credit note no.', 'Customer', 'Amount (EUR)'], value: null, versions: [], comments: [], description: '' },
  { id: 'i-e4-07', engagementId: 'e4', order: 7, label: 'VIES return reconciliation', type: 'file', required: true, deadline: '2025-05-09', status: 'change_requested',
    value: { files: ['VIES_Q1.xlsx'] }, changeReason: 'The totals on this reconciliation don’t tie to the output-VAT figure submitted. Please reconcile and re-upload.',
    versions: [{ v: 1, at: '2025-05-07', by: 'Petros Loizou', value: { files: ['VIES_Q1.xlsx'] }, note: '' }], comments: [], description: '' },

  // ── e5 Larnaca Logistics · Payroll Onboarding (on hold) ──
  { id: 'i-e5-01', engagementId: 'e5', order: 1, label: 'Employee master data', type: 'file', required: true, deadline: '2025-05-12', status: 'submitted',
    value: { files: ['EmployeeMaster.xlsx'] }, versions: [{ v: 1, at: '2025-03-04', by: 'Yiota Demetriou', value: { files: ['EmployeeMaster.xlsx'] }, note: '' }], comments: [], description: '' },
  { id: 'i-e5-02', engagementId: 'e5', order: 2, label: 'Number of employees at onboarding', type: 'number', required: true, deadline: '2025-05-12', status: 'accepted',
    value: { number: 64 }, versions: [{ v: 1, at: '2025-03-04', by: 'Yiota Demetriou', value: { number: 64 }, note: '' }], comments: [], description: '' },
  { id: 'i-e5-03', engagementId: 'e5', order: 3, label: 'Standard monthly pay date', type: 'date', required: true, deadline: '2025-05-12', status: 'accepted',
    value: { date: '2025-01-28' }, versions: [{ v: 1, at: '2025-03-04', by: 'Yiota Demetriou', value: { date: '2025-01-28' }, note: '' }], comments: [], description: 'The recurring date each month on which staff are paid.' },
  { id: 'i-e5-04', engagementId: 'e5', order: 4, label: 'Pay frequency', type: 'multichoice', required: true, deadline: '2025-05-12', status: 'accepted',
    options: mc('Pay frequency'), value: { choice: 'Monthly' }, versions: [{ v: 1, at: '2025-03-04', by: 'Yiota Demetriou', value: { choice: 'Monthly' }, note: '' }], comments: [], description: '' },
  { id: 'i-e5-05', engagementId: 'e5', order: 5, label: 'Schedule of recurring allowances', type: 'table', required: false, deadline: '2025-05-15', status: 'pending',
    columns: ['Allowance', 'Frequency', 'Amount (EUR)'], value: null, versions: [], comments: [], description: '' },
  { id: 'i-e5-06', engagementId: 'e5', order: 6, label: 'Signed payroll services authorisation', type: 'file', required: true, deadline: '2025-05-20', status: 'pending',
    value: null, versions: [], comments: [], description: '' },

  // ── e6 Aegean Holdings · VAT Quarterly Q4 2024 (completed — portal history) ──
  { id: 'i-e6-01', engagementId: 'e6', order: 1, label: 'VAT sales ledger — Q4 2024', type: 'file', required: true, deadline: '2025-01-25', status: 'accepted',
    value: { files: ['VAT_Sales_Q4_2024.xlsx'] }, versions: [{ v: 1, at: '2025-01-20', by: 'Elena Markou', value: { files: ['VAT_Sales_Q4_2024.xlsx'] }, note: '' }], comments: [], description: '' },
  { id: 'i-e6-02', engagementId: 'e6', order: 2, label: 'VAT purchases ledger — Q4 2024', type: 'file', required: true, deadline: '2025-01-25', status: 'accepted',
    value: { files: ['VAT_Purchases_Q4_2024.xlsx'] }, versions: [{ v: 1, at: '2025-01-20', by: 'Elena Markou', value: { files: ['VAT_Purchases_Q4_2024.xlsx'] }, note: '' }], comments: [], description: '' },
  { id: 'i-e6-03', engagementId: 'e6', order: 3, label: 'Total output VAT (EUR)', type: 'currency', required: true, deadline: '2025-01-28', status: 'accepted',
    value: { amount: 312540, currency: 'EUR' }, versions: [{ v: 1, at: '2025-01-21', by: 'Elena Markou', value: { amount: 312540, currency: 'EUR' }, note: '' }], comments: [], description: '' },
  { id: 'i-e6-04', engagementId: 'e6', order: 4, label: 'Any intra-EU acquisitions this quarter?', type: 'boolean', required: true, deadline: '2025-01-28', status: 'accepted',
    value: { bool: false }, versions: [{ v: 1, at: '2025-01-21', by: 'Elena Markou', value: { bool: false }, note: '' }], comments: [], description: '' },
];

// ── Studies (TP) — lifecycle Draft → Running → Review → Complete → Archived
const STUDIES = [
  { id: 's1', name: 'Distribution Benchmark FY2024',     engagement: 'Aegean Holdings',     clientId: 'c1', candidates: 187, reviewed: 187, status: 'complete', createdBy: 'u3' },
  { id: 's2', name: 'IP Licensing Comps Q3 2025',         engagement: 'Maritime Group',      clientId: 'c2', candidates: 142, reviewed: 92,  status: 'review',   createdBy: 'u5' },
  { id: 's3', name: 'Real Estate Services Comps',         engagement: 'Limassol Properties', clientId: 'c3', candidates: 234, reviewed: 0,   status: 'running',  createdBy: 'u6' },
  { id: 's4', name: 'Software Services Benchmark FY2025', engagement: 'Nicosia Tech',        clientId: 'c4', candidates: 96,  reviewed: 0,   status: 'draft',    createdBy: 'u5' },
];

// ── Activity feed (reframed to portal / submission model) ─────────────────
const ACTIVITY = [
  { id:  1, type: 'item_submitted',  desc: 'Client submitted “Signed FY2024 management accounts”', engId: 'e1', studyId: null, when: '18 minutes ago' },
  { id:  2, type: 'change_requested',desc: 'Change requested on “Intra-group transactions”',       engId: 'e3', studyId: null, when: '42 minutes ago' },
  { id:  3, type: 'item_submitted',  desc: '3 VAT items submitted for review',                     engId: 'e4', studyId: null, when: '1 hour ago' },
  { id:  4, type: 'study_completed', desc: 'Study marked complete — 187 candidates reviewed',      engId: null, studyId: 's1', when: '2 hours ago' },
  { id:  5, type: 'item_accepted',   desc: 'Accepted “Closing cash & bank balance”',               engId: 'e1', studyId: null, when: '3 hours ago' },
  { id:  6, type: 'reminder_sent',   desc: 'Deadline reminder sent to client contact',             engId: 'e5', studyId: null, when: '5 hours ago' },
  { id:  7, type: 'verdict_set',     desc: 'Analyst recorded 12 Accept / Reject verdicts',         engId: null, studyId: 's2', when: '6 hours ago' },
  { id:  8, type: 'item_accepted',   desc: 'Accepted “Audited financial statements FY2024”',       engId: 'e2', studyId: null, when: 'Yesterday' },
  { id:  9, type: 'engagement_created', desc: 'Engagement created from “VAT Quarterly” template',  engId: 'e4', studyId: null, when: '2 days ago' },
  { id: 10, type: 'item_submitted',  desc: 'Client submitted “Withholding tax certificates”',      engId: 'e2', studyId: null, when: '2 days ago' },
  { id: 11, type: 'reminder_sent',   desc: 'Reminder cadence advanced for 4 overdue items',        engId: 'e3', studyId: null, when: '3 days ago' },
  { id: 12, type: 'verdict_set',     desc: 'Analyst recorded 1 Reject verdict',                    engId: null, studyId: 's2', when: '4 days ago' },
  { id: 13, type: 'engagement_created', desc: 'Engagement created from “TP Local File” template',  engId: 'e3', studyId: null, when: '6 days ago' },
];

const WEEKLY_DATA = [
  { day: 'Fri', v: 3 }, { day: 'Sat', v: 1 }, { day: 'Sun', v: 0 },
  { day: 'Mon', v: 6 }, { day: 'Tue', v: 9 }, { day: 'Wed', v: 4 }, { day: 'Thu', v: 7 },
];

// ── Helpers ───────────────────────────────────────────────────────────────
const getItemsForEngagement = (eid) => REQUEST_ITEMS.filter(i => i.engagementId === eid).sort((a, b) => a.order - b.order);
const getEngagementById      = (id) => ENGAGEMENTS.find(e => e.id === id);
const getClientById          = (id) => CLIENTS.find(c => c.id === id);
const getUserById            = (id) => USERS.find(u => u.id === id);
const getTemplate            = (name) => TEMPLATES.find(t => t.name === name);
const serviceLineLabel       = (key) => (SERVICE_LINES[key] || { label: key }).label;

// Engagement progress derived from items (required-only drives completion)
const engagementStats = (eid) => {
  const items = getItemsForEngagement(eid);
  const required = items.filter(i => i.required);
  const accepted = items.filter(i => i.status === 'accepted').length;
  const acceptedRequired = required.filter(i => i.status === 'accepted').length;
  const submitted = items.filter(i => i.status === 'submitted').length;
  const changeReq = items.filter(i => i.status === 'change_requested').length;
  const outstanding = items.filter(i => i.status === 'pending' || i.status === 'change_requested').length;
  return { total: items.length, requiredTotal: required.length, accepted, acceptedRequired, submitted, changeReq, outstanding };
};

// Cross-engagement inbox: every item awaiting staff review
const getSubmittedItems = (engagements) => {
  const ids = new Set(engagements.map(e => e.id));
  return REQUEST_ITEMS.filter(i => i.status === 'submitted' && ids.has(i.engagementId));
};

const isOverdue = (deadline) => {
  if (!deadline) return false;
  return new Date(deadline) < new Date('2025-05-16T00:00:00Z');
};

const formatRelative = (iso) => {
  if (!iso) return '';
  const now = new Date('2025-05-16T12:00:00Z');
  const then = new Date(iso);
  const diff = Math.floor((now - then) / 1000);
  if (diff < 60) return 'just now';
  if (diff < 3600) return `${Math.floor(diff / 60)} min ago`;
  if (diff < 86400) return `${Math.floor(diff / 3600)} hours ago`;
  const days = Math.floor(diff / 86400);
  if (days === 1) return 'yesterday';
  if (days < 7) return `${days} days ago`;
  return then.toLocaleDateString('en-GB', { day: 'numeric', month: 'short' });
};

const formatDate = (iso, opts) => iso ? new Date(iso + (iso.length === 10 ? 'T00:00:00Z' : '')).toLocaleDateString('en-GB', opts || { day: 'numeric', month: 'short', year: 'numeric' }) : '—';

const ITEM_TYPE_META = {
  file:        { label: 'File',        icon: 'paperclip' },
  number:      { label: 'Number',      icon: 'hash' },
  currency:    { label: 'Currency',    icon: 'euro' },
  date:        { label: 'Date',        icon: 'calendar' },
  boolean:     { label: 'Yes / No',    icon: 'toggle-left' },
  multichoice: { label: 'Multi-choice',icon: 'list' },
  freetext:    { label: 'Free text',   icon: 'type' },
  table:       { label: 'Table',       icon: 'table' },
};

// Render a request-item's submitted value as a short string (for staff list / inbox)
const itemValueSummary = (item) => {
  const v = item.value;
  if (!v) return null;
  switch (item.type) {
    case 'file':        return (v.files || []).join(', ');
    case 'number':      return String(v.number);
    case 'currency':    return `${v.currency || 'EUR'} ${Number(v.amount).toLocaleString('en-GB')}`;
    case 'date':        return formatDate(v.date);
    case 'boolean':     return v.bool ? 'Yes' : 'No';
    case 'multichoice': return v.choice;
    case 'freetext':    return v.text;
    case 'table':       return `${Array.isArray(v.rows) ? v.rows.length : v.rows} rows`;
    default:            return null;
  }
};

Object.assign(window, {
  USERS, SERVICE_LINES, CLIENTS, TEMPLATES, CHOICE_SETS,
  ENGAGEMENTS, REQUEST_ITEMS, STUDIES, ACTIVITY, WEEKLY_DATA,
  ITEM_TYPE_META,
  getItemsForEngagement, getEngagementById, getClientById, getUserById, getTemplate,
  serviceLineLabel, engagementStats, getSubmittedItems, isOverdue,
  formatRelative, formatDate, itemValueSummary,
});
