// Seed data for Nudge CRM prototype
const SEED_DEALS = [
  {
    id: "atlas",
    company: "Atlas Logistics",
    dealName: "Q4 Enterprise Expansion",
    stage: "Negotiation",
    value: 340000,
    arr: "$340K ARR",
    closeDate: "May 20, 2026",
    status: "at-risk",
    statusLabel: "At Risk",
    champion: "Sarah Chen",
    championRole: "VP Operations",
    buyerScore: 50,
    sellerScore: 83,
    gap: -33,
    summary:
      "I've spotted a critical gap: Sarah Chen at Atlas Logistics reposted Linnworks' warehouse automation content on LinkedIn while our thread has been quiet. Buyer score dropped 15 points overnight (50% vs seller 83%). I recommend sending a focused competitive displacement note today — I've drafted one for you in AI Actions.",
    trend: [42, 48, 52, 58, 62, 65, 64, 60, 56, 52, 50],
    sellerTrend: [70, 72, 75, 78, 80, 82, 83, 84, 84, 83, 83],
    scoreEvents: [
      { delta: -15, label: "went silent 72h" },
      { delta: -8, label: "CFO unidentified" },
      { delta: +6, label: "confirmed budget approval" },
    ],
    nudges: [
      {
        kind: "GAP DETECTED",
        title: "Sarah Chen reposted Linnworks content",
        sub: "LinkedIn — Atlas champion amplified competitor warehouse automation post",
        action: "Send Linnworks displacement note",
        executeLabel: "Review competitive email",
        severity: "warn",
        evidence: {
          source: "LinkedIn",
          time: "Today",
          detail: "Sarah Chen reposted Linnworks' warehouse automation launch",
          proof: "Champion activity shifted toward a named competitor while the Atlas buying thread has been quiet for 72h.",
        },
      },
      {
        kind: "MISSING STAKEHOLDERS",
        title: "Decision-maker not yet involved",
        sub: "Atlas Logistics — CFO missing",
        action: "Draft Intro Request",
        severity: "warn",
      },
      {
        kind: "MISSING APPROVAL PATH",
        title: "Undocumented decision process",
        sub: "Atlas Logistics — path unknown",
        action: "Ask About Process",
        severity: "info",
      },
    ],
    activity: [
      {
        time: "Apr 24, 9:14 AM",
        kind: "email",
        actor: "Sarah Chen",
        title: "Replied to pricing thread",
        body: "Confirmed budget approval is contingent on procurement signoff.",
        tag: "buyer",
      },
      {
        time: "Apr 22, 4:02 PM",
        kind: "meeting",
        actor: "You + Sarah Chen",
        title: "Mutual action plan workshop",
        body: "Agreed on technical evaluation window through May 8.",
        tag: "milestone",
      },
      {
        time: "Apr 19, 11:30 AM",
        kind: "addy",
        actor: "Addy",
        title: "Flagged momentum stall",
        body: "Engagement score dropped 15 pts. Suggested re-engagement sequence.",
        tag: "ai",
      },
      {
        time: "Today, 8:42 AM",
        kind: "addy",
        actor: "Addy",
        title: "Detected competitor content signal",
        body: "Sarah Chen reposted Linnworks' warehouse automation launch on LinkedIn while the Atlas buying thread stayed quiet.",
        tag: "ai",
      },
      {
        time: "Apr 17, 8:51 AM",
        kind: "note",
        actor: "Ridha",
        title: "Logged competitive mention",
        body: "Buyer mentioned evaluating Linnworks — sent battlecard.",
        tag: "internal",
      },
    ],
    stakeholders: [
      { name: "Sarah Chen", role: "VP Operations", power: 4, support: 4, missing: false },
      { name: "Marcus Vela", role: "CFO", power: 5, support: 1, missing: true },
      { name: "Priya Rao", role: "Head of IT", power: 3, support: 3, missing: false },
      { name: "Devon Park", role: "Procurement", power: 3, support: 2, missing: false },
    ],
    meetings: [
      {
        id: "atlas-mtg-3",
        title: "Re-engagement check-in",
        date: "Apr 30, 3:00 PM PT",
        duration: "30 min",
        isPast: false,
        attendees: ["Sarah Chen", "Ridha"],
        goal: "Get Sarah back active and surface what's actually blocking her",
        intel: {
          pulse: "Sarah hasn't replied in 5 days. Engagement score dropped 15 pts. CFO Marcus Vela still never engaged.",
          risks: [
            "CFO Marcus Vela has not been looped in — likely the silent blocker.",
            "Procurement timeline puts the May close window at risk if no movement this week.",
            "A competitor (Linnworks) was mentioned in passing on Apr 17 — confirm it's still in the running.",
          ],
          talkingPoints: [
            "Open with a timeline check — does Apr 30 close still feel achievable on their side?",
            "Surface the CFO directly: 'Who else needs to weigh in before we sign?'",
            "Recap the v3 proposal pilot results so the value is fresh.",
            "Ask about the Linnworks evaluation — pre-empt the comparison.",
          ],
          docs: ["Proposal v3", "Atlas — Security FAQ", "Linnworks battlecard"],
        },
      },
      {
        id: "atlas-mtg-2",
        title: "Pricing thread review",
        date: "Apr 22, 4:02 PM PT",
        duration: "32 min",
        isPast: true,
        attendees: ["Sarah Chen", "Ridha"],
        debrief: {
          sentiment: "Cooperative but cautious",
          summary: "Sarah confirmed the budget is approved pending procurement sign-off. Asked detailed questions on the SLA tier and data residency. Did not commit to bringing the CFO in this week.",
          transcriptExcerpt: "...so when we say budget approved, that's contingent on procurement signoff, which usually takes 3 to 4 days at our end. I'll come back to you next week with a clearer view on...",
          videoUrl: "#",
          nextSteps: [
            "Send security FAQ document",
            "Schedule legal redline walkthrough",
            "Push for CFO intro by end of week",
          ],
          addyNotes: [
            "Sarah said 'we'd want to see at least 2 customer references' — flag for follow-up.",
            "Buyer score moved from 65 → 50 after this call due to subsequent silence.",
          ],
        },
      },
      {
        id: "atlas-mtg-1",
        title: "Mutual action plan workshop",
        date: "Apr 17, 11:00 AM PT",
        duration: "45 min",
        isPast: true,
        attendees: ["Sarah Chen", "Priya Rao", "Ridha"],
        debrief: {
          sentiment: "Energised",
          summary: "Aligned on the technical evaluation window through May 8. Priya took ownership of the IT review checklist. Sarah agreed to bring procurement in by Apr 25.",
          transcriptExcerpt: "...okay, let's lock May 8 as the technical decision date. Priya you'll own the eval checklist, I'll get procurement aligned. Anything else we need on the table from your end?...",
          videoUrl: "#",
          nextSteps: [
            "Share the technical evaluation checklist",
            "Send mutual action plan recap email",
            "Schedule procurement intro",
          ],
          addyNotes: [
            "Sarah dropped a Linnworks reference — competitive evaluation is still open.",
            "Priya has bandwidth concerns — flagged a possible 1-week slip risk.",
          ],
        },
      },
    ],
  },
  {
    id: "global",
    company: "Global Solutions Ltd",
    dealName: "Strategic Partnership",
    stage: "Discovery",
    value: 850000,
    arr: "$850K ARR",
    closeDate: "Jun 12, 2026",
    status: "at-risk",
    statusLabel: "At Risk",
    champion: "Daniel Okafor",
    championRole: "Director, Ops",
    buyerScore: 45,
    sellerScore: 80,
    gap: -35,
    summary:
      "Critical gap detected from LinkedIn: Daniel Okafor changed jobs, so Global Solutions no longer has an active champion in the deal. Your effort is at 100%, theirs is at 0% — buyer ownership is gone. Recommend finding a replacement champion and opening a fresh thread with the new operations owner.",
    trend: [50, 52, 54, 56, 55, 52, 50, 48, 47, 46, 45],
    sellerTrend: [70, 72, 74, 76, 77, 78, 79, 80, 80, 80, 80],
    scoreEvents: [
      { delta: -16, label: "champion changed job" },
      { delta: -6, label: "CFO not looped in" },
      { delta: +4, label: "discovery momentum" },
    ],
    nudges: [
      {
        kind: "GAP DETECTED",
        title: "Daniel Okafor changed jobs",
        sub: "LinkedIn — former champion now VP Operations at Northline Systems",
        action: "Find replacement champion",
        executeLabel: "Run champion search",
        severity: "warn",
        evidence: {
          source: "LinkedIn",
          time: "Live enrichment",
          detail: "Daniel Okafor updated role to VP Operations at Northline Systems",
          proof: "The active champion left Global Solutions, so the deal has no confirmed internal owner.",
        },
        automation: {
          type: "replacement-champion-lookup",
          source: "LinkedIn",
          foundContact: {
            name: "Amara Nwosu",
            role: "Senior Director, Operations",
            company: "Global Solutions Ltd",
            email: "amara.nwosu@globalsolutionsltd.com",
            signal: "Owns operations transformation after Daniel Okafor's departure",
          },
          steps: [
            { label: "Detect job change", detail: "Daniel Okafor updated LinkedIn to Northline Systems" },
            { label: "Search account map", detail: "Operations leaders still at Global Solutions" },
            { label: "Found", detail: "Amara Nwosu — Senior Director, Operations" },
            { label: "Draft outreach", detail: "Transfer context and ask who owns the evaluation now" },
          ],
        },
      },
      {
        kind: "MISSING STAKEHOLDERS",
        title: "CFO not looped in",
        sub: "Global Solutions — finance review pending",
        action: "Draft Intro Request",
        severity: "warn",
      },
      {
        kind: "ECONOMIC BUYER NOT IDENTIFIED",
        title: "Let Nudge identify the finance buyer",
        sub: "Global Solutions — CFO absent from the deal path",
        action: "Let Nudge identify it for you",
        executeLabel: "Execute lookup",
        severity: "warn",
        automation: {
          type: "economic-buyer-lookup",
          source: "LinkedIn",
          foundContact: {
            name: "Helena Voss",
            role: "CFO",
            company: "Global Solutions Ltd",
            email: "helena.voss@globalsolutionsltd.com",
            signal: "Owns finance approval for enterprise partnerships",
          },
          steps: [
            { label: "Search LinkedIn", detail: "Finance leaders at Global Solutions" },
            { label: "Found", detail: "Helena Voss — CFO" },
            { label: "Enrich email", detail: "helena.voss@globalsolutionsltd.com" },
            { label: "Send contact email", detail: "ROI intro using Daniel's discovery context" },
          ],
        },
      },
    ],
    activity: [
      {
        time: "Apr 25, 10:02 AM",
        kind: "addy",
        actor: "Addy",
        title: "Detected silence pattern",
        body: "Daniel hasn't opened the proposal in 4 days.",
        tag: "ai",
      },
      {
        time: "Today, 9:18 AM",
        kind: "addy",
        actor: "Addy",
        title: "Detected champion job change",
        body: "LinkedIn shows Daniel Okafor moved to Northline Systems. Suggested finding a replacement champion at Global Solutions.",
        tag: "ai",
      },
      {
        time: "Apr 21, 3:30 PM",
        kind: "email",
        actor: "Ridha",
        title: "Sent updated proposal v3",
        body: "Included revised licensing tier and SLA addendum.",
        tag: "internal",
      },
    ],
    stakeholders: [
      { name: "Daniel Okafor", role: "Director, Ops", power: 3, support: 3, missing: false },
      { name: "Amara Nwosu", role: "Senior Director, Operations", power: 4, support: 2, missing: true },
      { name: "Helena Voss", role: "CFO", power: 5, support: 2, missing: true },
    ],
  },
  {
    id: "techstart",
    company: "TechStart Inc",
    dealName: "Mid-Market Expansion",
    stage: "Proposal",
    value: 125000,
    arr: "$125K ARR",
    closeDate: "May 18, 2026",
    status: "needs-attention",
    statusLabel: "Needs Attention",
    champion: "Jules Romero",
    championRole: "Head of Revenue",
    buyerScore: 62,
    sellerScore: 71,
    gap: -9,
    summary:
      "Buyer engagement is strong, but legal review has stalled twice. I drafted a redline summary to unblock and recommended a 15-min sync with their counsel.",
    trend: [55, 56, 58, 60, 62, 63, 63, 62, 62, 62, 62],
    sellerTrend: [60, 62, 64, 66, 68, 70, 71, 71, 71, 71, 71],
    scoreEvents: [
      { delta: -5, label: "legal silent 6d" },
      { delta: +6, label: "pricing aligned" },
      { delta: +4, label: "champion engaged" },
    ],
    nudges: [
      {
        kind: "BLOCKED",
        title: "Legal review stalled 6 days",
        sub: "TechStart — counsel response pending",
        action: "Send Redline Summary",
        severity: "warn",
      },
    ],
    activity: [
      {
        time: "Apr 23, 2:00 PM",
        kind: "meeting",
        actor: "You + Jules Romero",
        title: "Pricing alignment call",
        body: "Agreed on 2-year term with Q2 ramp.",
        tag: "milestone",
      },
      {
        time: "Apr 25, 10:18 AM",
        kind: "addy",
        actor: "Addy",
        title: "Flagged legal silence",
        body: "Counsel hasn't replied to redlines for 6 days. Drafted a redline summary to unblock.",
        tag: "ai",
      },
      {
        time: "Apr 21, 5:30 PM",
        kind: "email",
        actor: "Jules Romero",
        title: "Asked when redlines will land",
        body: "Wants the May 8 close to hold — flagged that legal hasn't responded.",
        tag: "buyer",
      },
    ],
    stakeholders: [
      { name: "Jules Romero", role: "Head of Revenue", power: 4, support: 5, missing: false },
      { name: "Aiden Park", role: "General Counsel", power: 3, support: 2, missing: false },
    ],
    meetings: [
      {
        id: "techstart-mtg-1",
        title: "Pricing alignment call",
        date: "Apr 23, 2:00 PM PT",
        duration: "30 min",
        isPast: true,
        attendees: ["Jules Romero", "Ridha"],
        goal: "Lock 2-year term and surface any remaining commercial blockers.",
        debrief: {
          sentiment: "Confident",
          summary: "Pricing aligned on 2-year term with Q2 ramp. Legal review is the only open item before May 8 close.",
          nextSteps: ["Send redline summary to Aiden Park", "Confirm legal response window by Apr 26"],
        },
      },
    ],
  },
  {
    id: "acme",
    company: "Acme Corporation",
    dealName: "Enterprise Platform Deal",
    stage: "Negotiation",
    value: 450000,
    arr: "$450K ARR",
    closeDate: "May 30, 2026",
    status: "healthy",
    statusLabel: "On Track",
    champion: "Rina Patel",
    championRole: "VP Engineering",
    buyerScore: 81,
    sellerScore: 85,
    gap: -4,
    summary:
      "Strong alignment across both sides. Procurement signed the security review yesterday. Recommend pushing for verbal commit by Friday.",
    trend: [60, 65, 70, 73, 76, 78, 79, 80, 80, 81, 81],
    sellerTrend: [70, 73, 76, 79, 81, 82, 83, 84, 85, 85, 85],
    scoreEvents: [
      { delta: +8, label: "security review cleared" },
      { delta: +5, label: "procurement aligned" },
      { delta: +3, label: "champion socializing" },
    ],
    nudges: [
      {
        kind: "OPPORTUNITY",
        title: "Push for verbal commit this week",
        sub: "Acme — momentum is high",
        action: "Draft Close Plan",
        severity: "info",
      },
    ],
    activity: [
      {
        time: "Apr 25, 4:11 PM",
        kind: "email",
        actor: "Rina Patel",
        title: "Confirmed security review passed",
        body: "Procurement is ready to move to redlines.",
        tag: "buyer",
      },
      {
        time: "Apr 24, 11:00 AM",
        kind: "meeting",
        actor: "You + Rina Patel + Marco Liu",
        title: "Close plan workshop",
        body: "Agreed on May 30 close target. Marco confirmed signing authority sits with him.",
        tag: "milestone",
      },
      {
        time: "Apr 22, 9:42 AM",
        kind: "email",
        actor: "Marco Liu",
        title: "Approved budget for FY26",
        body: "CFO signed off on $450K platform spend last week. Engineering owns the decision.",
        tag: "buyer",
      },
    ],
    stakeholders: [
      { name: "Rina Patel", role: "VP Engineering", power: 4, support: 5, missing: false },
      { name: "Marco Liu", role: "CTO", power: 5, support: 4, missing: false },
    ],
    meetings: [
      {
        id: "acme-mtg-1",
        title: "Close plan workshop",
        date: "Apr 24, 11:00 AM PT",
        duration: "45 min",
        isPast: true,
        attendees: ["Rina Patel", "Marco Liu", "Ridha"],
        goal: "Lock close date and confirm signing authority before redline cycle.",
        debrief: {
          sentiment: "Aligned and confident",
          summary: "Marco confirmed signing authority. May 30 close date agreed. Rina to drive procurement timeline.",
          nextSteps: ["Send mutual close plan by Apr 28", "Procurement kickoff Apr 30"],
        },
      },
      {
        id: "acme-mtg-2",
        title: "Verbal commit checkpoint",
        date: "May 2, 2:00 PM PT",
        duration: "20 min",
        isPast: false,
        attendees: ["Rina Patel", "Ridha"],
        goal: "Secure verbal commit on May 30 close date and confirm redline window.",
        intel: {
          pulse: "Rina is aligned; Marco has signing authority confirmed.",
          talkingPoints: ["Confirm verbal close date", "Walk through redline timeline", "Identify procurement owner"],
        },
      },
    ],
  },
  {
    id: "startupco",
    company: "StartupCo",
    dealName: "Mid-Market Quick Win",
    stage: "Qualification",
    value: 45000,
    arr: "$45K ARR",
    closeDate: "May 22, 2026",
    status: "needs-attention",
    statusLabel: "Needs Attention",
    champion: "Lin Bennett",
    championRole: "COO",
    buyerScore: 58,
    sellerScore: 74,
    gap: -16,
    summary:
      "Champion is engaged but no economic buyer identified. Recommend a discovery call with their CFO.",
    trend: [40, 45, 48, 52, 55, 56, 57, 58, 58, 58, 58],
    sellerTrend: [60, 64, 67, 70, 72, 73, 74, 74, 74, 74, 74],
    scoreEvents: [
      { delta: +5, label: "qualification call" },
      { delta: +3, label: "champion mapped pain" },
      { delta: -3, label: "CFO unidentified" },
    ],
    nudges: [
      {
        kind: "MISSING ECONOMIC BUYER",
        title: "No CFO contact yet",
        sub: "StartupCo — finance silent",
        action: "Let Nudge identify it for you",
        severity: "warn",
        executeLabel: "Execute lookup",
        automation: {
          type: "economic-buyer-lookup",
          source: "LinkedIn",
          foundContact: {
            name: "Marta Singh",
            role: "Finance Lead",
            company: "StartupCo",
            email: "marta.singh@startupco.com",
            signal: "Listed as finance owner for vendor approvals",
          },
          steps: [
            { label: "Search LinkedIn", detail: "Finance owner connected to Lin Bennett" },
            { label: "Found", detail: "Marta Singh — Finance Lead" },
            { label: "Enrich email", detail: "marta.singh@startupco.com" },
            { label: "Send contact email", detail: "Ask for 20-min budget validation call" },
          ],
        },
      },
    ],
    activity: [
      {
        time: "Apr 20, 1:15 PM",
        kind: "meeting",
        actor: "You + Lin Bennett",
        title: "Qualification call",
        body: "Mapped pain points to platform; asked for CFO intro.",
        tag: "milestone",
      },
      {
        time: "Apr 26, 8:45 AM",
        kind: "addy",
        actor: "Addy",
        title: "Identified finance owner",
        body: "Marta Singh found via LinkedIn — listed as finance owner for vendor approvals at StartupCo.",
        tag: "ai",
      },
      {
        time: "Apr 22, 4:30 PM",
        kind: "note",
        actor: "Ridha",
        title: "Lin can't sign",
        body: "Lin confirmed COO role doesn't carry budget authority. CFO conversation is required before any commit.",
        tag: "internal",
      },
    ],
    stakeholders: [
      { name: "Lin Bennett", role: "COO", power: 3, support: 4, missing: false },
      { name: "Marta Singh", role: "Finance Lead", power: 4, support: 2, missing: true },
    ],
    meetings: [
      {
        id: "startupco-mtg-1",
        title: "Qualification call",
        date: "Apr 20, 1:15 PM PT",
        duration: "30 min",
        isPast: true,
        attendees: ["Lin Bennett", "Ridha"],
        goal: "Map pain to product fit and identify the economic buyer path.",
        debrief: {
          sentiment: "Engaged but blocked",
          summary: "Lin sees the value but doesn't carry budget authority. Asked for a CFO intro — pending.",
          nextSteps: ["Identify finance owner (Addy ran lookup)", "Email Marta Singh with budget validation ask"],
        },
      },
    ],
  },

  // ── Closed Won — full demo path through every stage ───────────────────
  {
    id: "horizon",
    company: "Horizon Industries",
    dealName: "Multi-year Platform Expansion",
    stage: "Closed Won",
    value: 620000,
    arr: "$620K ARR",
    closeDate: "Apr 18, 2026",
    status: "healthy",
    statusLabel: "Closed Won",
    champion: "Maya Chen",
    championRole: "VP Revenue Operations",
    buyerScore: 96,
    sellerScore: 92,
    gap: 4,
    summary:
      "Multi-year platform license signed Apr 18. Buyer-led close — Maya brought CFO and CRO into pricing alignment two weeks early. Expansion conversation already booked for Q3.",
    trend: [40, 48, 56, 64, 72, 80, 86, 90, 93, 95, 96],
    sellerTrend: [45, 52, 60, 67, 74, 80, 85, 88, 90, 91, 92],
    scoreEvents: [
      { delta: +12, label: "approved final redlines" },
      { delta: +9, label: "CFO aligned on pricing" },
      { delta: +7, label: "Maya offered reference" },
    ],
    nudges: [
      {
        kind: "EXPANSION OPPORTUNITY",
        title: "Schedule QBR + expansion conversation",
        sub: "Horizon — Maya signaled appetite for additional users in Q3",
        action: "Draft QBR Agenda",
        severity: "info",
      },
      {
        kind: "CONTACT MENTIONED IN CALL",
        title: "Add expansion contact and reach out",
        sub: "Horizon — Maya mentioned Nina Patel during contract signing",
        action: "Add contact & reach out",
        executeLabel: "Execute outreach",
        severity: "info",
        automation: {
          type: "call-mentioned-expansion-contact",
          source: "Contract signing call + LinkedIn",
          foundContact: {
            name: "Nina Patel",
            role: "VP Sales Operations",
            company: "Horizon Industries",
            email: "nina.patel@horizonindustries.com",
            signal: "Mentioned by Maya as the Q3 expansion owner",
          },
          steps: [
            { label: "Detect mention", detail: "Maya named Nina during the contract call" },
            { label: "Search LinkedIn", detail: "Matched Nina Patel at Horizon Industries" },
            { label: "Add contact", detail: "Added VP Sales Operations to the account map" },
            { label: "Reach out", detail: "Draft expansion intro with Maya context" },
          ],
        },
      },
      {
        kind: "REFERENCE OPPORTUNITY",
        title: "Ask for a logo + case study",
        sub: "Horizon — Maya offered to co-author when contract closed",
        action: "Draft Reference Request",
        severity: "info",
      },
    ],
    activity: [
      { time: "Apr 18, 5:42 PM", kind: "meeting", actor: "You + Maya Chen", title: "Contract signed",                  body: "Maya signed the MSA on the call. Procurement countersigned by EOD.",                tag: "milestone" },
      { time: "Apr 18, 5:49 PM", kind: "addy",    actor: "Addy",           title: "Detected expansion contact",        body: "Maya mentioned Nina Patel as the Sales Ops owner for the Q3 expansion path. LinkedIn match found and email enriched.", tag: "ai" },
      { time: "Apr 14, 2:10 PM", kind: "email",   actor: "Maya Chen",      title: "Approved final redlines",            body: "Legal returned the MSA with two minor edits — accepted both.",                       tag: "buyer"     },
      { time: "Apr 10, 11:00 AM",kind: "meeting", actor: "Ridha + Horizon legal", title: "Redline walkthrough",          body: "Walked legal through SLA and indemnity clauses; resolved on the call.",              tag: "milestone" },
      { time: "Apr 4, 9:15 AM",  kind: "email",   actor: "Maya Chen",      title: "Approved proposal v2",               body: "CFO and CRO both signed off on the multi-year structure.",                           tag: "buyer"     },
      { time: "Mar 28, 3:30 PM", kind: "meeting", actor: "You + Maya + CFO",title: "Pricing alignment",                  body: "Aligned on multi-year discount and ramp schedule. CFO comfortable.",                  tag: "milestone" },
      { time: "Mar 18, 10:02 AM",kind: "addy",    actor: "Addy",           title: "Buyer score crossed 80",             body: "Strong momentum signal — recommended close-plan workshop. Triggered automation.",     tag: "ai"        },
      { time: "Mar 11, 1:00 PM", kind: "meeting", actor: "You + Maya Chen",title: "Solution review",                    body: "Demonstrated platform on Maya's data; covered objections live.",                      tag: "milestone" },
      { time: "Mar 4, 8:48 AM",  kind: "email",   actor: "Ridha",          title: "Sent initial proposal",              body: "v1 proposal with pricing options and three case studies.",                            tag: "internal"  },
      { time: "Feb 22, 11:30 AM",kind: "meeting", actor: "You + Maya Chen",title: "Discovery call",                     body: "Mapped Maya's revops priorities to the platform's strengths. Stage moved → Qualification.", tag: "milestone" },
      { time: "Feb 14, 4:00 PM", kind: "note",    actor: "Ridha",          title: "Inbound — Maya replied to outreach", body: "Maya responded to LinkedIn message; agreed to a discovery slot.",                     tag: "internal"  },
    ],
    stakeholders: [
      { name: "Maya Chen",   role: "VP Revenue Operations", power: 5, support: 5, missing: false },
      { name: "Theo Park",   role: "CFO",                    power: 5, support: 4, missing: false },
      { name: "Lena Volkov", role: "CRO",                    power: 5, support: 5, missing: false },
      { name: "Nina Patel",  role: "VP Sales Operations",    power: 4, support: 3, missing: false },
      { name: "Owen Wells",  role: "Procurement",            power: 3, support: 4, missing: false },
    ],
    meetings: [
      {
        id: "horizon-mtg-qbr",
        title: "First QBR — 60-day adoption review",
        date: "Jun 11, 10:00 AM PT",
        duration: "60 min",
        isPast: false,
        attendees: ["Maya Chen", "Theo Park", "Lena Volkov", "Ridha"],
        goal: "Lock in expansion conversation; surface 60-day adoption signals.",
        intel: {
          pulse: "Maya signaled Q3 expansion appetite during pricing alignment. Adoption is tracking 18% above plan.",
          risks: [
            "Theo (CFO) was sceptical on the pace assumption — bring the actual ramp data, not projections.",
            "Owen (Procurement) is not invited yet — confirm whether the expansion needs a fresh PO.",
          ],
          talkingPoints: [
            "Open with the 60-day adoption numbers — lead with the wins their team owns.",
            "Walk through Q3 expansion options (additional users, new business unit).",
            "Surface the case-study ask Maya offered during pricing — formalise it now.",
          ],
          docs: ["60-day adoption snapshot", "Q3 expansion options deck", "Reference program agreement (draft)"],
        },
      },
      {
        id: "horizon-mtg-sign",
        title: "Contract signing",
        date: "Apr 18, 5:42 PM PT",
        duration: "20 min",
        isPast: true,
        attendees: ["Maya Chen", "Owen Wells", "Ridha"],
        debrief: {
          sentiment: "Closed Won",
          summary: "Maya signed the MSA on the call. Procurement countersigned by EOD. Maya volunteered to be a reference, asked about timing for the Q3 expansion conversation, and mentioned Nina Patel as the Sales Ops owner.",
          transcriptExcerpt: "...alright, signing now — and yes, happy to be a reference, you've earned it. Let's plan the QBR for early June and start sketching what Q3 looks like. Nina Patel should be in that thread from our Sales Ops side...",
          videoUrl: "#",
          nextSteps: [
            "Send signed MSA to procurement and legal",
            "Schedule kickoff with implementation team",
            "Add Nina Patel to the account map",
            "Draft QBR agenda + Q3 expansion deck",
            "Open reference-program conversation",
          ],
          addyNotes: [
            "Maya's reference offer is the second one this quarter — strong tailwind.",
            "Nina Patel matched on LinkedIn and email enrichment completed.",
            "Owen flagged that an additional PO will be needed for any Q3 expansion.",
          ],
        },
      },
      {
        id: "horizon-mtg-pricing",
        title: "Pricing alignment",
        date: "Mar 28, 3:30 PM PT",
        duration: "45 min",
        isPast: true,
        attendees: ["Maya Chen", "Theo Park", "Ridha"],
        debrief: {
          sentiment: "Aligned",
          summary: "Walked Theo through the multi-year structure. CFO comfortable with ramp schedule. Maya committed to introducing Lena (CRO) for final sign-off.",
          transcriptExcerpt: "...the ramp makes this work for me — year one looks reasonable, year two we'll re-evaluate based on adoption. I'm comfortable. Let's get Lena on it...",
          videoUrl: "#",
          nextSteps: [
            "Send updated proposal v2 with ramp schedule",
            "Schedule intro with Lena Volkov (CRO)",
            "Prepare redline kickoff for legal",
          ],
          addyNotes: [
            "Theo's comfort with year-2 reassessment is a soft expansion hook — pin for QBR.",
          ],
        },
      },
    ],
  },
  {
    id: "northstar",
    company: "Northstar Analytics",
    dealName: "Enterprise Forecasting Rollout",
    stage: "Closed Lost",
    lostAtStage: "Proposal",
    value: 280000,
    arr: "$280K ARR",
    closeDate: "Apr 12, 2026",
    status: "at-risk",
    statusLabel: "Closed Lost",
    champion: "Evan Brooks",
    championRole: "VP Sales Ops",
    buyerScore: 34,
    sellerScore: 78,
    gap: -44,
    summary:
      "Closed lost Apr 12. Champion engagement stayed high, but Finance never validated the ROI model and procurement moved forward with an incumbent renewal.",
    trend: [58, 55, 51, 46, 43, 40, 38, 35, 34],
    sellerTrend: [62, 66, 70, 73, 76, 78, 78, 78, 78],
    scoreEvents: [
      { delta: -18, label: "finance declined ROI review" },
      { delta: -10, label: "timing concern raised" },
      { delta: -7, label: "incumbent shortlisted" },
    ],
    nudges: [
      {
        kind: "LOSS REVIEW",
        title: "Finance never validated ROI",
        sub: "Northstar — economic buyer stayed outside the process",
        action: "Log Loss Pattern",
        severity: "warn",
      },
    ],
    activity: [
      { time: "Apr 12, 10:18 AM", kind: "note", actor: "Ridha", title: "Marked closed lost", body: "Northstar renewed with incumbent after Finance declined to review the ROI model.", tag: "internal" },
      { time: "Apr 8, 2:40 PM", kind: "email", actor: "Evan Brooks", title: "Timing concern", body: "Evan said Finance wanted a lower-risk renewal path this quarter.", tag: "buyer" },
      { time: "Mar 29, 11:00 AM", kind: "meeting", actor: "You + Evan Brooks", title: "Forecasting workflow review", body: "Champion saw fit, but no economic buyer joined the review.", tag: "milestone" },
    ],
    stakeholders: [
      { name: "Evan Brooks", role: "VP Sales Ops", power: 3, support: 4, missing: false },
      { name: "Claire Nordin", role: "CFO", power: 5, support: 1, missing: true },
      { name: "Mina Patel", role: "Procurement", power: 3, support: 2, missing: false },
    ],
  },

  // ── Discovery stage stack (10 fresh deals) ─────────────────────────────
  // Reuses an inlined helper so the rest of the file stays scannable.
  ...[
    { id: "vector",    co: "Vector Robotics",      deal: "Pilot to Production",          v: 80000,  close: "Aug 15, 2026", status: "healthy",         label: "On Track",          champ: "Alex Chen",      role: "Head of Engineering", buyer: 65, seller: 72, line: "Discovery call complete; technical deep-dive scheduled." },
    { id: "aurora",    co: "Aurora Health",        deal: "Network Pilot",                v: 150000, close: "Sep 9, 2026",  status: "needs-attention", label: "Needs Attention",   champ: "Dana Iqbal",     role: "Director, Innovation", buyer: 52, seller: 70, line: "Champion engaged, but compliance team unaware. EB unidentified." },
    { id: "quantum",   co: "Quantum Pay",          deal: "Starter Tier",                 v: 45000,  close: "Jul 1, 2026",  status: "healthy",         label: "On Track",          champ: "Renee Lopez",    role: "Head of Product",      buyer: 60, seller: 64, line: "Initial scoping complete; pricing options sent." },
    { id: "bluefish",  co: "Bluefish Logistics",   deal: "Routing Engine",               v: 220000, close: "Oct 22, 2026", status: "healthy",         label: "On Track",          champ: "Hugo Maartens",  role: "VP Operations",        buyer: 68, seller: 73, line: "Data integration scoped. Awaiting platform demo follow-up." },
    { id: "northpoint",co: "Northpoint Foods",     deal: "Regional Rollout",             v: 90000,  close: "Aug 28, 2026", status: "healthy",         label: "On Track",          champ: "Isla Brennan",   role: "COO",                  buyer: 62, seller: 68, line: "Champion mapped pain. Scheduling cross-functional working session." },
    { id: "pacific",   co: "Pacific Steel",        deal: "Plant Modernization",          v: 130000, close: "Nov 14, 2026", status: "needs-attention", label: "Needs Attention",   champ: "Theo Hammond",   role: "VP Manufacturing",     buyer: 49, seller: 66, line: "Buyer goes quiet between calls. Need to surface decision-maker." },
    { id: "skyline",   co: "Skyline Media",        deal: "Content Ops",                  v: 60000,  close: "Jul 18, 2026", status: "healthy",         label: "On Track",          champ: "Ana Soto",       role: "Editor in Chief",      buyer: 70, seller: 74, line: "Strong fit. Champion is socializing internally." },
    { id: "verdant",   co: "Verdant AI",           deal: "Embedded Analytics",           v: 75000,  close: "Aug 5, 2026",  status: "healthy",         label: "On Track",          champ: "Niko Tanaka",    role: "Founder",              buyer: 66, seller: 70, line: "Early stage but founder-led decision; quick path possible." },
    { id: "ironbridge",co: "Ironbridge Capital",   deal: "Compliance Workflow",          v: 310000, close: "Dec 5, 2026",  status: "healthy",         label: "On Track",          champ: "Priscilla Adler",role: "Head of Compliance",   buyer: 64, seller: 71, line: "Large-fund interest. Procurement and legal are pre-aligned." },
    { id: "rooted",    co: "RootedCo",             deal: "Field Team Tooling",           v: 50000,  close: "Jul 25, 2026", status: "healthy",         label: "On Track",          champ: "Sam Okeke",      role: "Head of Field Ops",    buyer: 58, seller: 64, line: "Discovery scoped; budget conversation pending." },
  ].map((d) => ({
    id: d.id,
    company: d.co,
    dealName: d.deal,
    stage: "Discovery",
    value: d.v,
    arr: `$${Math.round(d.v / 1000)}K ARR`,
    closeDate: d.close,
    status: d.status,
    statusLabel: d.label,
    champion: d.champ,
    championRole: d.role,
    buyerScore: d.buyer,
    sellerScore: d.seller,
    gap: d.buyer - d.seller,
    summary: d.line,
    trend: [d.buyer - 14, d.buyer - 10, d.buyer - 7, d.buyer - 4, d.buyer - 2, d.buyer],
    sellerTrend: [d.seller - 12, d.seller - 8, d.seller - 5, d.seller - 3, d.seller - 1, d.seller],
    scoreEvents: d.status === "needs-attention"
      ? [
          { delta: -5, label: "stalled between calls" },
          { delta: +3, label: "champion engaged" },
          { delta: -2, label: "decision-maker unknown" },
        ]
      : [
          { delta: +5, label: "discovery momentum" },
          { delta: +3, label: "champion engaged" },
          { delta: +2, label: "fit identified" },
        ],
    nudges: [
      {
        kind: d.status === "needs-attention" ? "MISSING STAKEHOLDERS" : "OPPORTUNITY",
        title: d.status === "needs-attention" ? "Surface decision-maker" : "Schedule technical deep-dive",
        sub: `${d.co} — next step pending`,
        action: d.status === "needs-attention" ? "Draft Intro Request" : "Draft Email",
        severity: d.status === "needs-attention" ? "warn" : "info",
      },
    ],
    activity: [
      {
        time: "This week",
        kind: "meeting",
        actor: `You + ${d.champ}`,
        title: "Discovery call",
        body: d.line,
        tag: "milestone",
      },
    ],
    stakeholders: [
      { name: d.champ, role: d.role, power: 4, support: 4, missing: false },
    ],
  })),

  // ── Closed Lost stack — attributed to the stage they slipped at.
  // Powers the "Letter for Addy" pipeline funnel ("closed lost -1 = stage").
  ...[
    { id: "halcyon",     co: "Halcyon Pharma",     deal: "Compliance Suite",         v: 195000, lost: "Discovery",     close: "Mar 04, 2026", champ: "Iris Daoud",   role: "Director Quality",        buyer: 28, seller: 58, reason: "Pulled before scoping. Champion couldn't get a finance sponsor seated within their quarter window." },
    { id: "broadleaf",   co: "Broadleaf Energy",   deal: "Field Ops Pilot",          v: 110000, lost: "Discovery",     close: "Feb 18, 2026", champ: "Nate Carver",  role: "Ops Manager",             buyer: 22, seller: 54, reason: "Discovery never converted to a problem worth solving — buyer ran an internal alternative." },
    { id: "tessera",     co: "Tessera Labs",       deal: "Analytics Tier",           v: 140000, lost: "Qualification", close: "Mar 22, 2026", champ: "Mira Patel",   role: "Head of Data",            buyer: 36, seller: 62, reason: "Qualification revealed a hard procurement freeze. No path to budget this fiscal year." },
    { id: "lumen",       co: "Lumen Insurance",    deal: "Claims Modernization",     v: 320000, lost: "Qualification", close: "Apr 02, 2026", champ: "Owen Hsu",     role: "VP Claims",               buyer: 40, seller: 68, reason: "Champion left mid-qualification; backup never picked up the thread." },
    { id: "kestrel",     co: "Kestrel Media",      deal: "Workflow Rollout",         v: 175000, lost: "Proposal",      close: "Mar 29, 2026", champ: "Tess Romano",  role: "Director Editorial",      buyer: 44, seller: 74, reason: "Proposal opened twice then went silent. Finance reviewed and asked for a 50% cut we couldn't meet." },
    { id: "argonaut",    co: "Argonaut Shipping",  deal: "Route Optimization",       v: 260000, lost: "Negotiation",   close: "Apr 25, 2026", champ: "Lars Holm",    role: "VP Logistics",            buyer: 46, seller: 80, reason: "Lost in redlines. Legal pushed back on indemnification and the deal stalled past the buyer's go-live." },
    { id: "metric",      co: "Metric Health",      deal: "Patient Insights",         v: 90000,  lost: "Negotiation",   close: "May 02, 2026", champ: "Aanya Gill",   role: "VP Clinical Ops",         buyer: 42, seller: 76, reason: "Procurement ran a counter-quote. Incumbent matched price; champion couldn't justify the switch." },
  ].map((d) => ({
    id: d.id,
    company: d.co,
    dealName: d.deal,
    stage: "Closed Lost",
    lostAtStage: d.lost,
    value: d.v,
    arr: `$${Math.round(d.v / 1000)}K ARR`,
    closeDate: d.close,
    status: "at-risk",
    statusLabel: "Closed Lost",
    champion: d.champ,
    championRole: d.role,
    buyerScore: d.buyer,
    sellerScore: d.seller,
    gap: d.buyer - d.seller,
    summary: d.reason,
    trend: [d.buyer + 18, d.buyer + 14, d.buyer + 9, d.buyer + 5, d.buyer + 2, d.buyer],
    sellerTrend: [d.seller - 10, d.seller - 6, d.seller - 3, d.seller - 1, d.seller, d.seller],
    scoreEvents: [
      { delta: -12, label: `slipped at ${d.lost.toLowerCase()}` },
      { delta: -6,  label: "buyer disengaged" },
    ],
    nudges: [
      {
        kind: "LOSS REVIEW",
        title: `Lost at ${d.lost}`,
        sub: `${d.co} — ${d.reason}`,
        action: "Log Loss Pattern",
        severity: "warn",
      },
    ],
    activity: [
      { time: d.close, kind: "note", actor: "Ridha", title: "Marked closed lost", body: d.reason, tag: "internal" },
    ],
    stakeholders: [
      { name: d.champ, role: d.role, power: 3, support: 2, missing: false },
    ],
  })),
];

