export const WORKSPACE_ROLES = {
  superAdmin: 'Super Administrator',
  administrator: 'Administrator',
  directorGeneral: 'Director General',
  financeDirector: 'Finance Director',
  procurementLead: 'Procurement Lead',
  complianceAuditLead: 'Compliance and Audit Lead',
  projectDeliveryLead: 'Project Delivery Lead',
  public: 'Public',
} as const;

export const WORKSPACE_ROUTES = {
  [WORKSPACE_ROLES.superAdmin]: '/platform-command',
  [WORKSPACE_ROLES.administrator]: '/operations-command',
  [WORKSPACE_ROLES.directorGeneral]: '/executive-command',
  [WORKSPACE_ROLES.financeDirector]: '/financial-control',
  [WORKSPACE_ROLES.procurementLead]: '/procurement-desk',
  [WORKSPACE_ROLES.complianceAuditLead]: '/compliance-desk',
  [WORKSPACE_ROLES.projectDeliveryLead]: '/delivery-command',
} as const;

const ADMIN_DASHBOARD_ROLES = [WORKSPACE_ROLES.superAdmin, WORKSPACE_ROLES.administrator] as const;

export type WorkspaceMetricKey =
  | 'approvedBudget'
  | 'committedBudget'
  | 'disbursedBudget'
  | 'pendingApprovals'
  | 'contractsNearingExpiry'
  | 'vendorComplianceAlerts'
  | 'procurementPipeline'
  | 'openRiskAlerts'
  | 'averageProjectProgress'
  | 'highRiskProjects'
  | 'overduePayments'
  | 'activeProjects'
  | 'unreadNotifications'
  | 'organizationCount'
  | 'platformUserCount'
  | 'roleCount'
  | 'permissionCount'
  | 'auditEventCount';

export type WorkspaceDetailBlockKey =
  | 'focus'
  | 'summary'
  | 'watchlist'
  | 'approvalRisk'
  | 'operations'
  | 'delivery'
  | 'actions';

export type WorkspaceSectionKey =
  | 'approvalQueue'
  | 'riskPanel'
  | 'procurementQueue'
  | 'contractWatchlist'
  | 'recentNotifications'
  | 'provinceRollout'
  | 'topContracts'
  | 'quickActions';

export type WorkspaceQuickLinkIconKey =
  | 'organizations'
  | 'users'
  | 'approvals'
  | 'notifications'
  | 'projects'
  | 'contracts'
  | 'payments'
  | 'allocations'
  | 'requisitions'
  | 'tenders'
  | 'compliance'
  | 'audit'
  | 'milestones'
  | 'vendors';

export interface WorkspaceAction {
  href: string;
  label: string;
}

export interface WorkspaceQuickLink {
  href: string;
  label: string;
  description: string;
  icon: WorkspaceQuickLinkIconKey;
}

export interface WorkspaceSectionCopy {
  eyebrow: string;
  title: string;
  actionLabel?: string;
}

export interface WorkspaceBriefingCard {
  title: string;
  items: string[];
}

export interface WorkspaceConfig {
  sidebarLabel: string;
  pageTitle: string;
  eyebrow: string;
  heroTitle: string;
  heroDescription: string;
  primaryAction: WorkspaceAction;
  secondaryAction: WorkspaceAction;
  briefingCards: WorkspaceBriefingCard[];
  highlightedMetricKeys: WorkspaceMetricKey[];
  heroMetricKeys: WorkspaceMetricKey[];
  blockOrder: WorkspaceDetailBlockKey[];
  sectionCopy: Record<WorkspaceSectionKey, WorkspaceSectionCopy>;
  quickLinks: WorkspaceQuickLink[];
}

