/* eslint-disable */
// ============================================================
// ACTIONS REGISTRY
// ------------------------------------------------------------
// The whole UI is rendered against this registry. Every clickable thing —
// page, toolbar button, row action, KPI card, detail tab — is an Action
// with an ActionId, a PartialView (which component renders it), and
// MergedParams (the JSON config that customises it).
//
// In production this comes from /api/rbac/payload/{actionId} (single)
// and /api/rbac/related/{actionId}/{Section} (related set). Here we mock
// the data inline; mockApi.jsx serves it asynchronously to simulate the
// real protocol.
// ============================================================

// ---- Personas + roles (the demo user roster) ----
const ROLES = [
  { id: "Admin",         icon: "shield",  blurb: "Full access · can edit configs" },
  { id: "Sales Manager", icon: "user",    blurb: "Most columns · can export" },
  { id: "Support Agent", icon: "user",    blurb: "Limited PII · read-mostly" },
];

const PERSONAS = {
  Admin:           { name: "Maya Patel",   initials: "MP", title: "Workspace admin",        accent: "#ad4a1a" },
  "Sales Manager": { name: "Daniel Kim",   initials: "DK", title: "Senior account manager", accent: "#0a6e6e" },
  "Support Agent": { name: "Sasha Müller", initials: "SM", title: "Customer support",       accent: "#7c3aed" },
};

// ---- Enum colour tokens (used by EnumPill renderer) ----
const ENUM_COLORS = {
  // Problem statuses
  Approved:    { bg: "var(--success-bg)", text: "var(--success)", dot: "var(--success)" },
  Rejected:    { bg: "var(--danger-bg)",  text: "var(--danger)",  dot: "var(--danger)"  },
  "On Hold":   { bg: "var(--warning-bg)", text: "var(--warning)", dot: "var(--warning)" },
  "In Review": { bg: "var(--info-bg)",    text: "var(--info)",    dot: "var(--info)"    },
  // Participant statuses
  Active:      { bg: "var(--success-bg)", text: "var(--success)", dot: "var(--success)" },
  Inactive:    { bg: "var(--surface-3)",  text: "var(--muted)",   dot: "var(--subtle)"  },
  Pending:     { bg: "var(--warning-bg)", text: "var(--warning)", dot: "var(--warning)" },
  // Participant roles
  Admin:       { bg: "var(--primary-bg)", text: "var(--primary)", dot: "var(--primary)" },
  Member:      { bg: "var(--accent-bg)",  text: "var(--accent)",  dot: "var(--accent)"  },
  Guest:       { bg: "var(--surface-3)",  text: "var(--muted)",   dot: "var(--subtle)"  },
  // Idea priorities
  High:        { bg: "var(--danger-bg)",  text: "var(--danger)",  dot: "var(--danger)"  },
  Medium:      { bg: "var(--warning-bg)", text: "var(--warning)", dot: "var(--warning)" },
  Low:         { bg: "var(--accent-bg)",  text: "var(--accent)",  dot: "var(--accent)"  },
};

// ---- Option sets (referenced by Column.OptionSet) ----
const OPTION_SETS = {
  OptIdeaStatus:    ["Approved", "Rejected", "On Hold", "In Review"],
  OptParticipantStatus: ["Active", "Inactive", "Pending"],
  OptParticipantRole:   ["Admin", "Member", "Guest"],
  OptPriority:      ["High", "Medium", "Low"],
};