// Each nudge is written in the responsible agent's first-person voice.
// Scout observes, Drafter proposes, Forecaster assesses. The action is phrased
// as a question or offer — the agent is asking permission, not announcing.
const SEED_NUDGES_FEED = [
  {
    id: "n1",
    deal: "Atlas Logistics",
    dealId: "atlas",
    agentId: "scout",
    severity: "warn",
    title: "I noticed Sarah Chen reposted Linnworks this morning",
    body: "Our Atlas thread has been quiet for 72h while Sarah amplified a named competitor. If you want, Drafter can prepare a displacement note for you.",
    action: "Hand off to Drafter",
    time: "12 min ago",
  },
  {
    id: "n2",
    deal: "Global Solutions Ltd",
    dealId: "global",
    agentId: "scout",
    severity: "warn",
    title: "Daniel Okafor moved to Northline — I'm watching for a new champion",
    body: "I matched Amara Nwosu as the most likely replacement (Head of Ops, same org). Want Drafter to write an intro request?",
    action: "Draft intro to Amara",
    time: "1 h ago",
  },
  {
    id: "n3",
    deal: "Acme Corporation",
    dealId: "acme",
    agentId: "forecaster",
    severity: "good",
    title: "Acme's evidence supports moving to Commit",
    body: "Procurement cleared security · contracting meeting on the calendar. Buyer score is at 78. I'd recommend pushing for verbal commit by Friday — Drafter has a close-plan email ready.",
    action: "Review close plan",
    time: "3 h ago",
  },
  {
    id: "n4",
    deal: "TechStart Inc",
    dealId: "techstart",
    agentId: "drafter",
    severity: "warn",
    title: "I drafted a redline summary — counsel has been silent 6 days",
    body: "I pulled the open redlines into a one-pager to escalate to your deal owner. Want to review before I send?",
    action: "Review redline summary",
    time: "5 h ago",
  },
  {
    id: "n5",
    deal: "StartupCo",
    dealId: "startupco",
    agentId: "scout",
    severity: "info",
    title: "I think Marta Singh's CFO 'Dave' is the economic buyer",
    body: "From the Apr 18 Gong transcript, Marta mentioned looping in finance. The CFO at StartupCo is Dave Liang — want me to confirm with Marta before Drafter writes the intro?",
    action: "Confirm with Marta",
    time: "Yesterday",
  },
];