type WorkspaceConfigInput = Omit<WorkspaceConfig, 'sectionCopy' | 'heroMetricKeys' | 'blockOrder' | 'quickLinks' | 'briefingCards'> & {
  heroMetricKeys?: WorkspaceMetricKey[];
  blockOrder?: WorkspaceDetailBlockKey[];
  sectionCopy?: Partial<Record<WorkspaceSectionKey, WorkspaceSectionCopy>>;
  quickLinks?: WorkspaceQuickLink[];
  briefingCards?: WorkspaceBriefingCard[];
};

const defaultBlockOrder: WorkspaceDetailBlockKey[] = [
  'focus',
  'summary',
  'watchlist',
  'approvalRisk',
  'operations',
  'delivery',
  'actions',
];

const defaultSectionCopy: Record<WorkspaceSectionKey, WorkspaceSectionCopy> = {
  approvalQueue: {
    eyebrow: 'Approval inbox',
    title: 'Pending institutional decisions',
    actionLabel: 'Open approvals',
  },
  riskPanel: {
    eyebrow: 'Risk and red-flag panel',
    title: 'Compliance, audit, and payment exposure',
  },
  procurementQueue: {
    eyebrow: 'Procurement workflow',
    title: 'Live procurement pipeline',
    actionLabel: 'All requisitions',
  },
  contractWatchlist: {
    eyebrow: 'Contract watchlist',
    title: 'Expiring commitments',
    actionLabel: 'Contract register',
  },
  recentNotifications: {
    eyebrow: 'Notifications',
    title: 'Recent operational signals',
    actionLabel: 'Notification center',
  },
  provinceRollout: {
    eyebrow: 'Geographic rollout',
    title: 'Projects by province',
    actionLabel: 'Projects register',
  },
  topContracts: {
    eyebrow: 'Top-value contracts',
    title: 'Largest commitments currently tracked',
    actionLabel: 'Vendor master',
  },
  quickActions: {
    eyebrow: 'Action launcher',
    title: 'Move from oversight to execution',
  },
};

const defaultQuickLinks: WorkspaceQuickLink[] = [
  {
    href: '/requisitions/requisitions-new',
    label: 'Create requisition',
    description: 'Start the procurement workflow.',
    icon: 'requisitions',
  },
  {
    href: '/approvals/approvals-list',
    label: 'Approval inbox',
    description: 'Review pending decisions and escalations.',
    icon: 'approvals',
  },
  {
    href: '/contracts/contracts-list',
    label: 'Contract register',
    description: 'Inspect value, milestones, and expiry status.',
    icon: 'contracts',
  },
  {
    href: '/audit_logs/audit_logs-list',
    label: 'Audit center',
    description: 'Trace actions, timestamps, and record history.',
    icon: 'audit',
  },
];

const createWorkspaceConfig = ({
  heroMetricKeys,
  blockOrder,
  sectionCopy,
  quickLinks,
  briefingCards,
  ...config
}: WorkspaceConfigInput): WorkspaceConfig => ({
  ...config,
  heroMetricKeys: heroMetricKeys || config.highlightedMetricKeys.slice(0, 4),
  blockOrder: blockOrder || defaultBlockOrder,
  sectionCopy: {
    ...defaultSectionCopy,
    ...sectionCopy,
  },
  quickLinks: quickLinks || defaultQuickLinks,
  briefingCards: briefingCards || [],
});