// ============================================================
// MOCK DATA SOURCES
// (in production these live in the DB and come via /api/data/list)
// ============================================================
const DATA_SOURCES = {
  problems: [
    { Id: 1042, TeamLabel: "Frontend",  IdeaNumber: 1042, IdeaDescription: "Onboarding drops users after step 3 — <strong>conversion is 42%</strong>, target 70%. Need to investigate friction at the team-invite stage.", Recommendation_Value: "Approved",  Priority: "High",   SubmittedBy: "Maya Patel",    SubmittedAt: "2026-05-04T09:14:00Z", LinkedIdeas: 3 },
    { Id: 1043, TeamLabel: "Backend",   IdeaNumber: 1043, IdeaDescription: "API <code>/v2/search</code> p95 latency climbed to <strong>1.8s</strong> last week. Suspected N+1 query in tag lookup.", Recommendation_Value: "In Review", Priority: "High",   SubmittedBy: "Daniel Kim",    SubmittedAt: "2026-05-04T11:02:00Z", LinkedIdeas: 2 },
    { Id: 1044, TeamLabel: "Design",    IdeaNumber: 1044, IdeaDescription: "Dark-mode contrast fails WCAG on the secondary button. Audit revealed <em>11 components</em> below 4.5:1.", Recommendation_Value: "Approved",  Priority: "Medium", SubmittedBy: "Sasha Müller",  SubmittedAt: "2026-05-05T15:48:00Z", LinkedIdeas: 1 },
    { Id: 1045, TeamLabel: "Data",      IdeaNumber: 1045, IdeaDescription: "Daily ETL job has silently dropped <strong>~3% of events</strong> for three weeks. Schema drift in `event_meta`.", Recommendation_Value: "Approved",  Priority: "High",   SubmittedBy: "Imran Qureshi", SubmittedAt: "2026-05-05T17:23:00Z", LinkedIdeas: 0 },
    { Id: 1046, TeamLabel: "Platform",  IdeaNumber: 1046, IdeaDescription: "Build pipeline averages <strong>14 min</strong>; engineers report context-switching cost. Cache hit rate is 38%.", Recommendation_Value: "On Hold",   Priority: "Medium", SubmittedBy: "Hannah Wright", SubmittedAt: "2026-05-06T08:41:00Z", LinkedIdeas: 4 },
    { Id: 1047, TeamLabel: "Mobile",    IdeaNumber: 1047, IdeaDescription: "iOS crash on push notification tap. Stack points to a nil unwrap in <code>DeepLinkRouter</code>. <em>147 affected sessions yesterday.</em>", Recommendation_Value: "Approved",  Priority: "High",   SubmittedBy: "Lucas Romero",  SubmittedAt: "2026-05-06T12:09:00Z", LinkedIdeas: 2 },
    { Id: 1048, TeamLabel: "Growth",    IdeaNumber: 1048, IdeaDescription: "Trial-to-paid conversion lifts <strong>+8.2%</strong> when the pricing page leads with annual. Validated in EU cohort, propose global rollout.", Recommendation_Value: "In Review", Priority: "Medium", SubmittedBy: "Priya Shah",    SubmittedAt: "2026-05-07T10:27:00Z", LinkedIdeas: 5 },
    { Id: 1049, TeamLabel: "Backend",   IdeaNumber: 1049, IdeaDescription: "Customer reports duplicated webhooks during deploys. Idempotency key not checked on the retry path.", Recommendation_Value: "Approved",  Priority: "High",   SubmittedBy: "Daniel Kim",    SubmittedAt: "2026-05-07T14:55:00Z", LinkedIdeas: 1 },
    { Id: 1050, TeamLabel: "Frontend",  IdeaNumber: 1050, IdeaDescription: "Table virtualization is jittery on Safari 17. <em>requestAnimationFrame</em> coalescing fix lined up for next sprint.", Recommendation_Value: "On Hold",   Priority: "Low",    SubmittedBy: "Maya Patel",    SubmittedAt: "2026-05-08T09:00:00Z", LinkedIdeas: 0 },
    { Id: 1051, TeamLabel: "Design",    IdeaNumber: 1051, IdeaDescription: "Iconography inconsistencies across the admin app — at least <strong>three icon families</strong> in use. Consolidation needed.", Recommendation_Value: "Approved",  Priority: "Low",    SubmittedBy: "Sasha Müller",  SubmittedAt: "2026-05-08T13:12:00Z", LinkedIdeas: 0 },
    { Id: 1052, TeamLabel: "Data",      IdeaNumber: 1052, IdeaDescription: "Customer-segmentation dashboard takes <strong>~9s</strong> to render. Pre-aggregating in nightly job should cut to under 1s.", Recommendation_Value: "In Review", Priority: "Medium", SubmittedBy: "Imran Qureshi", SubmittedAt: "2026-05-09T07:46:00Z", LinkedIdeas: 2 },
    { Id: 1053, TeamLabel: "Platform",  IdeaNumber: 1053, IdeaDescription: "Migrate legacy cron service to scheduled workers. Effort: <em>2 sprints, 1 engineer</em>. Eliminates 6 incidents/quarter.", Recommendation_Value: "Approved",  Priority: "Medium", SubmittedBy: "Hannah Wright", SubmittedAt: "2026-05-09T16:34:00Z", LinkedIdeas: 1 },
    { Id: 1054, TeamLabel: "Mobile",    IdeaNumber: 1054, IdeaDescription: "Android app size has grown <strong>+22 MB</strong> in 6 months. R8 config can recover ~14 MB.", Recommendation_Value: "Approved",  Priority: "Low",    SubmittedBy: "Lucas Romero",  SubmittedAt: "2026-05-10T11:21:00Z", LinkedIdeas: 0 },
    { Id: 1055, TeamLabel: "Growth",    IdeaNumber: 1055, IdeaDescription: "Referral copy A/B: variant B (\"give $20, get $20\") outperforms control by <strong>+31%</strong>.", Recommendation_Value: "Approved",  Priority: "Medium", SubmittedBy: "Priya Shah",    SubmittedAt: "2026-05-10T13:50:00Z", LinkedIdeas: 3 },
    { Id: 1056, TeamLabel: "Backend",   IdeaNumber: 1056, IdeaDescription: "DB connection pool saturates during nightly imports. Move imports to a dedicated reader.", Recommendation_Value: "Rejected",  Priority: "Low",    SubmittedBy: "Daniel Kim",    SubmittedAt: "2026-05-11T08:18:00Z", LinkedIdeas: 0 },
    { Id: 1057, TeamLabel: "Frontend",  IdeaNumber: 1057, IdeaDescription: "Replace legacy modal stack with the new headless dialog primitive. Touches <em>~40 call sites</em>.", Recommendation_Value: "In Review", Priority: "Medium", SubmittedBy: "Maya Patel",    SubmittedAt: "2026-05-11T15:02:00Z", LinkedIdeas: 1 },
    { Id: 1058, TeamLabel: "Design",    IdeaNumber: 1058, IdeaDescription: "Empty states feel inconsistent. Propose a small kit: <strong>4 layouts + 1 illustration system</strong>.", Recommendation_Value: "Approved",  Priority: "Low",    SubmittedBy: "Sasha Müller",  SubmittedAt: "2026-05-12T10:11:00Z", LinkedIdeas: 2 },
    { Id: 1059, TeamLabel: "Data",      IdeaNumber: 1059, IdeaDescription: "Sales asks for cohort retention export. Doable with current pipeline; ~3 days of work.", Recommendation_Value: "On Hold",   Priority: "Low",    SubmittedBy: "Imran Qureshi", SubmittedAt: "2026-05-12T14:33:00Z", LinkedIdeas: 1 },
    { Id: 1060, TeamLabel: "Platform",  IdeaNumber: 1060, IdeaDescription: "Tracing rolled out to <strong>3/12</strong> services. Prioritize checkout path next — biggest revenue impact.", Recommendation_Value: "Approved",  Priority: "High",   SubmittedBy: "Hannah Wright", SubmittedAt: "2026-05-13T09:55:00Z", LinkedIdeas: 4 },
    { Id: 1061, TeamLabel: "Growth",    IdeaNumber: 1061, IdeaDescription: "Drip campaign step 4 unsubscribe rate is <strong>5.7%</strong>, ~3× cohort average. Recommend rewriting.", Recommendation_Value: "Rejected",  Priority: "Medium", SubmittedBy: "Priya Shah",    SubmittedAt: "2026-05-13T12:40:00Z", LinkedIdeas: 0 },
  ],
  participants: [
    { Id: "p01", FirstName: "Maya",     LastName: "Patel",         Email: "maya.patel@northwind.io",  Phone: "+1 (415) 555-0142", JoinedDate: "2024-11-03T00:00:00Z", Status: "Active",   Role: "Admin",  LastActiveAt: "2026-05-13T09:32:00Z", Conversations: 47 },
    { Id: "p02", FirstName: "Daniel",   LastName: "Kim",           Email: "d.kim@northwind.io",       Phone: "+1 (206) 555-0188", JoinedDate: "2024-08-21T00:00:00Z", Status: "Active",   Role: "Admin",  LastActiveAt: "2026-05-13T08:51:00Z", Conversations: 31 },
    { Id: "p03", FirstName: "Sasha",    LastName: "Müller",        Email: "sasha.muller@northwind.io",Phone: "+49 30 555 0173",   JoinedDate: "2025-01-14T00:00:00Z", Status: "Active",   Role: "Member", LastActiveAt: "2026-05-12T17:14:00Z", Conversations: 19 },
    { Id: "p04", FirstName: "Imran",    LastName: "Qureshi",       Email: "imran.q@northwind.io",     Phone: "+1 (737) 555-0119", JoinedDate: "2024-09-09T00:00:00Z", Status: "Active",   Role: "Member", LastActiveAt: "2026-05-13T07:46:00Z", Conversations: 22 },
    { Id: "p05", FirstName: "Hannah",   LastName: "Wright",        Email: "hannah.wright@northwind.io",Phone:"+1 (917) 555-0166", JoinedDate: "2024-07-02T00:00:00Z", Status: "Active",   Role: "Admin",  LastActiveAt: "2026-05-13T10:02:00Z", Conversations: 38 },
    { Id: "p06", FirstName: "Lucas",    LastName: "Romero",        Email: "lucas.r@northwind.io",     Phone: "+34 91 555 0149",   JoinedDate: "2025-02-18T00:00:00Z", Status: "Active",   Role: "Member", LastActiveAt: "2026-05-12T22:09:00Z", Conversations: 14 },
    { Id: "p07", FirstName: "Priya",    LastName: "Shah",          Email: "priya.shah@northwind.io",  Phone: "+1 (510) 555-0102", JoinedDate: "2024-06-28T00:00:00Z", Status: "Active",   Role: "Member", LastActiveAt: "2026-05-13T09:00:00Z", Conversations: 26 },
    { Id: "p08", FirstName: "Noah",     LastName: "Lindqvist",     Email: "noah.l@northwind.io",      Phone: "+46 8 555 0135",    JoinedDate: "2025-04-11T00:00:00Z", Status: "Pending",  Role: "Guest",  LastActiveAt: "2026-05-10T14:25:00Z", Conversations: 2 },
    { Id: "p09", FirstName: "Amara",    LastName: "Okafor",        Email: "amara.o@northwind.io",     Phone: "+44 20 7946 0721",  JoinedDate: "2024-12-19T00:00:00Z", Status: "Active",   Role: "Member", LastActiveAt: "2026-05-13T11:18:00Z", Conversations: 18 },
    { Id: "p10", FirstName: "Bjorn",    LastName: "Halvorsen",     Email: "bjorn.h@northwind.io",     Phone: "+47 22 555 0190",   JoinedDate: "2024-05-14T00:00:00Z", Status: "Inactive", Role: "Member", LastActiveAt: "2026-01-17T16:42:00Z", Conversations: 0 },
    { Id: "p11", FirstName: "Camila",   LastName: "Soto",          Email: "c.soto@northwind.io",      Phone: "+52 55 5555 0177",  JoinedDate: "2025-03-22T00:00:00Z", Status: "Active",   Role: "Member", LastActiveAt: "2026-05-13T06:55:00Z", Conversations: 11 },
    { Id: "p12", FirstName: "Eli",      LastName: "Becker",        Email: "eli.becker@northwind.io",  Phone: "+1 (212) 555-0181", JoinedDate: "2024-10-08T00:00:00Z", Status: "Active",   Role: "Admin",  LastActiveAt: "2026-05-13T10:44:00Z", Conversations: 41 },
    { Id: "p13", FirstName: "Fatima",   LastName: "Al-Rashid",     Email: "f.alrashid@northwind.io",  Phone: "+971 4 555 0162",   JoinedDate: "2025-05-30T00:00:00Z", Status: "Pending",  Role: "Guest",  LastActiveAt: "2026-05-09T13:12:00Z", Conversations: 1 },
    { Id: "p14", FirstName: "Theo",     LastName: "Ashworth",      Email: "theo.a@northwind.io",      Phone: "+1 (646) 555-0157", JoinedDate: "2024-04-04T00:00:00Z", Status: "Active",   Role: "Member", LastActiveAt: "2026-05-12T19:30:00Z", Conversations: 23 },
    { Id: "p15", FirstName: "Yui",      LastName: "Tanaka",        Email: "yui.tanaka@northwind.io",  Phone: "+81 3 5555 0124",   JoinedDate: "2025-01-29T00:00:00Z", Status: "Active",   Role: "Member", LastActiveAt: "2026-05-13T03:51:00Z", Conversations: 17 },
    { Id: "p16", FirstName: "Rohan",    LastName: "Mehta",         Email: "rohan.m@northwind.io",     Phone: "+91 22 5555 0148",  JoinedDate: "2024-08-15T00:00:00Z", Status: "Active",   Role: "Member", LastActiveAt: "2026-05-13T04:10:00Z", Conversations: 29 },
    { Id: "p17", FirstName: "Ines",     LastName: "Carvalho",      Email: "ines.c@northwind.io",      Phone: "+351 21 555 0115",  JoinedDate: "2024-11-25T00:00:00Z", Status: "Inactive", Role: "Guest",  LastActiveAt: "2025-12-04T11:22:00Z", Conversations: 0 },
    { Id: "p18", FirstName: "Kofi",     LastName: "Mensah",        Email: "kofi.mensah@northwind.io", Phone: "+233 30 555 0140",  JoinedDate: "2025-06-12T00:00:00Z", Status: "Active",   Role: "Member", LastActiveAt: "2026-05-12T20:48:00Z", Conversations: 8 },
    { Id: "p19", FirstName: "Ada",      LastName: "Whitfield",     Email: "ada.w@northwind.io",       Phone: "+1 (303) 555-0193", JoinedDate: "2024-02-09T00:00:00Z", Status: "Active",   Role: "Admin",  LastActiveAt: "2026-05-13T09:21:00Z", Conversations: 52 },
    { Id: "p20", FirstName: "Marek",    LastName: "Nowak",         Email: "marek.n@northwind.io",     Phone: "+48 22 555 0156",   JoinedDate: "2025-07-04T00:00:00Z", Status: "Pending",  Role: "Guest",  LastActiveAt: "2026-05-08T15:00:00Z", Conversations: 3 },
  ],
  ideas: [
    // Derived from problems; each idea is a proposed solution to one problem
    { Id: "i01", ParentId: 1042, Title: "Add inline tooltips at the team-invite step", Owner: "Maya Patel",    Impact: 7.5, Effort: 3, Priority: "High",   Status: "In Review",  CreatedAt: "2026-05-05T10:14:00Z" },
    { Id: "i02", ParentId: 1042, Title: "Pre-fill teammate emails from contact import", Owner: "Maya Patel",   Impact: 8.2, Effort: 5, Priority: "Medium", Status: "Approved",   CreatedAt: "2026-05-05T12:31:00Z" },
    { Id: "i03", ParentId: 1042, Title: "Replace step 3 with a skip-and-continue flow", Owner: "Sasha Müller", Impact: 6.0, Effort: 2, Priority: "Low",    Status: "On Hold",    CreatedAt: "2026-05-06T08:55:00Z" },
    { Id: "i04", ParentId: 1043, Title: "Add covering index on (account_id, tag_id)",   Owner: "Daniel Kim",   Impact: 9.0, Effort: 1, Priority: "High",   Status: "Approved",   CreatedAt: "2026-05-04T16:00:00Z" },
    { Id: "i05", ParentId: 1043, Title: "Rewrite N+1 in tag-resolver as a single CTE",  Owner: "Daniel Kim",   Impact: 8.7, Effort: 3, Priority: "High",   Status: "In Review",  CreatedAt: "2026-05-05T09:22:00Z" },
    { Id: "i06", ParentId: 1044, Title: "Bump secondary button to #1f2937 on dark",     Owner: "Sasha Müller", Impact: 5.5, Effort: 1, Priority: "Medium", Status: "Approved",   CreatedAt: "2026-05-06T11:11:00Z" },
    { Id: "i07", ParentId: 1046, Title: "Move npm install to a warm cache layer",        Owner: "Hannah Wright",Impact: 7.0, Effort: 2, Priority: "Medium", Status: "Approved",   CreatedAt: "2026-05-07T13:00:00Z" },
    { Id: "i08", ParentId: 1046, Title: "Parallelize test shards by previous-run timing",Owner: "Hannah Wright",Impact: 6.5, Effort: 4, Priority: "Low",    Status: "On Hold",    CreatedAt: "2026-05-08T09:10:00Z" },
    { Id: "i09", ParentId: 1048, Title: "Ship annual-default for new EU signups first",  Owner: "Priya Shah",   Impact: 9.2, Effort: 1, Priority: "High",   Status: "In Review",  CreatedAt: "2026-05-07T14:00:00Z" },
    { Id: "i10", ParentId: 1055, Title: "Localise referral copy variant B for FR/DE/ES", Owner: "Priya Shah",   Impact: 6.8, Effort: 3, Priority: "Medium", Status: "Approved",   CreatedAt: "2026-05-11T10:00:00Z" },
    { Id: "i11", ParentId: 1060, Title: "Instrument checkout span with x-request-id",    Owner: "Hannah Wright",Impact: 8.0, Effort: 2, Priority: "High",   Status: "Approved",   CreatedAt: "2026-05-13T11:00:00Z" },
    { Id: "i12", ParentId: 1047, Title: "Add nil-check + crashlytics breadcrumb",        Owner: "Lucas Romero", Impact: 8.4, Effort: 1, Priority: "High",   Status: "Approved",   CreatedAt: "2026-05-07T08:30:00Z" },
  ],
};