// ---------- Diagnose → prescribe mapping ----------
// For each deal id, surface the single most actionable problem inline:
//   what — concrete diagnostic, numeric where possible
//   why — impact in plain English
//   fix — drafted prescription (tied to the deal's first nudge action)
//   symptoms — chips with short symptom labels
// This is the model's job; each is hand-written so the language reads
// like a sales coach, not a system log.
const DEAL_DIAGNOSIS = {
  atlas: {
    severity: "warn",
    headline: "Champion reposted Linnworks",
    what: "Sarah Chen reposted Linnworks' warehouse automation launch while Atlas has been quiet for 72h.",
    why: "The champion is actively engaging with a named competitor while our buying thread is stalled. If we don't reframe against Linnworks now, Atlas may anchor on the competitor narrative before procurement.",
    fix: "Send Linnworks displacement note to Sarah Chen",
    fixMeta: "Drafted · competitor proof included",
    symptoms: [
      { tone: "warn", label: "Linnworks repost" },
      { tone: "warn", label: "72h silent" },
      { tone: "warn", label: "−33 pts gap" },
    ],
    committee: [
      { role: "Champion",  name: "Sarah Chen",   state: "warn",  signal: "Reposted Linnworks 2d ago" },
      { role: "Econ buyer", name: "James Park",  state: "amber", signal: "Silent 9d" },
      { role: "Technical", name: "Rina Volkov", state: "good",  signal: "Demo'd this week" },
    ],
    draft: {
      channel: "Email",
      to: "Sarah Chen, Atlas Corp",
      subject: "Quick context on the Linnworks launch",
      text: "Sarah — saw your repost on Linnworks' warehouse automation announcement this week. A few quick proof points on where our approach diverges for the migration window you flagged earlier:\n\n· No full rip-and-replace — we run alongside your existing WMS for the first 6 weeks.\n· Peak-load profile we benchmarked matches yours within 8% (Linnworks' published spec doesn't cover your SKU velocity).\n· Reference: Northline migrated in 6 weeks on a similar topology — happy to set up a 15min call with their VP Ops.\n\nWorth 20 minutes Wednesday to walk through this before you finalize the shortlist?",
    },
    outcome: "Sarah replied · 20min Wed booked · Linnworks objection addressed",
  },
  global: {
    severity: "warn",
    headline: "Champion changed jobs",
    what: "LinkedIn shows Daniel Okafor left Global Solutions for Northline Systems.",
    why: "The deal no longer has an active internal owner. If Amara Nwosu or another operations leader doesn't pick it up, the discovery momentum resets and the June close becomes unlikely.",
    fix: "Find and message Amara Nwosu",
    fixMeta: "LinkedIn match · replacement champion found",
    symptoms: [
      { tone: "warn", label: "Champion left" },
      { tone: "warn", label: "−35 pts gap" },
      { tone: "warn", label: "No owner" },
    ],
    committee: [
      { role: "Champion",  name: "Daniel Okafor", state: "warn",  signal: "Departed · joined Northline" },
      { role: "Backup",    name: "Amara Nwosu",   state: "amber", signal: "Identified · not yet engaged" },
      { role: "Econ buyer", name: "—",             state: "warn",  signal: "No CFO contact" },
    ],
    draft: {
      channel: "LinkedIn DM",
      to: "Amara Nwosu, Global Solutions",
      subject: null,
      text: "Hi Amara — saw you took over the Operations org at Global Solutions after Daniel Okafor moved on to Northline. We had been working with Daniel on the operations review and a procurement plan that was timed to your June close. Wanted to reach out directly given the transition.\n\nWorth a 20min intro on what we'd mapped, so you can decide whether it makes sense to pick up the thread or let it lapse? Happy to come to you on whatever channel works best.",
    },
    outcome: "Amara responded · open to 30min intro · Global re-engaged",
  },
  techstart: {
    severity: "amber",
    headline: "Legal stalled 6 days",
    what: "Legal review stalled 6 days — counsel hasn't replied to redlines.",
    why: "Pricing is settled, but legal silence is the only thing holding May 8 close. One follow-up usually unblocks this.",
    fix: "Send redline summary to Aiden Park",
    fixMeta: "Drafted · 2 paragraphs",
    symptoms: [
      { tone: "amber", label: "Legal 6d silent" },
      { tone: "info", label: "Pricing aligned" },
    ],
    committee: [
      { role: "Champion", name: "Aiden Park",   state: "good",  signal: "Aligned · pushing on legal" },
      { role: "Legal",    name: "Counsel team", state: "warn",  signal: "Silent 6d on redlines" },
      { role: "Econ buyer", name: "Priya Shah",  state: "good",  signal: "Pricing approved" },
    ],
    draft: {
      channel: "Email",
      to: "Aiden Park, TechStart",
      subject: "Quick redline summary — let's lock this by Thursday",
      text: "Aiden — pulling the open redline points into one short note since we're 6 days past the date we had targeted. Three items left, none material to commercials:\n\n1. Indemnification scope — we've narrowed to commercial-grade only (matches your MSA language with similar vendors).\n2. Data retention — 18 months → 24 months to align with your audit cadence.\n3. SLA carve-out for force majeure — standard language, attached.\n\nAll three are in the v3 redline. 15min sync Thursday to finalize so we hold the May 8 close?",
    },
    outcome: "Aiden confirmed · counsel redlines back Thursday · May 8 close held",
  },
  acme: {
    severity: "good",
    headline: "Push for verbal commit",
    what: "Strong alignment on both sides; security review cleared.",
    why: "Momentum is high. Deals at this stage that get a verbal commit within 7 days close 2.4× more often than those that don't.",
    fix: "Draft mutual close plan for Rina Patel",
    fixMeta: "Drafted · push for verbal commit by Fri",
    symptoms: [
      { tone: "good", label: "Security cleared" },
      { tone: "good", label: "+81% buyer" },
      { tone: "good", label: "Momentum high" },
    ],
    committee: [
      { role: "Champion",  name: "Rina Patel",   state: "good", signal: "Driving close plan" },
      { role: "Econ buyer", name: "Marcus Cole",  state: "good", signal: "Approved budget" },
      { role: "Technical", name: "Security team", state: "good", signal: "Cleared review" },
    ],
    draft: {
      channel: "Email",
      to: "Rina Patel, ACME",
      subject: "Mutual close plan · targeting verbal commit by Friday",
      text: "Rina — strong alignment this week and security review cleared. Wanted to put what we discussed on paper before we lose the momentum.\n\nProposed milestones:\n· Mon — exec sponsor (Marcus) sign-off on the commercial terms\n· Wed — procurement final review + redline returns\n· Fri — verbal commit; counter-signature target the following Tuesday\n\nAnything you'd adjust on your side? If this lands, I'll loop Marcus directly and we hold the Friday slot.",
    },
    outcome: "Marcus signed off · Friday verbal commit confirmed",
  },
  startupco: {
    severity: "amber",
    headline: "No economic buyer yet",
    what: "Champion engaged but no economic buyer identified.",
    why: "Lin can advocate but can't sign. Without a CFO conversation in the next 7 days, you're at risk of a nice-meeting-no-decision outcome.",
    fix: "Identify and email Marta Singh",
    fixMeta: "LinkedIn match · email enriched",
    symptoms: [
      { tone: "amber", label: "No EB" },
      { tone: "info", label: "Champion engaged" },
    ],
    committee: [
      { role: "Champion",  name: "Maya Lin",    state: "good", signal: "Driving the deal" },
      { role: "Econ buyer", name: "—",           state: "warn", signal: "Not yet identified" },
      { role: "Procurement", name: "Marta Singh", state: "amber", signal: "Surfaced via LinkedIn · not engaged" },
    ],
    draft: {
      channel: "Email",
      to: "Marta Singh, StartupCo Finance",
      subject: "Brief intro from Maya — finance prioritization for Q3",
      text: "Marta — Maya at StartupCo asked me to reach out directly given we're at the point where finance prioritization matters. Maya has been deep on the operations side with us; we'd want to make sure Q3 finance plans don't lock before this gets visibility.\n\nWorth a 20min conversation this week or next — happy to come to you. If a written summary lands better first, I can send our one-pager and we go from there.",
    },
    outcome: "Marta requested short call next week · finance loop opened",
  },
  horizon: {
    severity: "closed-won",
    headline: "Signed Apr 18 · QBR ahead",
    what: "Closed Won — multi-year, expansion-ready.",
    why: "Buyer-led close with CFO and CRO aligned. Maya offered to be a reference and mentioned Nina Patel as the Sales Ops expansion owner.",
    fix: "Add Nina Patel and reach out",
    fixMeta: "LinkedIn match · contact added",
    symptoms: [
      { tone: "closed-won", label: "Closed Won" },
      { tone: "good", label: "Reference offered" },
      { tone: "good", label: "Q3 expansion" },
    ],
  },
  northstar: {
    severity: "closed-lost",
    headline: "Lost to incumbent renewal",
    what: "Closed Lost — Finance never validated ROI and defaulted to a low-risk renewal.",
    why: "The champion liked the workflow, but the economic buyer stayed outside the process. Seller activity kept climbing while buyer confidence fell.",
    fix: "Log Finance validation as loss pattern",
    fixMeta: "Loss review · update playbook",
    symptoms: [
      { tone: "closed-lost", label: "Closed Lost" },
      { tone: "warn", label: "ROI unvalidated" },
      { tone: "warn", label: "CFO missing" },
    ],
  },
};