const workspaceConfigs: Record<string, WorkspaceConfig> = {
  [WORKSPACE_ROLES.superAdmin]: createWorkspaceConfig({
    sidebarLabel: 'Platform Administration',
    pageTitle: 'Platform Administration',
    eyebrow: 'FDSU ERP · Platform Administration',
    heroTitle: 'Govern tenants, access structure, and audit visibility across the platform.',
    heroDescription:
      'This workspace is for the Super Admin only. It focuses on organizations, platform users, role design, permission governance, and audit visibility across tenants without turning the Super Admin into an organization-level ERP operator.',
    primaryAction: { href: '/organizations/organizations-list', label: 'Review organizations' },
    secondaryAction: { href: '/permissions/permissions-list', label: 'Review permissions' },
    briefingCards: [
      {
        title: 'Should see',
        items: ['Organizations using the platform', 'Platform users, roles, permissions, and access assignments', 'Audit activity and cross-tenant control exceptions'],
      },
      {
        title: 'Should do',
        items: ['Create and govern organizations', 'Maintain the platform access model and segregation of duties', 'Support administrators without owning daily ERP transactions'],
      },
      {
        title: 'Receives from',
        items: ['Tenant setup requests', 'Access-governance escalations', 'Audit findings and platform support issues'],
      },
      {
        title: 'Hands off to',
        items: ['Administrators for organization execution', 'Functional leads for business workflows', 'Director General or tenant owners when decisions become operational'],
      },
    ],
    highlightedMetricKeys: ['organizationCount', 'platformUserCount', 'roleCount', 'permissionCount', 'auditEventCount', 'unreadNotifications'],
    heroMetricKeys: ['organizationCount', 'platformUserCount', 'roleCount', 'auditEventCount'],
    blockOrder: ['summary', 'focus', 'actions'],
    sectionCopy: {
      quickActions: {
        eyebrow: 'Platform administration shortcuts',
        title: 'Go directly to organizations, access models, permissions, audit logs, and notices',
      },
    },
    quickLinks: [
      {
        href: '/organizations/organizations-list',
        label: 'Organizations',
        description: 'Review tenants, owners, and platform coverage.',
        icon: 'organizations',
      },
      {
        href: '/users/users-list',
        label: 'Platform users',
        description: 'Inspect who has access across the platform.',
        icon: 'users',
      },
      {
        href: '/roles/roles-list',
        label: 'Roles',
        description: 'Maintain responsibility boundaries and access structure.',
        icon: 'users',
      },
      {
        href: '/permissions/permissions-list',
        label: 'Permissions',
        description: 'Review the permission catalogue and control surface.',
        icon: 'audit',
      },
      {
        href: '/audit_logs/audit_logs-list',
        label: 'Audit logs',
        description: 'Trace platform activity and investigate access changes.',
        icon: 'audit',
      },
    ],
  }),
  [WORKSPACE_ROLES.administrator]: createWorkspaceConfig({
    sidebarLabel: 'Organization Administration',
    pageTitle: 'Organization Administration',
    eyebrow: 'FDSU ERP · Organization Administration',
    heroTitle: 'Keep the organization ready to operate: users, routing, notices, and master data.',
    heroDescription:
      'This workspace is for the Administrator. It owns user setup, departments, provinces, approval routing, notifications, and day-to-day system readiness. It should not read like a finance, procurement, or project command center.',
    primaryAction: { href: '/approval_workflows/approval_workflows-list', label: 'Review workflow setup' },
    secondaryAction: { href: '/notifications/notifications-list', label: 'Review notifications' },
    briefingCards: [
      {
        title: 'Should see',
        items: ['Workflow readiness and routing issues', 'Users, departments, provinces, and notices', 'Configuration gaps slowing daily operations'],
      },
      {
        title: 'Should do',
        items: ['Onboard and support users', 'Maintain approval steps, delegations, and notifications', 'Keep administrative records clean and usable'],
      },
      {
        title: 'Receives from',
        items: ['Super Admin policy and access structure', 'Support requests from staff', 'Broken-routing or setup escalations from functional leads'],
      },
      {
        title: 'Hands off to',
        items: ['Operational staff for daily execution', 'Functional leads for domain decisions', 'Director General when administrative blockages affect the institution'],
      },
    ],
    highlightedMetricKeys: ['pendingApprovals', 'unreadNotifications', 'openRiskAlerts', 'vendorComplianceAlerts'],
    heroMetricKeys: ['pendingApprovals', 'unreadNotifications', 'openRiskAlerts', 'vendorComplianceAlerts'],
    blockOrder: ['summary', 'focus', 'watchlist', 'approvalRisk', 'actions'],
    sectionCopy: {
      approvalQueue: {
        eyebrow: 'Workflow routing queue',
        title: 'Approvals waiting because routing, delegation, or setup needs attention',
        actionLabel: 'Open approval queue',
      },
      riskPanel: {
        eyebrow: 'Administrative control signals',
        title: 'Alerts and exceptions that often point to setup, delegation, or record issues',
      },
      recentNotifications: {
        eyebrow: 'Administrator notices',
        title: 'Support and system notices requiring administrator follow-through',
        actionLabel: 'Open notices',
      },
      quickActions: {
        eyebrow: 'Administration shortcuts',
        title: 'Go straight to users, workflow setup, notifications, and organization records',
      },
    },
    quickLinks: [
      {
        href: '/users/users-list',
        label: 'Users',
        description: 'Manage onboarding, account support, and assignments.',
        icon: 'users',
      },
      {
        href: '/approval_workflows/approval_workflows-list',
        label: 'Approval workflows',
        description: 'Maintain routes, steps, and approval readiness.',
        icon: 'approvals',
      },
      {
        href: '/notifications/notifications-list',
        label: 'Notifications',
        description: 'Review notices, workflow signals, and support follow-up.',
        icon: 'notifications',
      },
      {
        href: '/departments/departments-list',
        label: 'Departments',
        description: 'Keep organization structure and master data aligned.',
        icon: 'users',
      },
    ],
  }),
  [WORKSPACE_ROLES.directorGeneral]: createWorkspaceConfig({
    sidebarLabel: 'Executive Oversight',
    pageTitle: 'Executive Oversight',
    eyebrow: 'FDSU ERP · Executive Oversight',
    heroTitle: 'See the institution across finance, procurement, compliance, and delivery, then make executive decisions.',
    heroDescription:
      'This workspace is for the Director General. It brings together budget posture, delivery progress, risk concentration, and high-impact approvals so executive attention stays on direction, escalation, and accountability.',
    primaryAction: { href: '/approvals/approvals-list', label: 'Review escalations' },
    secondaryAction: { href: '/projects/projects-list', label: 'Review project portfolio' },
    briefingCards: [
      {
        title: 'Should see',
        items: ['Strategic budget posture', 'Delivery momentum and risk concentration', 'Major approvals and contracts needing executive direction'],
      },
      {
        title: 'Should do',
        items: ['Approve high-impact decisions', 'Set priorities across functions', 'Resolve escalations that cross departmental boundaries'],
      },
      {
        title: 'Receives from',
        items: ['Finance, procurement, compliance, and delivery leads', 'Administrator escalations with institution-wide impact'],
      },
      {
        title: 'Hands off to',
        items: ['Functional leads for execution', 'Administrator for coordination follow-through', 'Operational teams through approved decisions'],
      },
    ],
    highlightedMetricKeys: ['approvedBudget', 'committedBudget', 'disbursedBudget', 'pendingApprovals', 'highRiskProjects', 'contractsNearingExpiry'],
    heroMetricKeys: ['approvedBudget', 'disbursedBudget', 'pendingApprovals', 'highRiskProjects'],
    blockOrder: ['summary', 'focus', 'watchlist', 'delivery', 'approvalRisk', 'actions'],
    sectionCopy: {
      riskPanel: {
        eyebrow: 'Executive risk watch',
        title: 'Strategic risks, bottlenecks, and control exposure needing executive attention',
      },
      provinceRollout: {
        eyebrow: 'Delivery coverage',
        title: 'Project rollout and execution pace across provinces',
        actionLabel: 'Open projects',
      },
      topContracts: {
        eyebrow: 'Major commitments',
        title: 'Largest contracts shaping institutional exposure and delivery',
        actionLabel: 'Open contracts',
      },
      quickActions: {
        eyebrow: 'Executive shortcuts',
        title: 'Open the records most relevant to executive review and escalation',
      },
    },
    quickLinks: [
      {
        href: '/approvals/approvals-list',
        label: 'Escalations',
        description: 'Review approvals and issues that need executive decision.',
        icon: 'approvals',
      },
      {
        href: '/projects/projects-list',
        label: 'Projects',
        description: 'Review delivery status and accountability.',
        icon: 'projects',
      },
      {
        href: '/contracts/contracts-list',
        label: 'Contracts',
        description: 'Inspect major commitments and expiry exposure.',
        icon: 'contracts',
      },
      {
        href: '/notifications/notifications-list',
        label: 'Executive notices',
        description: 'See the latest escalations and control signals.',
        icon: 'notifications',
      },
    ],
  }),
  [WORKSPACE_ROLES.financeDirector]: createWorkspaceConfig({
    sidebarLabel: 'Financial Management',
    pageTitle: 'Financial Management',
    eyebrow: 'FDSU ERP · Financial Management',
    heroTitle: 'Control budget, commitments, disbursements, and payment pressure.',
    heroDescription:
      'This workspace is for the Finance Director. It focuses on allocations, commitments, disbursements, aging payment requests, and finance approvals while staying tied to the contracts and spending decisions that drive exposure.',
    primaryAction: { href: '/payment_requests/payment_requests-list', label: 'Review payment requests' },
    secondaryAction: { href: '/allocations/allocations-list', label: 'Review allocations' },
    briefingCards: [
      {
        title: 'Should see',
        items: ['Approved versus committed budget', 'Payment backlog and disbursement risk', 'Allocation pressure and finance approvals'],
      },
      {
        title: 'Should do',
        items: ['Validate funding coverage', 'Clear finance approvals and payment bottlenecks', 'Escalate shortfalls and fiscal-control issues'],
      },
      {
        title: 'Receives from',
        items: ['Operational finance staff', 'Procurement commitments and award decisions', 'Administrator-routed approvals'],
      },
      {
        title: 'Hands off to',
        items: ['Director General for major funding decisions', 'Payment and ledger staff for execution', 'Procurement and delivery leads on affordability constraints'],
      },
    ],
    highlightedMetricKeys: ['approvedBudget', 'committedBudget', 'disbursedBudget', 'overduePayments', 'pendingApprovals', 'unreadNotifications'],
    heroMetricKeys: ['approvedBudget', 'committedBudget', 'disbursedBudget', 'overduePayments'],
    blockOrder: ['summary', 'focus', 'watchlist', 'approvalRisk', 'actions'],
    sectionCopy: {
      approvalQueue: {
        eyebrow: 'Finance approval queue',
        title: 'Approvals affecting commitments, disbursements, and payment timing',
        actionLabel: 'Open finance approvals',
      },
      riskPanel: {
        eyebrow: 'Fiscal exposure',
        title: 'Budget pressure, aging payments, and control exceptions affecting finance',
      },
      quickActions: {
        eyebrow: 'Finance shortcuts',
        title: 'Go directly to allocations, payment requests, commitments, and approvals',
      },
    },
    quickLinks: [
      {
        href: '/payment_requests/payment_requests-list',
        label: 'Payment requests',
        description: 'Review pending and aging disbursement requests.',
        icon: 'payments',
      },
      {
        href: '/allocations/allocations-list',
        label: 'Allocations',
        description: 'Check available headroom and funding coverage.',
        icon: 'allocations',
      },
      {
        href: '/contracts/contracts-list',
        label: 'Commitments',
        description: 'Inspect the contracts driving current spend exposure.',
        icon: 'contracts',
      },
      {
        href: '/approvals/approvals-list',
        label: 'Finance approvals',
        description: 'Track bottlenecks holding back finance action.',
        icon: 'approvals',
      },
    ],
  }),
  [WORKSPACE_ROLES.procurementLead]: createWorkspaceConfig({
    sidebarLabel: 'Procurement Management',
    pageTitle: 'Procurement Management',
    eyebrow: 'FDSU ERP · Procurement Management',
    heroTitle: 'Own the demand-to-award chain: requisitions, tenders, vendors, awards, and contract readiness.',
    heroDescription:
      'This workspace is for the Procurement Lead. It keeps sourcing leadership focused on requisition inflow, tender progression, vendor readiness, contract deadlines, and approvals that are slowing the procurement chain.',
    primaryAction: { href: '/requisitions/requisitions-list', label: 'Review requisitions' },
    secondaryAction: { href: '/tenders/tenders-list', label: 'Review tenders' },
    briefingCards: [
      {
        title: 'Should see',
        items: ['Requisition inflow and tender progress', 'Expiring contracts and supplier readiness', 'Approvals slowing sourcing and award decisions'],
      },
      {
        title: 'Should do',
        items: ['Move demand into sourcing', 'Review awards and vendor readiness', 'Escalate blockers in the procurement chain'],
      },
      {
        title: 'Receives from',
        items: ['Operational requesters and departments', 'Project teams needing sourcing support', 'Administrator workflow routing and setup support'],
      },
      {
        title: 'Hands off to',
        items: ['Finance on commitments and funding coverage', 'Compliance on control concerns', 'Director General on high-value or escalated decisions'],
      },
    ],
    highlightedMetricKeys: ['procurementPipeline', 'pendingApprovals', 'contractsNearingExpiry', 'vendorComplianceAlerts', 'openRiskAlerts', 'activeProjects'],
    heroMetricKeys: ['procurementPipeline', 'pendingApprovals', 'contractsNearingExpiry', 'vendorComplianceAlerts'],
    blockOrder: ['summary', 'focus', 'watchlist', 'approvalRisk', 'operations', 'actions'],
    sectionCopy: {
      approvalQueue: {
        eyebrow: 'Procurement approval queue',
        title: 'Decisions blocking sourcing, evaluation, award, or contract signature',
        actionLabel: 'Open approval backlog',
      },
      procurementQueue: {
        eyebrow: 'Sourcing pipeline',
        title: 'Requisitions and tenders currently needing procurement action',
        actionLabel: 'Open sourcing queue',
      },
      contractWatchlist: {
        eyebrow: 'Contract renewals',
        title: 'Supplier commitments nearing expiry or needing follow-through',
        actionLabel: 'Open contracts',
      },
      quickActions: {
        eyebrow: 'Procurement shortcuts',
        title: 'Go directly to requisitions, tenders, vendors, and contract follow-up',
      },
    },
    quickLinks: [
      {
        href: '/requisitions/requisitions-list',
        label: 'Requisitions',
        description: 'Review new demand and sourcing readiness.',
        icon: 'requisitions',
      },
      {
        href: '/tenders/tenders-list',
        label: 'Tenders',
        description: 'Follow active tenders and consultations.',
        icon: 'tenders',
      },
      {
        href: '/contracts/contracts-list',
        label: 'Contracts',
        description: 'Track expiring commitments and follow-up actions.',
        icon: 'contracts',
      },
      {
        href: '/vendors/vendors-list',
        label: 'Vendors',
        description: 'Inspect supplier readiness and history.',
        icon: 'vendors',
      },
    ],
  }),
  [WORKSPACE_ROLES.complianceAuditLead]: createWorkspaceConfig({
    sidebarLabel: 'Compliance & Audit',
    pageTitle: 'Compliance & Audit',
    eyebrow: 'FDSU ERP · Compliance & Audit',
    heroTitle: 'Watch control breaches, evidence gaps, expiring obligations, and approvals that need independent review.',
    heroDescription:
      'This workspace is for the Compliance and Audit Lead. It focuses on red flags, evidence quality, audit trails, expiring obligations, and approvals where controls must be checked before risk becomes failure.',
    primaryAction: { href: '/compliance_alerts/compliance_alerts-list', label: 'Review compliance alerts' },
    secondaryAction: { href: '/audit_logs/audit_logs-list', label: 'Review audit logs' },
    briefingCards: [
      {
        title: 'Should see',
        items: ['Compliance alerts and evidence gaps', 'Expiring obligations and aging items', 'Approvals requiring control review'],
      },
      {
        title: 'Should do',
        items: ['Investigate red flags', 'Trace actions in audit logs', 'Push corrective action and evidence follow-up'],
      },
      {
        title: 'Receives from',
        items: ['System alerts and audit trails', 'Functional leads reporting control exceptions', 'Administrator notices and escalations'],
      },
      {
        title: 'Hands off to',
        items: ['Director General on serious exposure', 'Process owners for remediation', 'Staff for evidence completion and follow-up'],
      },
    ],
    highlightedMetricKeys: ['openRiskAlerts', 'vendorComplianceAlerts', 'contractsNearingExpiry', 'pendingApprovals', 'overduePayments', 'unreadNotifications'],
    heroMetricKeys: ['openRiskAlerts', 'vendorComplianceAlerts', 'contractsNearingExpiry', 'pendingApprovals'],
    blockOrder: ['summary', 'focus', 'watchlist', 'approvalRisk', 'actions'],
    sectionCopy: {
      approvalQueue: {
        eyebrow: 'Control review queue',
        title: 'Approvals and cases requiring audit or compliance follow-through',
        actionLabel: 'Open control queue',
      },
      riskPanel: {
        eyebrow: 'Compliance watch',
        title: 'Exceptions, evidence gaps, overdue items, and red flags needing review',
      },
      recentNotifications: {
        eyebrow: 'Control notices',
        title: 'Recent signals that may indicate policy, evidence, or routing problems',
        actionLabel: 'Open notices',
      },
      quickActions: {
        eyebrow: 'Compliance shortcuts',
        title: 'Go directly to alerts, logs, approvals, and obligations needing review',
      },
    },
    quickLinks: [
      {
        href: '/compliance_alerts/compliance_alerts-list',
        label: 'Compliance alerts',
        description: 'Review open red flags and follow-up status.',
        icon: 'compliance',
      },
      {
        href: '/audit_logs/audit_logs-list',
        label: 'Audit logs',
        description: 'Trace evidence across users and records.',
        icon: 'audit',
      },
      {
        href: '/approvals/approvals-list',
        label: 'Control queue',
        description: 'Inspect approvals needing governance review.',
        icon: 'approvals',
      },
      {
        href: '/contracts/contracts-list',
        label: 'Obligations',
        description: 'Check commitments nearing expiry or breach.',
        icon: 'contracts',
      },
    ],
  }),
  [WORKSPACE_ROLES.projectDeliveryLead]: createWorkspaceConfig({
    sidebarLabel: 'Project Delivery',
    pageTitle: 'Project Delivery',
    eyebrow: 'FDSU ERP · Project Delivery',
    heroTitle: 'Keep projects moving by watching milestones, execution risk, approvals, and payment delays.',
    heroDescription:
      'This workspace is for the Project Delivery Lead. It centers on implementation progress, field issues, delivery blockers, and the finance or procurement dependencies that can delay execution.',
    primaryAction: { href: '/projects/projects-list', label: 'Review projects' },
    secondaryAction: { href: '/project_milestones/project_milestones-list', label: 'Review milestones' },
    briefingCards: [
      {
        title: 'Should see',
        items: ['Project status and milestone slippage', 'Field issues and execution risks', 'Approvals or payments delaying delivery'],
      },
      {
        title: 'Should do',
        items: ['Review project progress', 'Clear delivery blockers with other leads', 'Escalate risks before timelines fail'],
      },
      {
        title: 'Receives from',
        items: ['Project staff and field verification teams', 'Procurement and finance status updates', 'Administrator workflow escalations'],
      },
      {
        title: 'Hands off to',
        items: ['Director General for major decisions', 'Procurement and finance leads on blockers', 'Operational project teams for execution'],
      },
    ],
    highlightedMetricKeys: ['activeProjects', 'averageProjectProgress', 'highRiskProjects', 'pendingApprovals', 'overduePayments', 'unreadNotifications'],
    heroMetricKeys: ['activeProjects', 'averageProjectProgress', 'highRiskProjects', 'pendingApprovals'],
    blockOrder: ['summary', 'focus', 'watchlist', 'delivery', 'approvalRisk', 'actions'],
    sectionCopy: {
      approvalQueue: {
        eyebrow: 'Delivery blocker queue',
        title: 'Approvals holding back project execution',
        actionLabel: 'Open delivery blockers',
      },
      provinceRollout: {
        eyebrow: 'Delivery footprint',
        title: 'Project progress and execution pace by province',
        actionLabel: 'Open project register',
      },
      topContracts: {
        eyebrow: 'Delivery contracts',
        title: 'Largest contracts underpinning execution and milestone delivery',
        actionLabel: 'Open contracts',
      },
      quickActions: {
        eyebrow: 'Delivery shortcuts',
        title: 'Go directly to projects, milestones, blockers, and supporting contracts',
      },
    },
    quickLinks: [
      {
        href: '/projects/projects-list',
        label: 'Projects',
        description: 'Review implementation status and ownership.',
        icon: 'projects',
      },
      {
        href: '/project_milestones/project_milestones-list',
        label: 'Milestones',
        description: 'Track critical delivery checkpoints.',
        icon: 'milestones',
      },
      {
        href: '/approvals/approvals-list',
        label: 'Delivery blockers',
        description: 'See approvals slowing field execution.',
        icon: 'approvals',
      },
      {
        href: '/contracts/contracts-list',
        label: 'Supporting contracts',
        description: 'Inspect contracts affecting delivery scope.',
        icon: 'contracts',
      },
    ],
  }),
};