// ---- Per-problem detail data (mock returns from /api/data/list scoped to a parent) ----
// Returns fake conversations + activity per problem id.
const PROBLEM_CONVERSATIONS = {
  1042: [
    { Id: "c1", When: "2026-05-04T08:50:00Z", Speaker: "Customer", Snippet: "I tried inviting my team but couldn't get past the step asking for everyone's email all at once." },
    { Id: "c2", When: "2026-05-04T09:01:00Z", Speaker: "Agent",    Snippet: "Could you skip that step? Some people add teammates later from settings." },
    { Id: "c3", When: "2026-05-04T09:04:00Z", Speaker: "Customer", Snippet: "Yes — I just exited and came back from a different link." },
  ],
  1043: [
    { Id: "c1", When: "2026-05-04T10:15:00Z", Speaker: "Customer", Snippet: "Search has gotten really slow this week — sometimes it spins for 2 seconds." },
    { Id: "c2", When: "2026-05-04T10:42:00Z", Speaker: "Agent",    Snippet: "Got it. We're seeing the same on our internal dashboards. Engineering is investigating." },
  ],
  1044: [
    { Id: "c1", When: "2026-05-05T13:20:00Z", Speaker: "Customer", Snippet: "The secondary button on the settings page is hard to read in dark mode." },
  ],
};