// ---------- Agent activity feed (right rail of Home) ----------
// Each entry is something Addy DID — not what the user should do. This
// surfaces the "system is alive and watching" feel.
const AGENT_FEED = [
  { time: "2m",  kind: "score",  deal: "Atlas Logistics",       text: "Buyer score dropped 4 pts after thread silence",         tone: "warn"  },
  { time: "8m",  kind: "draft",  deal: "Atlas Logistics",       text: "Drafted re-engagement email for Sarah Chen",             tone: "amber" },
  { time: "21m", kind: "signal", deal: "Global Solutions",      text: "Detected CFO mentioned in inbound reply",                tone: "info"  },
  { time: "44m", kind: "score",  deal: "Acme Corporation",      text: "Buyer score +2 — security review cleared",               tone: "good"  },
  { time: "1h",  kind: "draft",  deal: "TechStart Inc",         text: "Drafted redline summary to unblock counsel",             tone: "amber" },
  { time: "2h",  kind: "signal", deal: "Global Solutions",      text: "Proposal v3 still unopened (4 days)",                    tone: "warn"  },
  { time: "3h",  kind: "play",   deal: "—",                     text: "Playbook \"Re-engage cold champion\" matched 3 deals",   tone: "info"  },
  { time: "5h",  kind: "score",  deal: "StartupCo",             text: "Buyer score +3 after qualification call",                tone: "good"  },
];