export function getWorkspaceConfig(roleName?: string | null): WorkspaceConfig {
  if (!roleName) {
    return workspaceConfigs[WORKSPACE_ROLES.projectDeliveryLead];
  }

  return workspaceConfigs[roleName] || workspaceConfigs[WORKSPACE_ROLES.projectDeliveryLead];
}

export function getWorkspaceRoute(roleName?: string | null) {
  if (!roleName) {
    return '/executive-summary';
  }

  return WORKSPACE_ROUTES[roleName] || '/executive-summary';
}

export function normalizeInternalRedirectTarget(target?: string | string[] | null) {
  const redirectTarget = Array.isArray(target) ? target[0] : target;

  if (!redirectTarget || typeof redirectTarget !== 'string') {
    return null;
  }

  if (!redirectTarget.startsWith('/') || redirectTarget.startsWith('//')) {
    return null;
  }

  if (redirectTarget.startsWith('/login')) {
    return null;
  }

  return redirectTarget;
}

export function getPostLoginRoute(roleName?: string | null, redirectTarget?: string | string[] | null) {
  return normalizeInternalRedirectTarget(redirectTarget) || getWorkspaceRoute(roleName);
}

export function getLoginRoute(redirectTarget?: string | string[] | null) {
  const safeRedirectTarget = normalizeInternalRedirectTarget(redirectTarget);

  if (!safeRedirectTarget) {
    return '/login';
  }

  return `/login?redirect=${encodeURIComponent(safeRedirectTarget)}`;
}

export function isDashboardRole(roleName?: string | null) {
  if (!roleName) {
    return false;
  }

  return ADMIN_DASHBOARD_ROLES.includes(roleName as (typeof ADMIN_DASHBOARD_ROLES)[number]);
}

export function itemVisibleForRole(itemRoles?: string[], roleName?: string | null) {
  if (!itemRoles?.length) {
    return true;
  }

  if (!roleName) {
    return false;
  }

  return itemRoles.includes(roleName);
}