const PROBLEM_ACTIVITY = {
  1042: [
    { Id: "a1", When: "2026-05-04T09:14:00Z", Type: "created",  Actor: "system",   Text: "Problem extracted from conversation #c-2204" },
    { Id: "a2", When: "2026-05-05T10:14:00Z", Type: "linked",   Actor: "Maya Patel", Text: "Linked idea i01 \"Add inline tooltips at the team-invite step\"" },
    { Id: "a3", When: "2026-05-06T11:55:00Z", Type: "status",   Actor: "Maya Patel", Text: "Status set to Approved" },
  ],
  1043: [
    { Id: "a1", When: "2026-05-04T11:02:00Z", Type: "created",  Actor: "system",      Text: "Problem extracted from conversation #c-2210" },
    { Id: "a2", When: "2026-05-04T16:00:00Z", Type: "linked",   Actor: "Daniel Kim",  Text: "Linked idea i04 \"Add covering index on (account_id, tag_id)\"" },
  ],
};

// ============================================================
// COLUMN DEFINITIONS (used in MergedParams.Columns)
// ============================================================
const COL_LIBRARY = {
  problems: [
    { ColOrder: 10,  PropertyName: "IdeaNumber",            Label: "#",            DataType: "int",      Visible: true, Selected: true, Sortable: true, Filterable: true, Groupable: false, Width: "80px",  ReadOnly: true },
    { ColOrder: 20,  PropertyName: "TeamLabel",             Label: "Team",         DataType: "string",   Visible: true, Selected: true, Sortable: true, Filterable: true, Groupable: true,  Width: "130px", ReadOnly: false, Aggregate: "Count" },
    { ColOrder: 30,  PropertyName: "IdeaDescription",       Label: "Description",  DataType: "string",   Visible: true, Selected: true, Sortable: false,Filterable: true, Groupable: false, Width: "auto",  ReadOnly: false, IsHtml: true },
    { ColOrder: 40,  PropertyName: "Recommendation_Value",  Label: "Status",       DataType: "enum",     Visible: true, Selected: true, Sortable: true, Filterable: true, Groupable: true,  Width: "130px", ReadOnly: false, OptionSet: "OptIdeaStatus", Aggregate: "Count" },
    { ColOrder: 50,  PropertyName: "Priority",              Label: "Priority",     DataType: "enum",     Visible: true, Selected: true, Sortable: true, Filterable: true, Groupable: true,  Width: "110px", ReadOnly: false, OptionSet: "OptPriority", Template: "_PriorityChip" },
    { ColOrder: 60,  PropertyName: "LinkedIdeas",           Label: "Ideas",        DataType: "int",      Visible: true, Selected: true, Sortable: true, Filterable: true, Groupable: false, Width: "80px",  ReadOnly: true, Template: "_BadgeNumber" },
    { ColOrder: 70,  PropertyName: "SubmittedBy",           Label: "Submitted by", DataType: "string",   Visible: true, Selected: true, Sortable: true, Filterable: true, Groupable: true,  Width: "150px", ReadOnly: true },
    { ColOrder: 80,  PropertyName: "SubmittedAt",           Label: "Submitted",    DataType: "datetime", Visible: true, Selected: true, Sortable: true, Filterable: true, Groupable: false, Width: "140px", ReadOnly: true, Format: "{0:MMM d, yyyy}" },
  ],
  participants: [
    { ColOrder: 10, PropertyName: "FirstName",    Label: "First name",   DataType: "string",   Visible: true, Selected: true, Sortable: true,  Filterable: true, Groupable: false, Width: "130px", ReadOnly: false },
    { ColOrder: 20, PropertyName: "LastName",     Label: "Last name",    DataType: "string",   Visible: true, Selected: true, Sortable: true,  Filterable: true, Groupable: false, Width: "130px", ReadOnly: false },
    { ColOrder: 30, PropertyName: "Email",        Label: "Email",        DataType: "string",   Visible: true, Selected: true, Sortable: true,  Filterable: true, Groupable: false, Width: "220px", ReadOnly: false, Template: "_EmailLink" },
    { ColOrder: 40, PropertyName: "Phone",        Label: "Phone",        DataType: "string",   Visible: true, Selected: true, Sortable: false, Filterable: true, Groupable: false, Width: "150px", ReadOnly: false },
    { ColOrder: 50, PropertyName: "JoinedDate",   Label: "Joined",       DataType: "datetime", Visible: true, Selected: true, Sortable: true,  Filterable: true, Groupable: false, Width: "120px", ReadOnly: true, Format: "{0:MMM d, yyyy}" },
    { ColOrder: 60, PropertyName: "Status",       Label: "Status",       DataType: "enum",     Visible: true, Selected: true, Sortable: true,  Filterable: true, Groupable: true,  Width: "110px", ReadOnly: false, OptionSet: "OptParticipantStatus", Aggregate: "Count" },
    { ColOrder: 70, PropertyName: "Role",         Label: "Role",         DataType: "enum",     Visible: true, Selected: true, Sortable: true,  Filterable: true, Groupable: true,  Width: "110px", ReadOnly: false, OptionSet: "OptParticipantRole",   Aggregate: "Count" },
    { ColOrder: 80, PropertyName: "Conversations",Label: "Convos",       DataType: "int",      Visible: true, Selected: true, Sortable: true,  Filterable: true, Groupable: false, Width: "90px",  ReadOnly: true, Template: "_BadgeNumber" },
    { ColOrder: 90, PropertyName: "LastActiveAt", Label: "Last active",  DataType: "datetime", Visible: true, Selected: true, Sortable: true,  Filterable: true, Groupable: false, Width: "150px", ReadOnly: true, Format: "{0:MMM d, yyyy h:mm tt}" },
  ],
  ideas: [
    { ColOrder: 10, PropertyName: "Title",     Label: "Idea",      DataType: "string",   Visible: true, Selected: true, Sortable: true, Filterable: true, Groupable: false, Width: "auto",  ReadOnly: false },
    { ColOrder: 20, PropertyName: "Owner",     Label: "Owner",     DataType: "string",   Visible: true, Selected: true, Sortable: true, Filterable: true, Groupable: true,  Width: "150px", ReadOnly: true },
    { ColOrder: 30, PropertyName: "Impact",    Label: "Impact",    DataType: "decimal",  Visible: true, Selected: true, Sortable: true, Filterable: true, Groupable: false, Width: "90px",  ReadOnly: true, Format: "{0:0.0}", Template: "_ImpactBar", Aggregate: "Avg" },
    { ColOrder: 40, PropertyName: "Effort",    Label: "Effort",    DataType: "int",      Visible: true, Selected: true, Sortable: true, Filterable: true, Groupable: false, Width: "90px",  ReadOnly: true, Template: "_EffortDots" },
    { ColOrder: 50, PropertyName: "Priority",  Label: "Priority",  DataType: "enum",     Visible: true, Selected: true, Sortable: true, Filterable: true, Groupable: true,  Width: "110px", ReadOnly: false, OptionSet: "OptPriority" },
    { ColOrder: 60, PropertyName: "Status",    Label: "Status",    DataType: "enum",     Visible: true, Selected: true, Sortable: true, Filterable: true, Groupable: true,  Width: "130px", ReadOnly: false, OptionSet: "OptIdeaStatus", Aggregate: "Count" },
    { ColOrder: 70, PropertyName: "CreatedAt", Label: "Created",   DataType: "datetime", Visible: true, Selected: true, Sortable: true, Filterable: true, Groupable: false, Width: "130px", ReadOnly: true, Format: "{0:MMM d}" },
  ],
};