// ---------- Daily score deltas (signal ticker tiles) ----------
// One tile per deal: today's buyer-score change. Lets the user scan
// what's moving without leaving Home.
const SIGNAL_DELTAS = {
  atlas:     { delta: -4, since: "Linnworks repost",     status: "at-risk" },
  global:    { delta: -7, since: "champion changed job", status: "at-risk" },
  techstart: { delta:  0, since: "legal silent",         status: "needs-attention" },
  acme:      { delta: +2, since: "security cleared",     status: "healthy" },
  startupco: { delta: +3, since: "qualification call",   status: "needs-attention" },
};

// ---------- Channel resolver mock layer (frontend-only) ----------
// The prototype has no real integrations or channel-history data, so the
// "Where to do it" recommendation reads from this isolated layer. Two
// pieces: tenant-level ACTIVE_CHANNELS (what is connected at all), and
// EXECUTION_CONTEXT (per-deal contact relationship + per-nudge action
// attributes). Resolver falls back to safe defaults if a deal is missing.
const ACTIVE_CHANNELS = {
  whatsapp: true,
  slack: true,
  linkedin: true,
  email: true,
  calendar: true,
  crm: true,
  phone: true,
};

const EXECUTION_CONTEXT = {
  atlas: {
    contacts: {
      "Sarah Chen": {
        role: "champion",
        relationshipStrength: "strong",
        lastUsedChannel: "whatsapp",
        channelFrequency: { whatsapp: "high", slack: "low", linkedin: "medium", email: "high" },
      },
      "Marcus Vela": {
        role: "economic_buyer",
        relationshipStrength: "weak",
        channelFrequency: { whatsapp: "none", slack: "none", linkedin: "low", email: "medium" },
      },
      "Priya Rao": {
        role: "technical_evaluator",
        relationshipStrength: "medium",
        lastUsedChannel: "slack",
        channelFrequency: { slack: "high", email: "medium", whatsapp: "none", linkedin: "low" },
      },
      "Devon Park": {
        role: "procurement",
        relationshipStrength: "weak",
        channelFrequency: { email: "low" },
      },
    },
    nudgeAttrs: [
      { contact: "Sarah Chen",  missingEvidence: "competitor_info", sensitivity: "high",   urgency: "high",   formality: "informal", actionType: "clarify"     },
      { contact: "Marcus Vela", missingEvidence: "decision_owner",  sensitivity: "medium", urgency: "high",   formality: "formal",   actionType: "escalate"    },
      { contact: "Priya Rao",   missingEvidence: "approval_path",   sensitivity: "low",    urgency: "medium", formality: "neutral",  actionType: "ask_for_info" },
    ],
    diagAttrs:    { contact: "Sarah Chen",  missingEvidence: "competitor_info", sensitivity: "high", urgency: "high", formality: "informal", actionType: "clarify" },
  },
  global: {
    contacts: {
      "Daniel Okafor": { role: "champion", relationshipStrength: "weak",    channelFrequency: { email: "low" } },
      "Amara Nwosu":   { role: "unknown",  relationshipStrength: "weak",    lastUsedChannel: "linkedin",
                         channelFrequency: { linkedin: "medium", email: "none" } },
    },
    nudgeAttrs: [
      { contact: "Amara Nwosu", missingEvidence: "stakeholder_map", sensitivity: "medium", urgency: "high", formality: "neutral", actionType: "follow_up" },
    ],
    diagAttrs:    { contact: "Amara Nwosu", missingEvidence: "stakeholder_map", sensitivity: "medium", urgency: "high", formality: "neutral", actionType: "follow_up" },
  },
  techstart: {
    contacts: {
      "Aiden Park": { role: "procurement", relationshipStrength: "medium", channelFrequency: { email: "high" } },
    },
    nudgeAttrs: [
      { contact: "Aiden Park", missingEvidence: "approval_path", sensitivity: "medium", urgency: "high", formality: "formal", actionType: "follow_up" },
    ],
    diagAttrs:    { contact: "Aiden Park", missingEvidence: "approval_path", sensitivity: "medium", urgency: "high", formality: "formal", actionType: "follow_up" },
  },
  acme: {
    contacts: {
      "Rina Patel": { role: "champion", relationshipStrength: "strong", lastUsedChannel: "email",
                      channelFrequency: { email: "high", calendar: "high", whatsapp: "low" } },
    },
    nudgeAttrs: [
      { contact: "Rina Patel", missingEvidence: "next_step", sensitivity: "low", urgency: "medium", formality: "neutral", actionType: "schedule" },
    ],
    diagAttrs:    { contact: "Rina Patel", missingEvidence: "next_step", sensitivity: "low", urgency: "medium", formality: "neutral", actionType: "schedule" },
  },
  startupco: {
    contacts: {
      "Lin Patel":    { role: "champion",        relationshipStrength: "medium",  channelFrequency: { email: "medium", whatsapp: "low" } },
      "Marta Singh":  { role: "economic_buyer",  relationshipStrength: "unknown", channelFrequency: { email: "none", linkedin: "low" } },
    },
    nudgeAttrs: [
      { contact: "Marta Singh", missingEvidence: "decision_owner", sensitivity: "medium", urgency: "high", formality: "formal", actionType: "escalate" },
    ],
    diagAttrs:    { contact: "Marta Singh", missingEvidence: "decision_owner", sensitivity: "medium", urgency: "high", formality: "formal", actionType: "escalate" },
  },
};

// ─── DEMO FRESHENER ─────────────────────────────────────────────────
// At runtime, prepend per-deal "live" activity to make the timeline
// feel like the deal is moving right now, no matter when the demo is
// opened. Also schedules a near-term meeting on each priority deal so
// the agenda always has something happening today/tomorrow. Original
// historical activity is preserved underneath as context.
//
// Exposed via `window.freshenDeals(deals)` — called from app.jsx during
// the initial setDeals() so the prototype boots in a "deal in motion"
// state every time.

function fmtRelativeTime(now, minutesAgo) {
  const past = new Date(now.getTime() - minutesAgo * 60000);
  if (minutesAgo < 60) return `${minutesAgo}m ago`;
  const hh = past.getHours();
  const mm = past.getMinutes();
  const ampm = hh < 12 ? "AM" : "PM";
  const h = hh % 12 || 12;
  const stamp = `${h}:${String(mm).padStart(2, "0")} ${ampm}`;
  if (minutesAgo < 12 * 60) return `Today, ${stamp}`;
  if (minutesAgo < 36 * 60) return `Yesterday, ${stamp}`;
  const days = Math.round(minutesAgo / 1440);
  return `${days}d ago`;
}

function fmtMeetingDate(now, daysAhead, hour, minute = 0) {
  const d = new Date(now);
  d.setDate(d.getDate() + daysAhead);
  d.setHours(hour, minute, 0, 0);
  const months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
  const h12 = d.getHours() % 12 || 12;
  const ampm = d.getHours() < 12 ? "AM" : "PM";
  const stamp = `${h12}:${String(d.getMinutes()).padStart(2,"0")} ${ampm} PT`;
  if (daysAhead === 0)  return `Today, ${stamp}`;
  if (daysAhead === 1)  return `Tomorrow, ${stamp}`;
  return `${months[d.getMonth()]} ${d.getDate()}, ${stamp}`;
}