// ============================================================
// THE ACTION REGISTRY
// ============================================================
const ACTIONS = {
  // -------- Top-level pages --------
  10: {
    ActionId: 10, ActionName: "Dashboard", ActionTitle: "Workspace overview",
    PartialView: "Dashboard",
    MergedParams: { Subtitle: "Live KPIs across this workspace's conversations, ideas & participants" },
  },
  20: {
    ActionId: 20, ActionName: "Problems", ActionTitle: "Raw problems extracted from chats",
    PartialView: "Grid",
    MergedParams: {
      DataSource: "problems",
      DetailActionId: 90,                                // double-click → open this detail action
      Columns: COL_LIBRARY.problems,
      Sort: [{ PropertyName: "SubmittedAt", ColOrder: "10", SortDirection: "0", Grouping: "0" }],
      Filter: [],
      Pagination: { Enabled: true, PageSize: 10 },
      Pinned: { Top: 0, Left: 0 },
    },
  },
  21: {
    ActionId: 21, ActionName: "Participants", ActionTitle: "Registered participants",
    PartialView: "Grid",
    MergedParams: {
      DataSource: "participants",
      DetailActionId: null,
      Columns: COL_LIBRARY.participants,
      Sort: [{ PropertyName: "JoinedDate", ColOrder: "10", SortDirection: "0", Grouping: "0" }],
      Filter: [],
      Pagination: { Enabled: true, PageSize: 10 },
    },
  },
  22: {
    ActionId: 22, ActionName: "Ideas", ActionTitle: "Proposed solutions across all problems",
    PartialView: "Grid",
    MergedParams: {
      DataSource: "ideas",
      DetailActionId: null,
      Columns: COL_LIBRARY.ideas,
      Sort: [
        { PropertyName: "Priority", ColOrder: "10", SortDirection: "1", Grouping: "1" },
        { PropertyName: "Impact",   ColOrder: "20", SortDirection: "0", Grouping: "0" },
      ],
      Filter: [],
      Pagination: { Enabled: true, PageSize: 10 },
    },
  },

  // -------- KPI Cards (related to action 10 via Section "KPICard") --------
  30: { ActionId: 30, ActionName: "Total problems", PartialView: "KPICardWidget", MergedParams: { Title: "Total problems",  Icon: "inbox",       Format: "{0:#,##0}",    Trend: "+12%", TrendDir: "up",   Aggregation: "count",   DataSource: "problems",     Where: null } },
  31: { ActionId: 31, ActionName: "Approved",       PartialView: "KPICardWidget", MergedParams: { Title: "Approved",        Icon: "checkCircle", Format: "{0:#,##0}",    Trend: "+4",   TrendDir: "up",   Aggregation: "count",   DataSource: "problems",     Where: { field: "Recommendation_Value", eq: "Approved" } } },
  32: { ActionId: 32, ActionName: "Pending review", PartialView: "KPICardWidget", MergedParams: { Title: "Pending review",  Icon: "clock",       Format: "{0:#,##0}",    Trend: "-2",   TrendDir: "down", Aggregation: "count",   DataSource: "problems",     Where: { field: "Recommendation_Value", eq: "In Review" } } },
  33: { ActionId: 33, ActionName: "Active people",  PartialView: "KPICardWidget", MergedParams: { Title: "Active participants", Icon: "users",   Format: "{0:#,##0}",    Trend: "+1",   TrendDir: "up",   Aggregation: "count",   DataSource: "participants", Where: { field: "Status", eq: "Active" } } },
  34: { ActionId: 34, ActionName: "Ideas",          PartialView: "KPICardWidget", MergedParams: { Title: "Linked ideas",    Icon: "sparkles",    Format: "{0:#,##0}",    Trend: "+5",   TrendDir: "up",   Aggregation: "count",   DataSource: "ideas",        Where: null } },
  35: { ActionId: 35, ActionName: "Avg impact",     PartialView: "KPICardWidget", MergedParams: { Title: "Avg idea impact", Icon: "trendingUp",  Format: "{0:0.0}",      Trend: "+0.4", TrendDir: "up",   Aggregation: "avg",     DataSource: "ideas",        Field: "Impact" } },
  36: { ActionId: 36, ActionName: "Health score",   PartialView: "KPICardWidget", MergedParams: { Title: "Workspace health",Icon: "pulse",       Format: "{0:0.0%}",     Trend: "stable",TrendDir: "flat", Aggregation: "custom",  Value: 0.842 } },

  // -------- GridToolBar actions (related via Section "GridToolBar") --------
  50: { ActionId: 50, ActionName: "Refresh",      PartialView: "ToolbarButton", MergedParams: { Label: "Refresh",          Icon: "refresh",  Variant: "secondary", Handler: "refresh"            } },
  51: { ActionId: 51, ActionName: "Group by",     PartialView: "ToolbarButton", MergedParams: { Label: "Group",            Icon: "layers",   Variant: "secondary", Handler: "openGroupBy"        } },
  52: { ActionId: 52, ActionName: "Columns",      PartialView: "ToolbarButton", MergedParams: { Label: "Columns",          Icon: "columns",  Variant: "secondary", Handler: "openColumnChooser" } },
  53: { ActionId: 53, ActionName: "Export CSV",   PartialView: "ToolbarButton", MergedParams: { Label: "Export",           Icon: "download", Variant: "secondary", Handler: "exportCsv"          } },
  54: { ActionId: 54, ActionName: "Add problem",  PartialView: "ToolbarButton", MergedParams: { Label: "New problem",      Icon: "plus",     Variant: "primary",   Handler: "addRow"             } },
  55: { ActionId: 55, ActionName: "Add participant", PartialView: "ToolbarButton", MergedParams: { Label: "Invite people", Icon: "plus",     Variant: "primary",   Handler: "addRow"             } },
  56: { ActionId: 56, ActionName: "Add idea",     PartialView: "ToolbarButton", MergedParams: { Label: "New idea",         Icon: "plus",     Variant: "primary",   Handler: "addRow"             } },

  // -------- Bulk actions (related via Section "BulkActions") --------
  60: { ActionId: 60, ActionName: "Bulk approve", PartialView: "BulkAction",   MergedParams: { Label: "Approve",       Icon: "check",        Variant: "primary",   Handler: "bulkApprove", ConfirmMessage: null } },
  61: { ActionId: 61, ActionName: "Bulk reject",  PartialView: "BulkAction",   MergedParams: { Label: "Reject",        Icon: "xCircle",      Variant: "secondary", Handler: "bulkReject",  ConfirmMessage: "Reject the selected items?" } },
  62: { ActionId: 62, ActionName: "Bulk hold",    PartialView: "BulkAction",   MergedParams: { Label: "Put on hold",   Icon: "clock",        Variant: "secondary", Handler: "bulkHold",    ConfirmMessage: null } },
  63: { ActionId: 63, ActionName: "Bulk delete",  PartialView: "BulkAction",   MergedParams: { Label: "Delete",        Icon: "trash",        Variant: "danger",    Handler: "bulkDelete",  ConfirmMessage: "Permanently delete the selected rows?" } },

  // -------- RowActions (related via Section "RowActions") --------
  70: { ActionId: 70, ActionName: "View",       PartialView: "RowAction", MergedParams: { Label: "View",          Icon: "eye",    Handler: "viewRow"   } },
  71: { ActionId: 71, ActionName: "Edit",       PartialView: "RowAction", MergedParams: { Label: "Edit",          Icon: "pencil", Handler: "editRow"   } },
  72: { ActionId: 72, ActionName: "Approve",    PartialView: "RowAction", MergedParams: { Label: "Approve",       Icon: "check",  Handler: "approveRow"} },
  73: { ActionId: 73, ActionName: "Reject",     PartialView: "RowAction", MergedParams: { Label: "Reject",        Icon: "xCircle",Handler: "rejectRow" } },
  74: { ActionId: 74, ActionName: "Delete",     PartialView: "RowAction", MergedParams: { Label: "Delete",        Icon: "trash",  Handler: "deleteRow", Danger: true } },
  75: { ActionId: 75, ActionName: "Assign to me",PartialView: "RowAction",MergedParams: { Label: "Assign to me",  Icon: "user",   Handler: "assignToMe"} },

  // -------- Detail (master-detail) --------
  90: {
    ActionId: 90, ActionName: "Problem detail", ActionTitle: "Problem detail",
    PartialView: "Detail",
    MergedParams: { DataSource: "problems", Title: "Problem #{IdeaNumber}", Subtitle: "{IdeaDescription}" },
  },
  // Detail tabs (related to 90 via Section "DetailTab")
  91: { ActionId: 91, ActionName: "Overview",      PartialView: "DetailTab", MergedParams: { Label: "Overview",       Icon: "info",     Body: "overview"     } },
  92: { ActionId: 92, ActionName: "Related ideas", PartialView: "DetailTab", MergedParams: { Label: "Related ideas",  Icon: "sparkles", Body: "relatedIdeas" } },
  93: { ActionId: 93, ActionName: "Conversations", PartialView: "DetailTab", MergedParams: { Label: "Conversations",  Icon: "message",  Body: "conversations"} },
  94: { ActionId: 94, ActionName: "Activity",      PartialView: "DetailTab", MergedParams: { Label: "Activity",       Icon: "history",  Body: "activity"     } },

  // -------- Admin pages --------
  100: { ActionId: 100, ActionName: "Settings", ActionTitle: "Settings & RBAC", PartialView: "RBACManager", MergedParams: {} },
  101: { ActionId: 101, ActionName: "Action library", ActionTitle: "Action library", PartialView: "ActionLibrary", MergedParams: {} },
};

// ============================================================
// RELATED MAP — parentActionId × Section → ordered list of child actionIds
// (mocked replacement for /api/rbac/related/{actionId}/{Section})
// ============================================================
const RELATED = {
  // Dashboard's KPI cards (ordered)
  10: { KPICard: [30, 31, 32, 33, 34, 35] },
  // Problems grid's toolbar / row actions / bulk actions
  20: {
    GridToolBar: [50, 51, 52, 53, 54],
    RowActions:  [70, 71, 72, 73, 74],
    BulkActions: [60, 61, 62, 63],
  },
  21: {
    GridToolBar: [50, 51, 52, 53, 55],
    RowActions:  [70, 71, 74, 75],
    BulkActions: [63],
  },
  22: {
    GridToolBar: [50, 51, 52, 53, 56],
    RowActions:  [70, 71, 72, 73],
    BulkActions: [60, 61],
  },
  // Detail tabs
  90: { DetailTab: [91, 92, 93, 94] },
};

// ============================================================
// RBAC — role → Set<actionId>
// In the real backend, every API call is also RBAC-checked. Here we filter
// related-action lists by intersecting with the active role's allowed set.
// ============================================================
const RBAC = {
  Admin: new Set([10,20,21,22, 30,31,32,33,34,35,36, 50,51,52,53,54,55,56, 60,61,62,63, 70,71,72,73,74,75, 90,91,92,93,94, 100,101]),
  "Sales Manager": new Set([10,20,21,22, 30,31,32,33,34,35, 50,51,52,53, 60,62, 70,71,72,73, 90,91,92,93]),
  "Support Agent": new Set([10,20, 30,31,32,33, 50,51,52, 70, 90,91,93]),
};