// Per-deal live injections. Each entry has minutesAgo (computed at
// runtime) + the activity body. Newest first.
const LIVE_DEMO_ACTIVITY = {
  atlas: [
    { minutesAgo: 8,   kind: "addy",     actor: "Addy",         title: "Sarah Chen opened proposal v3",            body: "Third view this week — opened from her phone, 4 min on page 12 (pricing).", tag: "ai" },
    { minutesAgo: 42,  kind: "linkedin", actor: "Sarah Chen",   title: "Reposted Linnworks automation launch",     body: "Visible to her 4.2K network. Competitor signal — Linnworks displacement note drafted in AI Actions.", tag: "buyer" },
    { minutesAgo: 95,  kind: "calendar", actor: "Atlas Logistics", title: "Internal finance review booked",        body: "30 min on Sarah's calendar with Marcus Vela (CFO) — Thu 2:00 PM. You're not invited yet.", tag: "milestone" },
    { minutesAgo: 240, kind: "addy",     actor: "Addy",         title: "Champion change detected — Atlas",          body: "Sarah's LinkedIn title updated 2h ago: 'VP Operations → VP Operations & Procurement'. Procurement now in her remit.", tag: "ai" },
    { minutesAgo: 26 * 60, kind: "email", actor: "Sarah Chen",  title: "Out-of-office reply ended",                 body: "Came back from PTO this morning. Inbox cleared 47 messages in 90 min.", tag: "buyer" },
  ],
  global: [
    { minutesAgo: 15,  kind: "linkedin", actor: "Amara Nwosu",   title: "Accepted LinkedIn intro request",            body: "Replacement champion opened the door — 'Happy to chat. Daniel briefed me on the operations review before he left.'", tag: "buyer" },
    { minutesAgo: 78,  kind: "email",    actor: "Daniel Okafor", title: "Auto-reply from old Global address",         body: "'I'm no longer at Global Solutions. For the operations evaluation please reach Amara Nwosu (amara.nwosu@globalsolutionsltd.com).'", tag: "internal" },
    { minutesAgo: 320, kind: "addy",     actor: "Addy",          title: "Confirmed Helena Voss as CFO via LinkedIn",  body: "Finance owner for enterprise partnerships. Email enriched. Drafted ROI intro using Daniel's discovery context — review in AI Actions.", tag: "ai" },
    { minutesAgo: 22 * 60, kind: "note", actor: "Ridha",         title: "Logged champion-change risk",                body: "Daniel left for Northline. June close at risk unless Amara picks up the thread this week.", tag: "internal" },
  ],
  techstart: [
    { minutesAgo: 4,   kind: "addy",     actor: "Addy",         title: "Legal review just paused",                  body: "Maya's legal team flagged data-residency. Drafted a one-pager rebuttal — review in AI Actions.", tag: "ai" },
    { minutesAgo: 53,  kind: "email",    actor: "Maya Tanaka",  title: "Asked for an EU data-residency clause",     body: "'Can you confirm the EU-hosted region is GA before we sign?' — needs a yes by Friday.", tag: "buyer" },
    { minutesAgo: 180, kind: "calendar", actor: "TechStart",    title: "Security review scheduled",                 body: "60 min with Maya + security lead — Wednesday 10:00 AM.", tag: "milestone" },
    { minutesAgo: 28 * 60, kind: "note", actor: "Ridha",        title: "Logged the legal blocker",                  body: "Flagging EU residency as the only open item. Maya is otherwise warm.", tag: "internal" },
  ],
  acme: [
    { minutesAgo: 22,  kind: "email",    actor: "Jordan Park",  title: "Signed the MSA",                            body: "Counter-signed and returned. Order form is next — sent for procurement review.", tag: "milestone" },
    { minutesAgo: 110, kind: "linkedin", actor: "Jordan Park",  title: "Updated title to 'VP Customer Ops'",        body: "Promotion. Expanded scope = more pipeline next quarter.", tag: "buyer" },
    { minutesAgo: 300, kind: "addy",     actor: "Addy",         title: "Procurement open — no champion paired",     body: "Order form sits in procurement queue. No internal champion CC'd. Recommend a nudge.", tag: "ai" },
  ],
  startupco: [
    { minutesAgo: 18,  kind: "calendar", actor: "Tomás Albers", title: "Declined the Thursday session",            body: "'Need to push — board prep this week.' Re-proposed slot for next Tue. No reply yet.", tag: "buyer" },
    { minutesAgo: 165, kind: "addy",     actor: "Addy",         title: "Deal cooled — 5d since last buyer touch",   body: "Tomás stopped replying after the board update. Sequence resume drafted.", tag: "ai" },
    { minutesAgo: 24 * 60, kind: "email", actor: "Tomás Albers", title: "Asked for case studies in their sector",    body: "Wants 2-3 fintech examples. Marketing has 4 ready — pulled the relevant ones.", tag: "buyer" },
  ],
};