// ============================================================
// MENU — role → ordered list of menu entries (each refers to an actionId).
// label/icon/section overrides come from here (the backend can override the
// action's own label per role-context).
// ============================================================
const DEFAULT_MENU = {
  Admin: [
    { id: "m-dash", actionId: 10, label: "Dashboard",     icon: "layoutDashboard", section: "Workspace",      visible: true },
    { id: "m-prob", actionId: 20, label: "Problems",      icon: "sparkles",        section: "Workspace",      visible: true },
    { id: "m-idea", actionId: 22, label: "Ideas",         icon: "zap",             section: "Workspace",      visible: true },
    { id: "m-part", actionId: 21, label: "Participants", icon: "users",           section: "Workspace",      visible: true },
    { id: "m-cfg",  actionId: 100, label: "Settings",     icon: "sliders",         section: "Administration", visible: true, locked: true },
    { id: "m-lib",  actionId: 101, label: "Action library", icon: "database",      section: "Administration", visible: true, locked: true },
  ],
  "Sales Manager": [
    { id: "m-dash", actionId: 10, label: "Pipeline overview", icon: "layoutDashboard", section: "Pipeline", visible: true },
    { id: "m-prob", actionId: 20, label: "Customer pain points", icon: "sparkles",     section: "Pipeline", visible: true },
    { id: "m-idea", actionId: 22, label: "Ideas",         icon: "zap",                  section: "Pipeline", visible: true },
    { id: "m-part", actionId: 21, label: "Accounts",      icon: "building",             section: "Pipeline", visible: true },
  ],
  "Support Agent": [
    { id: "m-dash", actionId: 10, label: "Today",         icon: "layoutDashboard", section: "Help desk", visible: true },
    { id: "m-prob", actionId: 20, label: "Open issues",   icon: "inbox",           section: "Help desk", visible: true },
  ],
};

// Per-role overrides for an action's page-level Title/Subtitle (so the same
// action looks role-appropriate when loaded). MergedParams within the action
// is single (one config per action) — these overrides only retitle.
const ACTION_TITLE_OVERRIDES = {
  "Sales Manager": {
    10: { ActionTitle: "Pipeline overview" },
    20: { ActionTitle: "Customer pain points",  Subtitle: "Issues raised by accounts you manage" },
    21: { ActionTitle: "Accounts",              Subtitle: "Active customer roster" },
  },
  "Support Agent": {
    10: { ActionTitle: "Today",                 Subtitle: "What needs attention right now" },
    20: { ActionTitle: "Open issues",           Subtitle: "Items needing follow-up" },
  },
};

// ============================================================
// SAVED VIEWS — defaults (in production keyed per user+action)
// ============================================================
const DEFAULT_SAVED_VIEWS = {
  20: [
    {
      id: "sv-highprio-open",
      name: "High-priority · open",
      MergedParams: {
        Sort: [{ PropertyName: "Priority", ColOrder: "10", SortDirection: "1", Grouping: "0" }],
        Filter: [
          { PropertyName: "Priority",             LogicalOperator: "AND", Filters: [{ Operator: "Eq", Value: "High" }] },
          { PropertyName: "Recommendation_Value", LogicalOperator: "AND", Filters: [{ Operator: "Neq", Value: "Rejected" }] },
        ],
      },
    },
    {
      id: "sv-by-team",
      name: "Grouped by team",
      MergedParams: {
        Sort: [{ PropertyName: "TeamLabel", ColOrder: "10", SortDirection: "1", Grouping: "1" }],
        Filter: [],
      },
    },
  ],
  22: [
    {
      id: "sv-impact",
      name: "Highest impact",
      MergedParams: {
        Sort: [{ PropertyName: "Impact", ColOrder: "10", SortDirection: "0", Grouping: "0" }],
        Filter: [],
      },
    },
  ],
};

Object.assign(window, {
  ROLES, PERSONAS, ENUM_COLORS, OPTION_SETS,
  DATA_SOURCES, PROBLEM_CONVERSATIONS, PROBLEM_ACTIVITY,
  COL_LIBRARY,
  ACTIONS, RELATED, RBAC, DEFAULT_MENU, ACTION_TITLE_OVERRIDES,
  DEFAULT_SAVED_VIEWS,
});