// Near-term meetings injected on top of the existing meetings array so
// the agenda always has something soon.
const LIVE_DEMO_MEETINGS = {
  atlas: {
    id: "atlas-mtg-live",
    title: "Re-engage Sarah · 1:1",
    daysAhead: 0, hour: 15, minute: 30,
    duration: "30 min",
    attendees: ["Sarah Chen", "Ridha"],
    goal: "Close the loop on the Linnworks signal and surface the CFO directly.",
    intel: {
      pulse: "Sarah opened proposal v3 this morning + reposted competitor content. She's evaluating.",
      risks: [
        "She declined the prior Wed slot — engagement is fragile.",
        "Marcus Vela (CFO) on her internal review but never met us.",
        "Linnworks demo likely happens this week.",
      ],
      talkingPoints: [
        "Open warm — congratulate the new 'Procurement' remit (LinkedIn signal).",
        "Don't mention Linnworks first. Wait for her to bring it up; if she doesn't, surface as a casual 'who else are you looking at?'.",
        "Ask directly: 'Should Marcus join the next call?'",
        "Propose a joint slot with Marcus before Friday.",
      ],
      docs: ["Proposal v3", "Atlas — Linnworks battlecard", "CFO-1:1 briefing brief"],
    },
  },
  global: {
    id: "global-mtg-live",
    title: "Diego · pricing walk-through",
    daysAhead: 1, hour: 11, minute: 0,
    duration: "45 min",
    attendees: ["Diego Ramos", "Marisol Vidal", "Ridha"],
    goal: "Hand Diego the numbers he asked for and bring Marisol into the deal.",
    intel: {
      pulse: "Diego is building the business case internally. Marisol just forwarded to CTO.",
      risks: [
        "CTO not yet in any meeting — could change the technical scope.",
        "POC ends in 6 days; need clarity on success criteria before we walk in.",
      ],
      talkingPoints: [
        "Lead with the Q3 ROI numbers Diego asked for in Slack.",
        "Probe Marisol on the CTO's concerns — likely integration.",
        "Confirm POC success metric in writing by EOD.",
      ],
      docs: ["Pricing — Global v2", "POC scope memo", "Q3 ROI deck"],
    },
  },
  techstart: {
    id: "techstart-mtg-live",
    title: "EU data-residency — fast answer",
    daysAhead: 0, hour: 17, minute: 0,
    duration: "20 min",
    attendees: ["Maya Tanaka", "Ridha"],
    goal: "Confirm EU region availability + unblock legal review.",
    intel: {
      pulse: "Legal paused this morning over data residency. Drafted rebuttal one-pager.",
      risks: [
        "If EU GA date slips, Maya's legal will push to Q4.",
        "Security review on Wed depends on a yes here.",
      ],
      talkingPoints: [
        "Lead with the GA date in writing. Don't soften.",
        "Offer the security review on Wed as the validation step.",
        "Ask: 'What else is on legal's list?'",
      ],
      docs: ["EU residency one-pager", "Security FAQ v2"],
    },
  },
  startupco: {
    id: "startupco-mtg-live",
    title: "Re-prompt Tomás · short sync",
    daysAhead: 2, hour: 10, minute: 15,
    duration: "15 min",
    attendees: ["Tomás Albers", "Ridha"],
    goal: "Restart momentum after the board-prep pause and confirm sector case studies landed.",
    intel: {
      pulse: "Declined Thursday, no answer on Tuesday slot. Asked for fintech case studies a week ago.",
      risks: [
        "Board pre-read may have changed the prioritization.",
        "Silence is the signal — 5d since last reply.",
      ],
      talkingPoints: [
        "Open with the 3 fintech case studies attached — don't bury the lead.",
        "Ask 'What changed in the last board cycle?' before reselling.",
        "Re-propose Tuesday with a single concrete agenda.",
      ],
      docs: ["Fintech case study pack", "Board context one-pager"],
    },
  },
};

function freshenDeals(deals, now = new Date()) {
  return deals.map((d) => {
    const inject = LIVE_DEMO_ACTIVITY[d.id] || [];
    const fresh = inject.map((a) => {
      const { minutesAgo, ...rest } = a;
      return { ...rest, time: fmtRelativeTime(now, minutesAgo) };
    });
    const meetingSpec = LIVE_DEMO_MEETINGS[d.id];
    const freshMeeting = meetingSpec
      ? {
          id: meetingSpec.id,
          title: meetingSpec.title,
          date: fmtMeetingDate(now, meetingSpec.daysAhead, meetingSpec.hour, meetingSpec.minute),
          duration: meetingSpec.duration,
          isPast: false,
          attendees: meetingSpec.attendees,
          goal: meetingSpec.goal,
          intel: meetingSpec.intel,
        }
      : null;
    return {
      ...d,
      activity: [...fresh, ...(d.activity || [])],
      meetings: freshMeeting
        ? [freshMeeting, ...(d.meetings || [])]
        : (d.meetings || undefined),
    };
  });
}

window.SEED_DEALS = SEED_DEALS;
window.SEED_NUDGES_FEED = SEED_NUDGES_FEED;
window.DEAL_DIAGNOSIS = DEAL_DIAGNOSIS;
window.AGENT_FEED = AGENT_FEED;
window.SIGNAL_DELTAS = SIGNAL_DELTAS;
window.ACTIVE_CHANNELS = ACTIVE_CHANNELS;
window.freshenDeals = freshenDeals;
window.EXECUTION_CONTEXT = EXECUTION_CONTEXT;
