// kova/data.jsx — frontend fixtures
// ----------------------------------------------------------------
// Frontend-only mock data. No backend, no API contract. When the
// real Worker API ships in a later phase, this file will be replaced
// by typed services from `lib/api/*`. Until then, the shape here is
// the *contract* — any UI built against this should keep working
// when the swap happens.
// ----------------------------------------------------------------

const CANONICAL_WORKFLOW = ['Queued', 'Context built', 'Agent ran', 'Verified', 'Awaiting approval', 'Execute · CONNECT', 'Outcome tracked'];

const baseChain = (cosignName, cosignRole) => ([
  { who: `${cosignName} · ${cosignRole}`, meta: 'Drafted recommendation · 9:02',   state: 'done' },
  { who: 'Auto · evidence sweep',         meta: '3 of 3 claims sourced · 9:04',     state: 'done' },
  { who: 'You · CEO',                     meta: 'Awaiting sign · ⌘⏎ to approve',    state: 'now' },
  { who: 'Logistics · execution',         meta: 'Will queue manifest on approval',  state: 'pending' },
]);

const baseWorkflow = (timesArr) => CANONICAL_WORKFLOW.map((label, i) => ({
  label,
  meta:  ['workflow.start', '128 KB · 4 sources', 'agent · v2.1', '3 / 3 claims sourced',
          'CEO · ⌘⏎ to sign', 'transfer.manifest', 'curator records'][i],
  time:  timesArr[i] || '—',
  state: i < 4 ? 'done' : i === 4 ? 'now' : 'pending',
}));

const SEED_DECISIONS = [
  {
    id: 'rcp-44c9',
    mod: 'orbit',
    priority: 'P1',
    impact: 'money',
    stamp: 'Verified · Orbit daily brief',
    status: 'pending', statusLabel: 'Pending CEO sign',
    runId: 'rcp-44c9', runVersion: 'v3', runWhen: '2 min ago',
    title: 'Transfer 38 SKUs Mumbai → Delhi to recover ₹14.2 L',
    reasoning: 'Delhi outperformed forecast 14 days running on solitaire bands; Mumbai’s same-cohort velocity slid 22 %. Transfer beats reprice on margin retained and preserves the catalogue.',
    stats: [
      { label: 'Unlock',     value: '₹14.2 L' },
      { label: 'SKUs',       value: '38' },
      { label: 'Median age', value: '214 d' },
      { label: 'Margin Δ',   value: '+ 6.4 %', color: 'success' },
    ],
    confidence: 3, confidenceLabel: 'High',
    cosign: 'Priya · Merch',
    chain: baseChain('Priya', 'Merch lead'),
    workflow: baseWorkflow(['09:42:01', '09:42:02', '09:42:09', '09:42:11', 'now', '—', '—']),
    claims: [
      { text: 'Delhi demand outperforming for solitaire bands.',           source: 'sales.read',                 receipt: 'rcp-44c9 / claim 1' },
      { text: 'Median age 214 d exceeds 180-day deadstock floor.',         source: 'inventory.read',             receipt: 'rcp-44c9 / claim 2' },
      { text: 'Delhi sell-price within 4 % of catalogue — no reprice.',    source: 'price.read · deterministic', receipt: 'rcp-44c9 / claim 3' },
    ],
    receipts: [
      { tool: 'sql.query',       scope: 'sales.read',     id: 'tool-receipt-882' },
      { tool: 'sql.query',       scope: 'inventory.read', id: 'tool-receipt-883' },
      { tool: 'price.calculate', scope: 'deterministic',  id: 'tool-receipt-884' },
      { tool: 'wiki.lookup',     scope: 'wiki.read',      id: 'tool-receipt-885' },
    ],
    math: [
      { expr: 'delhi_velocity_14d - forecast_14d',  value: '+ 22.3 %' },
      { expr: 'mumbai_velocity_14d - forecast_14d', value: '− 22.1 %' },
      { expr: 'unlock = Σ(sku_value × age_weight)', value: '₹14,21,800' },
      { expr: 'margin_delta = transfer − reprice',  value: '+ 6.4 %' },
    ],
  },
  {
    id: 'rcp-44ca',
    mod: 'vault',
    priority: 'P1',
    impact: 'money',
    stamp: 'Verified · Vault deadstock scan',
    status: 'pending', statusLabel: 'Co-sign · Inventory · then CEO',
    runId: 'rcp-44ca', runVersion: 'v17', runWhen: '11 min ago',
    title: 'Reprice 6 Bengaluru SKUs · −8 % unlocks ₹2.1 L',
    reasoning: 'These six are 198–241 days aged in a cooling cohort. Reprice cheaper than hold; transfer not viable given Bengaluru-only demand pattern.',
    stats: [
      { label: 'Unlock',   value: '₹2.1 L' },
      { label: 'SKUs',     value: '6' },
      { label: 'Reprice',  value: '−8 %' },
      { label: 'Margin Δ', value: '− 1.2 %', color: 'danger' },
    ],
    confidence: 3, confidenceLabel: 'High',
    cosign: 'Asha · Inventory',
    chain: [
      { who: 'Asha · Inventory mgr',  meta: 'Drafted reprice · 9:11', state: 'done' },
      { who: 'Auto · evidence sweep', meta: '3 / 3 claims sourced',   state: 'done' },
      { who: 'You · CEO',             meta: 'Awaiting sign',          state: 'now' },
      { who: 'PRICE engine · execute', meta: 'Apply to 6 SKUs',       state: 'pending' },
    ],
    workflow: baseWorkflow(['09:11:01', '09:11:02', '09:11:08', '09:11:10', 'now', '—', '—']),
    claims: [
      { text: 'Bengaluru cohort velocity has cooled 31 % over 30 days.', source: 'sales.read',       receipt: 'rcp-44ca / claim 1' },
      { text: 'Transfer cost > reprice margin loss for these SKUs.',     source: 'price.calculate',  receipt: 'rcp-44ca / claim 2' },
      { text: 'Median age 219 d · within deadstock policy.',             source: 'inventory.read',   receipt: 'rcp-44ca / claim 3' },
    ],
    receipts: [
      { tool: 'sql.query',       scope: 'sales.read',     id: 'tool-receipt-886' },
      { tool: 'price.calculate', scope: 'deterministic',  id: 'tool-receipt-887' },
    ],
    math: [
      { expr: 'reprice_unlock = Σ(reprice × age_factor)', value: '₹2,12,400' },
      { expr: 'transfer_cost_estimate',                   value: '₹38,800' },
      { expr: 'margin_loss_at_-8%',                       value: '− 1.2 %' },
    ],
  },
  {
    id: 'rcp-44cb',
    mod: 'price',
    priority: 'P0',
    impact: 'rate',
    stamp: 'Verified · Price engine · explained',
    status: 'pending', statusLabel: 'Awaiting CEO ceiling',
    runId: 'rcp-44cb', runVersion: 'v1', runWhen: '4 min ago',
    title: 'Approve gold rate update · 24K ₹78,420 → ₹79,520 / 10 g',
    reasoning: 'Spot moved +1.4 % overnight. PRICE engine calculated downstream impact on 412 SKUs; agent explains. Within CEO ceiling of ±2 % daily.',
    stats: [
      { label: 'Rate Δ',     value: '+ 1.4 %' },
      { label: 'SKUs',       value: '412' },
      { label: 'Margin Δ',   value: '+ 0.3 %', color: 'success' },
      { label: 'Ceiling',    value: 'within' },
    ],
    confidence: 4, confidenceLabel: 'Verified',
    cosign: 'Karan · Pricing',
    chain: [
      { who: 'Karan · Pricing lead',  meta: 'Posted update from market feed', state: 'done' },
      { who: 'Auto · engine verify',  meta: 'Within CEO ceiling',             state: 'done' },
      { who: 'You · CEO',             meta: 'Awaiting sign',                  state: 'now' },
      { who: 'PRICE engine · apply',  meta: 'Cascade to 412 SKUs',           state: 'pending' },
    ],
    workflow: baseWorkflow(['09:38:01', '09:38:01', '09:38:03', '09:38:04', 'now', '—', '—']),
    claims: [
      { text: 'Spot rate moved +1.4 % between 17:00 IST yesterday and 09:00 today.', source: 'rates.feed', receipt: 'rcp-44cb / claim 1' },
      { text: 'Cascade leaves all 412 SKUs within margin policy.',                   source: 'price.calculate',  receipt: 'rcp-44cb / claim 2' },
    ],
    receipts: [
      { tool: 'rates.fetch',     scope: 'feed.read',     id: 'tool-receipt-888' },
      { tool: 'price.calculate', scope: 'deterministic', id: 'tool-receipt-889' },
    ],
    math: [
      { expr: 'rate_delta = (new - old) / old',     value: '+ 1.40 %' },
      { expr: 'margin_after_cascade · weighted avg', value: '+ 0.3 %' },
      { expr: 'ceiling_check = abs(delta) < 0.02',  value: 'true' },
    ],
  },
  {
    id: 'rcp-44cc',
    mod: 'kraft',
    priority: 'P2',
    impact: 'launch',
    stamp: 'Verified · Design packet ready',
    status: 'pending', statusLabel: 'Awaiting CEO sign',
    runId: 'rcp-44cc', runVersion: 'v2', runWhen: '1 h ago',
    title: 'Sign off CAD-117 · custom necklace · launch pack',
    reasoning: 'Designer submitted final CAD with BOM; verified against brief constraints (margin floor, vendor capacity, lead time). Ready to ship to launch.',
    stats: [
      { label: 'Brief ref', value: 'kraft-1117' },
      { label: 'Margin',    value: '+ 38 %', color: 'success' },
      { label: 'Lead time', value: '14 d' },
      { label: 'BOM',       value: '₹62,400' },
    ],
    confidence: 4, confidenceLabel: 'Verified',
    cosign: 'Vikram · Designer',
    chain: [
      { who: 'Vikram · Senior designer', meta: 'Submitted CAD + BOM · 08:30', state: 'done' },
      { who: 'Auto · constraint check',  meta: 'Margin floor · vendor · time', state: 'done' },
      { who: 'You · CEO',                meta: 'Awaiting sign-off',           state: 'now' },
      { who: 'Manufacturing · queue',    meta: 'Vendor packet on approval',   state: 'pending' },
    ],
    workflow: baseWorkflow(['08:30:01', '08:30:02', '08:30:18', '08:30:21', 'now', '—', '—']),
    claims: [
      { text: 'Design within brief margin floor of 32 %.',           source: 'kraft.calculate', receipt: 'rcp-44cc / claim 1' },
      { text: 'Vendor capacity confirmed within lead time.',         source: 'connect.vendor',  receipt: 'rcp-44cc / claim 2' },
      { text: 'BOM verified against latest metal + stone rates.',    source: 'price.read',      receipt: 'rcp-44cc / claim 3' },
    ],
    receipts: [
      { tool: 'kraft.bom',       scope: 'design.read',    id: 'tool-receipt-890' },
      { tool: 'connect.vendor',  scope: 'partner.read',   id: 'tool-receipt-891' },
      { tool: 'price.read',      scope: 'deterministic',  id: 'tool-receipt-892' },
    ],
    math: [
      { expr: 'margin = (price − cost) / price', value: '38.1 %' },
      { expr: 'lead_time_days',                  value: '14' },
      { expr: 'bom_total',                       value: '₹62,400' },
    ],
    // KRAFT decisions carry the launch-pack design payload the CEO needs
    // to actually see what they're signing off. See architecture §8.5
    // and docs/design/KRAFT_CHAT_RATIONALE.md §3.
    designerName: 'Vikram',
    sessionId: 's-bridal-haram',
    designs: [
      { id: 'd-91ad-1', tag: 'Peacock medallion · 22k · mango drops',
        hue: 38, version: 2, parentDesignId: 'd-91a3-1', starred: true,
        material: { metal: '22k yellow gold', finish: 'high polish', weightG: 42 },
        stones:   { primary: 'Kemp ruby · cabochon', count: 7, totalCarat: 4.2, setting: 'kundan-set' },
        bomShare: '₹38,400', leadTimeDays: 14,
        mfg: { status: 'green', note: 'Closed-back jadau verified · prong gauge ≥ 0.9 mm.' },
        promptSummary: 'Heritage-inspired custom necklace · peacock motif · mango drops along chain · refined from rcp-91a3.' },
      { id: 'd-90c1-3', tag: 'Bar-set trio · 5.4 g',
        hue: 46, version: 1, starred: true,
        material: { metal: '18k yellow gold', finish: 'matte', weightG: 5.4 },
        stones:   { primary: 'Round-brilliant diamond', count: 3, totalCarat: 0.18, setting: 'bar-set' },
        bomShare: '₹14,600', leadTimeDays: 9,
        mfg: { status: 'green', note: 'Standard setting · vendor template available.' },
        promptSummary: 'Light daily-wear pendant · 18k · diamond-set · under 6 g.' },
      { id: 'd-8f12-1', tag: 'Signet · oval face · milgrain edge',
        hue: 42, version: 1, starred: true,
        material: { metal: '22k yellow gold', finish: 'high polish + matte centre', weightG: 18.4 },
        stones:   null,
        bomShare: '₹9,400', leadTimeDays: 12,
        mfg: { status: 'amber', note: 'Milgrain edge needs hand-finish — confirm artisan availability.' },
        promptSummary: 'Men\'s signet band · 22k comfort-fit · monogram-ready · oval face.' },
    ],
    comments: [
      { id: 'c-1', who: 'Vikram · Designer', at: '08:31', designId: null,
        text: 'Submitted 3 starred directions from the heritage-inspired custom necklace session. The peacock medallion is the v2 refinement with the mango drops you asked for last week.' },
      { id: 'c-2', who: 'Vikram · Designer', at: '08:33', designId: 'd-91ad-1',
        text: 'Peacock medallion: I went with 7 kemp ruby cabochons (4.2 ct total) — heavier than your v1 brief but it carries the centre better. Happy to rework if it pushes BOM over.' },
      { id: 'c-3', who: 'Vikram · Designer', at: '08:35', designId: 'd-8f12-1',
        text: 'Signet: amber on manufacturability — milgrain edge is hand-finish, lead time +2 d if our usual artisan is booked. Worth flagging to Hari before sign-off.' },
    ],
  },
  // approved history items for the "Approved" tab
  {
    id: 'rcp-44b8',
    mod: 'kraft',
    status: 'approved', statusLabel: 'Signed',
    runId: 'rcp-44b8', runVersion: 'v1', runWhen: 'Yesterday',
    title: 'Sign off CAD-114 · diamond eternity · launch pack',
    reasoning: 'Standard launch sign-off · within all constraints.',
    stats: [
      { label: 'Margin',    value: '+ 36 %', color: 'success' },
      { label: 'BOM',       value: '₹84,200' },
      { label: 'Lead time', value: '18 d' },
      { label: 'SKUs',      value: '1' },
    ],
    confidence: 4, confidenceLabel: 'Verified',
    cosign: 'Vikram · Designer',
    chain: [
      { who: 'Vikram · Senior designer',  meta: 'Submitted · Tue', state: 'done' },
      { who: 'Auto · constraint check',   meta: '3 / 3 sourced',    state: 'done' },
      { who: 'You · CEO',                 meta: 'Signed · 16:42',   state: 'done' },
      { who: 'Manufacturing · queued',    meta: 'Sent · 16:44',     state: 'done' },
    ],
    workflow: ['Queued', 'Context built', 'Agent ran', 'Verified', 'Approved', 'Executed', 'Outcome tracked'].map((l, i) => ({
      label: l, meta: '', time: ['Tue 09:01','Tue 09:01','Tue 09:18','Tue 09:21','Tue 16:42','Tue 16:44','Wed 11:00'][i], state: 'done',
    })),
  },
  {
    id: 'rcp-44a2',
    mod: 'vault',
    status: 'approved', statusLabel: 'Executed',
    runId: 'rcp-44a2', runVersion: 'v2', runWhen: '2 d ago',
    title: 'Transfer Pune → Mumbai · 14 SKUs · unlocked ₹4.8 L',
    reasoning: 'Pune cohort cooled; Mumbai absorbed the supply within 2 days.',
    stats: [
      { label: 'Unlocked', value: '₹4.8 L', color: 'success' },
      { label: 'SKUs',     value: '14' },
      { label: 'Days',     value: '2 d' },
      { label: 'Margin Δ', value: '+ 4.1 %', color: 'success' },
    ],
    confidence: 4, confidenceLabel: 'Verified',
    cosign: 'Asha · Inventory',
    chain: [
      { who: 'Asha · Inventory mgr', meta: 'Drafted', state: 'done' },
      { who: 'Auto · evidence',      meta: 'Sourced', state: 'done' },
      { who: 'You · CEO',            meta: 'Signed',  state: 'done' },
      { who: 'Logistics',            meta: 'Executed', state: 'done' },
    ],
    workflow: ['Queued', 'Context built', 'Agent ran', 'Verified', 'Approved', 'Executed', 'Outcome tracked'].map((l, i) => ({
      label: l, meta: '', time: 'Mon', state: 'done',
    })),
  },
  // a rejected one
  {
    id: 'rcp-44a0',
    mod: 'orbit',
    status: 'rejected', statusLabel: 'Returned · revise',
    runId: 'rcp-44a0', runVersion: 'v2', runWhen: '2 d ago',
    title: 'Push promotional bundle for ₹50K — rejected',
    reasoning: 'Margin floor compromised; risk profile outside CEO policy.',
    stats: [
      { label: 'Bundle',   value: '4 SKUs' },
      { label: 'Margin Δ', value: '− 12 %', color: 'danger' },
      { label: 'Risk',     value: 'high' },
      { label: 'Cap',      value: 'breached' },
    ],
    confidence: 2, confidenceLabel: 'Medium',
    cosign: 'Priya · Merch',
    chain: [
      { who: 'Priya · Merch lead',     meta: 'Drafted', state: 'done' },
      { who: 'Auto · evidence',         meta: 'Partial · 2/3', state: 'done' },
      { who: 'You · CEO',              meta: 'Rejected · margin floor breached', state: 'done' },
      { who: 'Returned to merchandising', meta: 'Revise', state: 'done' },
    ],
    workflow: ['Queued', 'Context built', 'Agent ran', 'Verified', 'Rejected', 'Returned', 'Outcome tracked'].map((l, i) => ({
      label: l, meta: '', time: 'Mon', state: i < 5 ? 'done' : i === 5 ? 'failed' : 'pending',
    })),
  },
];

/* === activity stream === */
const SEED_ACTIVITY = [
  { mod: 'orbit',     icon: 'O', title: 'orbit.daily_brief verified · 3 recommendations',     meta: 'orbit_brief_agent',  runId: 'rcp-44c9', time: '2 min' },
  { mod: 'approvals', icon: 'A', title: 'Awaiting your sign on Mumbai → Delhi transfer',       meta: 'co-sign · Priya',    runId: 'rcp-44c9', time: '9 min' },
  { mod: 'vault',     icon: 'V', title: 'vault.deadstock_scan completed · 38 candidates',      meta: 'vault_action_agent', runId: 'rcp-44ca', time: '11 min' },
  { mod: 'price',     icon: 'P', title: '24K rate update +1.4 % within ceiling',                meta: 'price_explain_agent', runId: 'rcp-44cb', time: '4 min' },
  { mod: 'connect',   icon: 'C', title: 'Tally sync completed · 412 SKUs reconciled',           meta: 'connector',                              time: '32 min' },
  { mod: 'kraft',     icon: 'K', title: 'CAD-117 packet ready for CEO review',                  meta: 'designer · Vikram',  runId: 'rcp-44cc', time: '1 h' },
];

/* ============================================================
   HEAD OF MERCHANDISING · ORBIT fixtures
   Draft briefs (status before CEO sign), market signals, opportunities.
   These map to the API spec §13 (Modules-Orbit endpoints).
   ============================================================ */

const SEED_HOM_DRAFTS = [
  {
    id: 'rcp-44d2',
    mod: 'orbit',
    priority: 'P1',
    impact: 'money',
    stamp: 'Drafted · Orbit daily brief',
    status: 'pending',
    statusLabel: 'Drafting · awaiting submit',
    runId: 'rcp-44d2', runVersion: 'v1', runWhen: '4 min ago',
    title: 'Push solitaire eternity collection to Delhi storefront',
    reasoning: 'Three signals indicate Delhi cohort is primed for premium solitaire eternity. Recommend front-window placement + 4-week test. Targeting 22 SKUs from the inactive launch pack.',
    stats: [
      { label: 'Cohort',     value: 'Delhi · ages 30-44' },
      { label: 'SKUs',       value: '22' },
      { label: 'Projection', value: '+ ₹18.4 L', color: 'success' },
      { label: 'Test window',value: '4 weeks' },
    ],
    confidence: 3, confidenceLabel: 'High',
    cosign: 'You · Merch',
    chain: [
      { who: 'Auto · evidence sweep',  meta: '3 / 3 claims sourced · 9:32', state: 'done' },
      { who: 'You · HoM',              meta: 'Drafting · ready to submit',  state: 'now'  },
      { who: 'CEO',                    meta: 'Awaits your submit',          state: 'pending' },
      { who: 'Manufacturing · staging', meta: 'Pre-stages on approval',     state: 'pending' },
    ],
    workflow: ['Queued','Context built','Agent ran','Verified','HoM review','CEO approval','Outcome tracked'].map((label, i) => ({
      label,
      step: ['queued','context_built','agent_ran','verified','hom_review','awaiting_approval','outcome_tracked'][i],
      meta: ['workflow.start','128 KB · 4 sources','orbit_brief_agent v2.1','3 / 3 claims sourced','HoM · ⌘⏎ to submit','CEO sign','curator records'][i],
      time: ['09:32:01','09:32:02','09:32:09','09:32:11','now','—','—'][i],
      state: i < 4 ? 'done' : i === 4 ? 'now' : 'pending',
    })),
    claims: [
      { text: 'Delhi cohort engagement up 28 % on similar editorial last quarter.', source: 'sales.read',     receipt: 'rcp-44d2 / claim 1' },
      { text: 'Inactive launch pack carries 22 matching SKUs at margin floor.',      source: 'inventory.read', receipt: 'rcp-44d2 / claim 2' },
      { text: 'Delhi storefront has open premium-window allocation through July.',   source: 'wiki.lookup',    receipt: 'rcp-44d2 / claim 3' },
    ],
    receipts: [
      { tool: 'sql.query',     scope: 'sales.read',     id: 'tool-receipt-901' },
      { tool: 'sql.query',     scope: 'inventory.read', id: 'tool-receipt-902' },
      { tool: 'wiki.lookup',   scope: 'wiki.read',      id: 'tool-receipt-903' },
    ],
    math: [
      { expr: 'projected_unlock = Σ(sku_price × engagement_lift)', value: '₹18,42,000' },
      { expr: 'test_window_days', value: '28' },
    ],
  },
  {
    id: 'rcp-44d3',
    mod: 'orbit',
    priority: 'P2',
    impact: 'launch',
    stamp: 'Drafted · Opportunity → brief',
    status: 'pending',
    statusLabel: 'Drafting · agent revision requested',
    runId: 'rcp-44d3', runVersion: 'v2', runWhen: '18 min ago',
    title: 'Test bridal Q3 capsule on Mumbai high-net-worth segment',
    reasoning: 'Q3 bridal cohort historically buys editorial 6 weeks before peak. Capsule prototype CAD-117 fits the price band. Recommend creating a KRAFT brief for designer prototyping.',
    stats: [
      { label: 'Segment',    value: 'Mumbai · HNW' },
      { label: 'Cohort size',value: '480 customers' },
      { label: 'Lead time',  value: '6 weeks' },
      { label: 'Hit rate',   value: '34 %', color: 'success' },
    ],
    confidence: 2, confidenceLabel: 'Medium',
    cosign: 'You · Merch',
    chain: [
      { who: 'Auto · evidence sweep', meta: '2 / 3 claims sourced',  state: 'done' },
      { who: 'You · HoM',             meta: 'Revising · awaiting v3', state: 'now'  },
      { who: 'CEO',                   meta: 'Awaits your submit',    state: 'pending' },
    ],
    workflow: ['Queued','Context built','Agent ran','Verified','HoM review','CEO approval','Outcome tracked'].map((label, i) => ({
      label,
      step: ['queued','context_built','agent_ran','verified','hom_review','awaiting_approval','outcome_tracked'][i],
      meta: ['workflow.start','64 KB · 3 sources','orbit_brief_agent v2.1','2 / 3 claims · 1 weak','HoM · refining','CEO sign','curator records'][i],
      time: ['09:18:00','09:18:01','09:18:07','09:18:10','now','—','—'][i],
      state: i < 4 ? 'done' : i === 4 ? 'now' : 'pending',
    })),
    claims: [
      { text: 'Mumbai HNW segment shows 34 % conversion on bridal capsules historically.', source: 'sales.read', receipt: 'rcp-44d3 / claim 1' },
      { text: 'CAD-117 manufactures within 6-week lead time at vendor capacity.',          source: 'connect.vendor', receipt: 'rcp-44d3 / claim 2' },
    ],
    receipts: [
      { tool: 'sql.query',      scope: 'sales.read',    id: 'tool-receipt-904' },
      { tool: 'connect.vendor', scope: 'partner.read',  id: 'tool-receipt-905' },
    ],
    math: [
      { expr: 'hit_rate · historical',  value: '34 %' },
      { expr: 'lead_time_weeks',        value: '6' },
    ],
  },
  {
    id: 'rcp-44d4',
    mod: 'orbit',
    priority: 'P0',
    impact: 'rate',
    stamp: 'Drafted · Signal triage',
    status: 'pending',
    statusLabel: 'Drafting · awaiting submit',
    runId: 'rcp-44d4', runVersion: 'v1', runWhen: '2 h ago',
    title: 'Diamond rough shortage · review price ceiling for May–Jul',
    reasoning: 'Supply-side feed shows rough diamond inventory drop of 18 % at our two primary vendors. PRICE policy may need a temporary ceiling adjustment.',
    stats: [
      { label: 'Vendors',   value: '2 of 2 affected' },
      { label: 'Drop',      value: '−18 %' },
      { label: 'Affects',   value: '142 SKUs' },
      { label: 'Margin Δ',  value: '− 2.1 pp', color: 'danger' },
    ],
    confidence: 4, confidenceLabel: 'Verified',
    cosign: 'You · Merch · Pricing co-sign',
    chain: [
      { who: 'Auto · evidence sweep', meta: '4 / 4 claims sourced',                          state: 'done' },
      { who: 'You · HoM',             meta: 'Ready to submit · loops Pricing in chain',     state: 'now'  },
      { who: 'Pricing Lead',          meta: 'Co-sign for ceiling change',                    state: 'pending' },
      { who: 'CEO',                   meta: 'Final approval',                                state: 'pending' },
    ],
    workflow: ['Queued','Context built','Agent ran','Verified','HoM review','Co-sign Pricing','CEO approval'].map((label, i) => ({
      label,
      step: ['queued','context_built','agent_ran','verified','hom_review','cosign','awaiting_approval'][i],
      meta: ['workflow.start','96 KB · supply feed','orbit_brief_agent v2.1','4 / 4 claims','HoM · ready','Pricing','CEO sign'][i],
      time: ['07:40:01','07:40:02','07:40:08','07:40:11','now','—','—'][i],
      state: i < 4 ? 'done' : i === 4 ? 'now' : 'pending',
    })),
    claims: [
      { text: 'Vendor A reported 17 % rough drop · confirmed 06:00 IST.',     source: 'connect.vendor', receipt: 'rcp-44d4 / claim 1' },
      { text: 'Vendor B reported 19 % rough drop · confirmed 06:18 IST.',     source: 'connect.vendor', receipt: 'rcp-44d4 / claim 2' },
      { text: '142 SKUs use these two vendors as primary diamond source.',    source: 'inventory.read', receipt: 'rcp-44d4 / claim 3' },
      { text: 'PRICE ceiling policy permits +2 % adjustment within CEO sign.', source: 'wiki.lookup',    receipt: 'rcp-44d4 / claim 4' },
    ],
    receipts: [
      { tool: 'connect.vendor', scope: 'partner.read',    id: 'tool-receipt-906' },
      { tool: 'sql.query',      scope: 'inventory.read',  id: 'tool-receipt-907' },
      { tool: 'wiki.lookup',    scope: 'wiki.read',       id: 'tool-receipt-908' },
    ],
    math: [
      { expr: 'weighted_drop = (vendorA + vendorB) / 2', value: '−18 %' },
      { expr: 'margin_delta_at_current_price',          value: '− 2.1 pp' },
    ],
  },
];

/* Signals · unprocessed market signals waiting on HoM triage */
const SEED_SIGNALS = [
  {
    id: 'sig-9001', source: 'social',    title: 'Solitaire stack styling spiking on metro social',
    description: 'Engagement on solitaire-stack content up 4.2× WoW across Delhi and Mumbai accounts. Average customer age cohort 28–34.',
    detectedAt: '2026-05-21T08:30:00Z', freshness: 'fresh', confidence: 3,
    modulesTagged: ['kraft', 'orbit'],
    status: 'new',
    metrics: [
      { label: 'WoW lift', value: '4.2×', color: 'success' },
      { label: 'Cities', value: '2' },
      { label: 'Age cohort', value: '28-34' },
    ],
    runId: 'rcp-44d5',
  },
  {
    id: 'sig-9002', source: 'catalogue', title: 'Inactive eternity pack matches Delhi demand pattern',
    description: '22 SKUs in launch pack 2024-Q4 align with current Delhi cohort engagement. Margin floor preserved.',
    detectedAt: '2026-05-21T09:12:00Z', freshness: 'fresh', confidence: 3,
    modulesTagged: ['vault', 'kraft', 'orbit'],
    status: 'new',
    metrics: [
      { label: 'SKUs', value: '22' },
      { label: 'Aged', value: '180+ days' },
      { label: 'Margin', value: '+ 36 %', color: 'success' },
    ],
    runId: 'rcp-44d5',
  },
  {
    id: 'sig-9003', source: 'partner',   title: 'Vendor B confirms rough diamond shortage',
    description: '19 % drop in rough supply confirmed from primary partner. May affect 142 SKUs that use this vendor as primary source.',
    detectedAt: '2026-05-21T06:18:00Z', freshness: 'fresh', confidence: 4,
    modulesTagged: ['price', 'orbit'],
    status: 'triaged',
    metrics: [
      { label: 'Drop', value: '−19 %', color: 'danger' },
      { label: 'SKUs at risk', value: '142' },
      { label: 'Vendor', value: 'B · primary' },
    ],
    runId: 'rcp-44d4',
  },
  {
    id: 'sig-9004', source: 'sales',     title: 'Pune cohort velocity cooling on bridal',
    description: 'Pune bridal engagement down 14 % over 21 days. Mumbai absorbed similar SKUs in 2 days when transferred (rcp-44a2).',
    detectedAt: '2026-05-20T17:42:00Z', freshness: 'stale', confidence: 2,
    modulesTagged: ['vault', 'orbit'],
    status: 'new',
    metrics: [
      { label: 'Δ velocity', value: '−14 %', color: 'danger' },
      { label: 'Window', value: '21 d' },
      { label: 'Cohort', value: 'Pune · bridal' },
    ],
    runId: 'rcp-44d6',
  },
  {
    id: 'sig-9005', source: 'news',      title: 'GST council to consider jewellery levy in June',
    description: 'Public docket lists jewellery GST review · potential 1.5 % move. Confidence based on agenda items, not policy commitment.',
    detectedAt: '2026-05-20T11:10:00Z', freshness: 'stale', confidence: 2,
    modulesTagged: ['price', 'orbit'],
    status: 'new',
    metrics: [
      { label: 'Magnitude',  value: '~1.5 %' },
      { label: 'Window',     value: 'June council' },
      { label: 'Confidence', value: 'mid' },
    ],
    runId: null,
  },
  {
    id: 'sig-9006', source: 'sales',     title: 'Bengaluru solitaire conversion above forecast',
    description: 'Engagement-to-sale on solitaire band up 12 % for week ending 18 May vs. 14-day rolling. No specific store responsible.',
    detectedAt: '2026-05-19T22:00:00Z', freshness: 'stale', confidence: 3,
    modulesTagged: ['vault', 'orbit'],
    status: 'dismissed',
    metrics: [
      { label: 'Lift', value: '+ 12 %', color: 'success' },
      { label: 'City', value: 'Bengaluru' },
    ],
    runId: null,
  },
];

/* Opportunities · forward-looking action items distilled from signals */
const SEED_OPPORTUNITIES = [
  {
    id: 'opp-7001', title: 'Reactivate Q4 inactive launch pack for Delhi solitaire-stack trend',
    description: 'Combine signal sig-9001 with catalogue match sig-9002. Cohort, supply, and storefront align.',
    projectedImpact: { value: '₹18.4 L', amount: 1842000, currency: 'INR' },
    confidence: 3, expiresAt: '2026-06-20T00:00:00Z',
    status: 'open',
    conversionPaths: ['create_brief', 'send_to_kraft'],
    relatedSignals: ['sig-9001', 'sig-9002'],
  },
  {
    id: 'opp-7002', title: 'Pre-emptive ceiling raise on diamond-heavy SKUs',
    description: 'Rough shortage at primary vendor (sig-9003) compounds with potential GST move (sig-9005). Pricing co-sign needed.',
    projectedImpact: { value: '+ 2.1 pp margin', amount: 21, currency: 'PERCENT_TENTHS' },
    confidence: 4, expiresAt: '2026-06-05T00:00:00Z',
    status: 'open',
    conversionPaths: ['create_brief', 'cosign_pricing'],
    relatedSignals: ['sig-9003', 'sig-9005'],
  },
  {
    id: 'opp-7003', title: 'Pune → Mumbai transfer for bridal cohort cooldown',
    description: 'Repeat pattern from rcp-44a2 — earlier transfer cleared in 2 days. sig-9004 mirrors that signature.',
    projectedImpact: { value: '₹4.8 L', amount: 480000, currency: 'INR' },
    confidence: 3, expiresAt: '2026-06-01T00:00:00Z',
    status: 'open',
    conversionPaths: ['send_to_vault'],
    relatedSignals: ['sig-9004'],
  },
];

/* ============================================================
   INVENTORY MANAGER · VAULT fixtures
   Aged SKUs the agent flags + action drafts the IM is preparing.
   Maps to architecture §8.3 + API spec §13 (Modules-Vault endpoints).
   ============================================================ */

/* Aged SKUs · the queue. Each carries a recommended action that the agent
   produced from a scan. IM reviews each item before drafting a real action. */
const SEED_VAULT_ITEMS = [
  { id: 'SKU-00883', sku: 'SKU-00883', name: 'Solitaire eternity band · 18K WG',
    city: 'Mumbai',     cohort: 'Solitaire eternity',  ageDays: 214, value: { amount: 342000, currency: 'INR', display: '₹3.42 L' },
    status: 'recommended_action', signals: ['sig-9001', 'sig-9002'],
    recommendedAction: { type: 'transfer', confidence: 3, toCity: 'Delhi',
      rationale: 'Delhi cohort 22 % above forecast on similar SKUs · transfer cheaper than reprice',
      projectedUnlock: { amount: 342000, currency: 'INR', display: '₹3.42 L' } } },
  { id: 'SKU-00901', sku: 'SKU-00901', name: 'Halo cluster · 18K YG',
    city: 'Mumbai',     cohort: 'Halo cluster',        ageDays: 198, value: { amount: 185000, currency: 'INR', display: '₹1.85 L' },
    status: 'recommended_action', signals: ['sig-9001'],
    recommendedAction: { type: 'reprice', confidence: 3, percentDelta: -0.08, newPriceHint: '−8 % MRP',
      rationale: 'Mumbai velocity sliding 14 d · reprice retains margin floor',
      projectedUnlock: { amount: 185000, currency: 'INR', display: '₹1.85 L' } } },
  { id: 'SKU-00664', sku: 'SKU-00664', name: 'Princess solitaire pendant',
    city: 'Delhi',      cohort: 'Solitaire pendant',   ageDays: 190, value: { amount: 289000, currency: 'INR', display: '₹2.89 L' },
    status: 'recommended_action', signals: ['sig-9006'],
    recommendedAction: { type: 'transfer', confidence: 2, toCity: 'Bengaluru',
      rationale: 'Bengaluru solitaire conversion lift confirms demand',
      projectedUnlock: { amount: 289000, currency: 'INR', display: '₹2.89 L' } } },
  { id: 'SKU-00712', sku: 'SKU-00712', name: 'Three-stone classic ring · 18K WG',
    city: 'Bengaluru',  cohort: 'Three-stone classic', ageDays: 241, value: { amount: 98000,  currency: 'INR', display: '₹0.98 L' },
    status: 'recommended_action', signals: [],
    recommendedAction: { type: 'hold', confidence: 3, holdWindowDays: 30,
      rationale: 'Cohort velocity recovering · hold one cycle before action',
      projectedUnlock: { amount: 0, currency: 'INR', display: '—' } } },
  { id: 'SKU-01014', sku: 'SKU-01014', name: 'Diamond eternity tennis bracelet',
    city: 'Pune',       cohort: 'Eternity bracelet',   ageDays: 267, value: { amount: 220000, currency: 'INR', display: '₹2.20 L' },
    status: 'recommended_action', signals: ['sig-9004'],
    recommendedAction: { type: 'reprice', confidence: 3, percentDelta: -0.12, newPriceHint: '−12 % MRP',
      rationale: 'Pune cohort cooling 21 d · deeper reprice to clear before quarter end',
      projectedUnlock: { amount: 220000, currency: 'INR', display: '₹2.20 L' } } },
  { id: 'SKU-02218', sku: 'SKU-02218', name: 'Pavé eternity band · 18K WG',
    city: 'Mumbai',     cohort: 'Pavé eternity',       ageDays: 203, value: { amount: 412000, currency: 'INR', display: '₹4.12 L' },
    status: 'recommended_action', signals: ['sig-9001'],
    recommendedAction: { type: 'transfer', confidence: 4, toCity: 'Delhi',
      rationale: 'Highest-confidence transfer of the scan · Delhi storefront window open',
      projectedUnlock: { amount: 412000, currency: 'INR', display: '₹4.12 L' } } },
  { id: 'SKU-03041', sku: 'SKU-03041', name: 'Floral cluster ring · 18K YG',
    city: 'Bengaluru',  cohort: 'Floral cluster',      ageDays: 211, value: { amount: 156000, currency: 'INR', display: '₹1.56 L' },
    status: 'recommended_action', signals: [],
    recommendedAction: { type: 'reprice', confidence: 2, percentDelta: -0.06, newPriceHint: '−6 % MRP',
      rationale: 'Mild reprice keeps margin and clears in one cycle',
      projectedUnlock: { amount: 156000, currency: 'INR', display: '₹1.56 L' } } },
  { id: 'SKU-03501', sku: 'SKU-03501', name: 'Half-eternity stack ring',
    city: 'Delhi',      cohort: 'Stack ring',          ageDays: 185, value: { amount: 78000,  currency: 'INR', display: '₹0.78 L' },
    status: 'recommended_action', signals: ['sig-9001'],
    recommendedAction: { type: 'hold', confidence: 2, holdWindowDays: 14,
      rationale: 'Signal sig-9001 suggests upside · hold for 14 d to confirm',
      projectedUnlock: { amount: 0, currency: 'INR', display: '—' } } },
  { id: 'SKU-01822', sku: 'SKU-01822', name: 'Oval-cut bridal pendant',
    city: 'Pune',       cohort: 'Bridal pendant',      ageDays: 224, value: { amount: 190000, currency: 'INR', display: '₹1.90 L' },
    status: 'recommended_action', signals: ['sig-9004'],
    recommendedAction: { type: 'transfer', confidence: 3, toCity: 'Mumbai',
      rationale: 'Pune→Mumbai transfer cleared similar SKUs in 2 d historically (rcp-44a2)',
      projectedUnlock: { amount: 190000, currency: 'INR', display: '₹1.90 L' } } },
  { id: 'SKU-02945', sku: 'SKU-02945', name: 'Marquise solitaire pendant',
    city: 'Mumbai',     cohort: 'Marquise pendant',    ageDays: 252, value: { amount: 308000, currency: 'INR', display: '₹3.08 L' },
    status: 'recommended_action', signals: [],
    recommendedAction: { type: 'reprice', confidence: 3, percentDelta: -0.10, newPriceHint: '−10 % MRP',
      rationale: 'Aged 252 d in Mumbai · cohort cooled · reprice to clear',
      projectedUnlock: { amount: 308000, currency: 'INR', display: '₹3.08 L' } } },
];


/* Action drafts · IM is preparing these · once submitted, they become Decisions
   in CEO's APPROVALS inbox, possibly with a Pricing or Logistics co-sign step. */
const SEED_VAULT_ACTIONS = [
  {
    id: 'rcp-vlt01', mod: 'vault', type: 'transfer',
    priority: 'P1', impact: 'money',
    stamp: 'Verified · Vault action draft',
    status: 'pending',
    statusLabel: 'Drafting · awaiting submit',
    runId: 'rcp-vlt01', runVersion: 'v1', runWhen: '8 min ago',
    title: 'Transfer 4 high-margin SKUs · Mumbai → Delhi · unlock ₹14.2 L',
    reasoning: 'Bundle of 4 highest-confidence transfer recommendations from today\'s scan. All Delhi cohort matches; Logistics has the manifest pre-staged.',
    itemIds: ['SKU-00883', 'SKU-02218', 'SKU-00664', 'SKU-01822'],
    fromCity: 'Mumbai', toCity: 'Delhi',
    stats: [
      { label: 'Unlock',       value: '₹14.2 L', color: 'success' },
      { label: 'SKUs',         value: '4' },
      { label: 'Median age',   value: '214 d' },
      { label: 'Margin Δ',     value: '+ 6.4 %', color: 'success' },
    ],
    confidence: 4, confidenceLabel: 'Verified',
    cosign: 'You · Inventory · Logistics co-sign',
    chain: [
      { who: 'Auto · evidence sweep',  meta: '3 / 3 claims sourced',           state: 'done' },
      { who: 'You · Inventory',        meta: 'Drafting · ready to submit',     state: 'now' },
      { who: 'Logistics',              meta: 'Co-sign on manifest feasibility', state: 'pending' },
      { who: 'CEO',                    meta: 'Final approval',                  state: 'pending' },
      { who: 'CONNECT · execute',      meta: 'Tally + WMS update',              state: 'pending' },
    ],
    workflow: ['Queued','Context built','Agent ran','Verified','IM review','Logistics co-sign','CEO approval'].map((label, i) => ({
      label,
      step: ['queued','context_built','agent_ran','verified','im_review','cosign_logistics','awaiting_approval'][i],
      meta: ['workflow.start','SKU snapshot','vault_action_agent v2.1','3 / 3 sourced','IM · ⌘⏎ to submit','Logistics review','CEO sign'][i],
      time: ['08:34:01','08:34:02','08:34:09','08:34:11','now','—','—'][i],
      state: i < 4 ? 'done' : i === 4 ? 'now' : 'pending',
    })),
    claims: [
      { text: 'Delhi cohort velocity 22 % above forecast across all 4 SKUs.',  source: 'sales.read',           receipt: 'rcp-vlt01 / claim 1' },
      { text: 'Logistics has manifest capacity Mon · Wed · Fri this week.',     source: 'connect.logistics',    receipt: 'rcp-vlt01 / claim 2' },
      { text: 'Delhi sell-price within 4 % of catalogue · no reprice needed.',  source: 'price.read · deterministic', receipt: 'rcp-vlt01 / claim 3' },
    ],
    receipts: [
      { tool: 'sql.query',        scope: 'sales.read',           id: 'tool-receipt-vlt-1' },
      { tool: 'connect.logistics',scope: 'partner.read',         id: 'tool-receipt-vlt-2' },
      { tool: 'price.calculate',  scope: 'deterministic',        id: 'tool-receipt-vlt-3' },
    ],
    math: [
      { expr: 'unlock = Σ(sku_value)',                       value: '₹14,21,800' },
      { expr: 'avg_margin_delta · post_transfer',            value: '+ 6.4 %' },
      { expr: 'transfer_cost · estimated',                   value: '₹38,800' },
    ],
  },
  {
    id: 'rcp-vlt02', mod: 'vault', type: 'reprice',
    priority: 'P1', impact: 'money',
    stamp: 'Verified · Vault action draft',
    status: 'pending',
    statusLabel: 'Drafting · awaiting Pricing co-sign',
    runId: 'rcp-vlt02', runVersion: 'v2', runWhen: '23 min ago',
    title: 'Reprice 3 Bengaluru SKUs · −8 % · unlock ₹4.4 L',
    reasoning: 'Three Bengaluru SKUs aged 198–241 d in a cooling cohort. Reprice retains margin floor; transfer not viable given Bengaluru-only demand pattern. Pricing Lead must co-sign because cap is at policy edge.',
    itemIds: ['SKU-00901', 'SKU-03041', 'SKU-00712'],
    fromCity: 'Bengaluru', toCity: null,
    repricePercent: -0.08,
    stats: [
      { label: 'Unlock',     value: '₹4.4 L', color: 'success' },
      { label: 'SKUs',       value: '3' },
      { label: 'Reprice',    value: '−8 %' },
      { label: 'Margin Δ',   value: '− 1.2 %', color: 'danger' },
    ],
    confidence: 3, confidenceLabel: 'High',
    cosign: 'You · Inventory · Pricing co-sign',
    chain: [
      { who: 'Auto · evidence sweep',  meta: '3 / 3 claims sourced',     state: 'done' },
      { who: 'You · Inventory',        meta: 'Drafted v2 · refining',    state: 'now' },
      { who: 'Pricing Lead',           meta: 'Co-sign for ceiling check', state: 'pending' },
      { who: 'CEO',                    meta: 'Final approval',           state: 'pending' },
      { who: 'CONNECT · execute',      meta: 'PRICE engine apply',       state: 'pending' },
    ],
    workflow: ['Queued','Context built','Agent ran','Verified','IM review','Pricing co-sign','CEO approval'].map((label, i) => ({
      label,
      step: ['queued','context_built','agent_ran','verified','im_review','cosign_pricing','awaiting_approval'][i],
      meta: ['workflow.start','3 SKUs snapshot','vault_action_agent v2.1','3 / 3 sourced','IM · refining','Pricing review','CEO sign'][i],
      time: ['08:19:00','08:19:01','08:19:08','08:19:10','now','—','—'][i],
      state: i < 4 ? 'done' : i === 4 ? 'now' : 'pending',
    })),
    claims: [
      { text: 'Bengaluru cohort velocity cooled 31 % over 30 d.',         source: 'sales.read',           receipt: 'rcp-vlt02 / claim 1' },
      { text: 'Transfer cost > reprice margin loss for this size lot.',    source: 'price.calculate',      receipt: 'rcp-vlt02 / claim 2' },
      { text: '−8 % keeps weighted margin within policy floor (32 %).',   source: 'wiki.lookup',          receipt: 'rcp-vlt02 / claim 3' },
    ],
    receipts: [
      { tool: 'sql.query',       scope: 'sales.read',     id: 'tool-receipt-vlt-4' },
      { tool: 'price.calculate', scope: 'deterministic',  id: 'tool-receipt-vlt-5' },
      { tool: 'wiki.lookup',     scope: 'wiki.read',      id: 'tool-receipt-vlt-6' },
    ],
    math: [
      { expr: 'reprice_unlock = Σ(price × −0.08)',     value: '₹4,40,400' },
      { expr: 'margin_loss',                            value: '− 1.2 %' },
      { expr: 'transfer_cost_alt',                      value: '₹56,000' },
    ],
  },
  {
    id: 'rcp-vlt03', mod: 'vault', type: 'hold',
    priority: 'P2', impact: 'ops',
    stamp: 'Verified · Vault action draft',
    status: 'pending',
    statusLabel: 'Drafting · IM-only action',
    runId: 'rcp-vlt03', runVersion: 'v1', runWhen: '1 h ago',
    title: 'Hold 2 Delhi SKUs for 14 days · signal pending confirmation',
    reasoning: 'Two Delhi SKUs flagged by Orbit sig-9001 (solitaire-stack social spike). Hold one cycle to confirm signal before deciding transfer vs reprice.',
    itemIds: ['SKU-03501'],
    fromCity: 'Delhi', toCity: null,
    holdDays: 14,
    stats: [
      { label: 'Items',       value: '1' },
      { label: 'Window',      value: '14 d' },
      { label: 'Risk',        value: 'low' },
      { label: 'Cost',        value: '₹0', color: 'success' },
    ],
    confidence: 3, confidenceLabel: 'High',
    cosign: 'You · Inventory · IM-only',
    chain: [
      { who: 'Auto · evidence sweep',  meta: '2 / 2 claims sourced',         state: 'done' },
      { who: 'You · Inventory',        meta: 'Drafting · IM signs only',     state: 'now' },
      { who: 'Watchlist · 14 days',    meta: 'Auto-revisit on signal change', state: 'pending' },
    ],
    workflow: ['Queued','Context built','Agent ran','Verified','IM review','Hold active','Auto-revisit'].map((label, i) => ({
      label,
      step: ['queued','context_built','agent_ran','verified','im_review','executed','outcome_tracked'][i],
      meta: ['workflow.start','snapshot','vault_action_agent v2.1','2 / 2 sourced','IM · ⌘⏎ to apply','Watchlist active','Signal monitor'][i],
      time: ['07:42:00','07:42:01','07:42:07','07:42:09','now','—','—'][i],
      state: i < 4 ? 'done' : i === 4 ? 'now' : 'pending',
    })),
    claims: [
      { text: 'sig-9001 suggests Delhi stack-ring upside · momentum new.',    source: 'orbit.signal',  receipt: 'rcp-vlt03 / claim 1' },
      { text: 'Holding 14 d incurs ₹0 carry-cost given existing rack space.', source: 'inventory.read', receipt: 'rcp-vlt03 / claim 2' },
    ],
    receipts: [
      { tool: 'orbit.signal',   scope: 'orbit.read',     id: 'tool-receipt-vlt-7' },
      { tool: 'sql.query',      scope: 'inventory.read', id: 'tool-receipt-vlt-8' },
    ],
    math: [
      { expr: 'hold_carry_cost',     value: '₹0' },
      { expr: 'reassess_after_days', value: '14' },
    ],
  },
];


/* ============================================================
   PRICING LEAD · PRICE fixtures
   Architecture §8.4 — "Agent explains. PRICE engine calculates."
   Every rate, quote, and co-sign carries its deterministic formula so the
   "View Formula" button (architecture §8.4) is always meaningful.
   ============================================================ */

/* Metal + stone rates · sourced from market_feed + supplier_feed.
   The PRICE engine consumes these as inputs to its deterministic math.
   Each rate carries its source so the View Formula drawer can cite it. */
const SEED_PRICE_RATES = [
  { id: 'r-24kg',  kind: 'metal', spec: '24K gold',          rate: { amount: 7842000, currency: 'INR', display: '₹78,420' }, per: '10 g',  source: 'market_feed',   updatedAt: '12 min ago', delta: '+ 1.4 %', deltaDir: 'up' },
  { id: 'r-22kg',  kind: 'metal', spec: '22K gold',          rate: { amount: 7180000, currency: 'INR', display: '₹71,800' }, per: '10 g',  source: 'market_feed',   updatedAt: '12 min ago', delta: '+ 1.3 %', deltaDir: 'up' },
  { id: 'r-18wg',  kind: 'metal', spec: '18K white gold',    rate: { amount: 5881500, currency: 'INR', display: '₹58,815' }, per: '10 g',  source: 'derived',       updatedAt: '12 min ago', delta: '+ 1.4 %', deltaDir: 'up' },
  { id: 'r-18yg',  kind: 'metal', spec: '18K yellow gold',   rate: { amount: 5881500, currency: 'INR', display: '₹58,815' }, per: '10 g',  source: 'derived',       updatedAt: '12 min ago', delta: '+ 1.4 %', deltaDir: 'up' },
  { id: 'r-18rg',  kind: 'metal', spec: '18K rose gold',     rate: { amount: 5881500, currency: 'INR', display: '₹58,815' }, per: '10 g',  source: 'derived',       updatedAt: '12 min ago', delta: '+ 1.4 %', deltaDir: 'up' },
  { id: 'r-pt',    kind: 'metal', spec: 'Platinum 950',      rate: { amount: 8900000, currency: 'INR', display: '₹89,000' }, per: '10 g',  source: 'market_feed',   updatedAt: '12 min ago', delta: '+ 0.6 %', deltaDir: 'up' },
  { id: 'r-ag',    kind: 'metal', spec: 'Silver 925',        rate: { amount: 95000,   currency: 'INR', display: '₹950'    }, per: '10 g',  source: 'market_feed',   updatedAt: '12 min ago', delta: '− 0.2 %', deltaDir: 'down' },
  { id: 'r-d-fsi', kind: 'stone', spec: 'Diamond · F · SI1',  rate: { amount: 42000000, currency: 'INR', display: '₹4,20,000' }, per: 'carat', source: 'supplier_feed', updatedAt: '4 h ago',   delta: '+ 3.1 %', deltaDir: 'up' },
  { id: 'r-d-dvvs',kind: 'stone', spec: 'Diamond · D · VVS1', rate: { amount: 120000000,currency: 'INR', display: '₹12,00,000'}, per: 'carat', source: 'supplier_feed', updatedAt: '4 h ago',   delta: '+ 2.7 %', deltaDir: 'up' },
  { id: 'r-em',    kind: 'stone', spec: 'Emerald · Colombian',rate: { amount: 18000000, currency: 'INR', display: '₹1,80,000' }, per: 'carat', source: 'supplier_feed', updatedAt: '6 h ago',   delta: 'flat',    deltaDir: 'flat' },
];


/* Customer quotes drafted by PL. Each is a structured pricing object with
   per-line margin computation. The 'formula' field is what View Formula shows. */
const SEED_PRICE_QUOTES = [
  {
    id: 'q-2001', customer: 'Sharma family',          segment: 'HNW · Delhi',
    skuCount: 3, totalAmount: { amount: 42000000, currency: 'INR', display: '₹4.20 L' },
    discountPercent: 5, margin: 38, marginFloor: 32, ceilingCheck: 'pass',
    status: 'draft', validUntil: '7 days', updatedAt: '2 h ago',
    items: [
      { sku: 'SKU-04102', name: 'Solitaire engagement ring · 1.05 ct', qty: 1, listed: 280000, final: 266000, margin: 39 },
      { sku: 'SKU-04201', name: 'Matching solitaire band · 18K WG',     qty: 1, listed: 95000,  final: 90250,  margin: 37 },
      { sku: 'SKU-04303', name: 'Diamond pendant · 0.5 ct',              qty: 1, listed: 55000,  final: 52250,  margin: 38 },
    ],
    formula: 'total = Σ(listed × (1 − discount)) · margin_weighted = (total − cost) / total = 38 %',
  },
  {
    id: 'q-2002', customer: 'Priya Jewellers · trade', segment: 'B2B',
    skuCount: 8, totalAmount: { amount: 185000000, currency: 'INR', display: '₹18.5 L' },
    discountPercent: 12, margin: 33, marginFloor: 32, ceilingCheck: 'pass',
    status: 'submitted', validUntil: '14 days', updatedAt: '4 h ago',
    items: [],
    formula: 'trade_discount = 12 % · margin retained at 33 % · within floor',
    submittedTo: 'CEO',
  },
  {
    id: 'q-2003', customer: 'Anil + Reena wedding',    segment: 'HNW · Mumbai',
    skuCount: 12, totalAmount: { amount: 260000000, currency: 'INR', display: '₹26.0 L' },
    discountPercent: 8, margin: 41, marginFloor: 32, ceilingCheck: 'pass',
    status: 'approved', validUntil: '21 days', updatedAt: 'Yesterday',
    items: [],
    formula: 'wedding bundle discount · 8 % · margin healthy at 41 %',
    sentAt: 'Tue 14:30',
  },
  {
    id: 'q-2004', customer: 'Walk-in · sample quote',   segment: 'retail',
    skuCount: 1, totalAmount: { amount: 14000000, currency: 'INR', display: '₹1.40 L' },
    discountPercent: 18, margin: 28, marginFloor: 32, ceilingCheck: 'breach',
    status: 'pending', validUntil: '3 days', updatedAt: '20 min ago',
    items: [
      { sku: 'SKU-04501', name: 'Marquise diamond ring · 0.7 ct', qty: 1, listed: 170000, final: 140000, margin: 28 },
    ],
    formula: 'discount = 18 % · margin drops to 28 % · breaches floor of 32 % · CEO sign required',
    submittedTo: 'CEO',
  },
];


/* SKUs hovering near the margin floor · architecture §8.4 /price/margin-risk */
const SEED_PRICE_MARGIN_RISK = [
  { id: 'SKU-04603', name: 'Halo diamond pendant',     city: 'Mumbai',     margin: 33, floor: 32, risk: 'low',    daysAtRisk:  4, action: 'monitor' },
  { id: 'SKU-04701', name: 'Pavé eternity stack',      city: 'Bengaluru',  margin: 31, floor: 32, risk: 'breach', daysAtRisk: 12, action: 'reprice_up' },
  { id: 'SKU-04802', name: 'Solitaire band · 18K YG',  city: 'Delhi',      margin: 32, floor: 32, risk: 'at',     daysAtRisk:  8, action: 'monitor' },
  { id: 'SKU-04903', name: 'Diamond cluster brooch',   city: 'Pune',       margin: 28, floor: 32, risk: 'breach', daysAtRisk: 18, action: 'reprice_up' },
  { id: 'SKU-05010', name: 'Three-stone bridal ring',  city: 'Mumbai',     margin: 34, floor: 32, risk: 'low',    daysAtRisk:  3, action: 'monitor' },
  { id: 'SKU-05122', name: 'Halo necklace',            city: 'Bengaluru',  margin: 30, floor: 32, risk: 'breach', daysAtRisk: 22, action: 'reprice_up' },
];


/* Cross-module items awaiting Pricing co-sign. In production, these are
   derived from /api/vault/actions + /api/decisions where chain has
   "Pricing Lead · state: now". Seeded here for fresh-page demos. */
const SEED_PRICING_COSIGN_QUEUE = [
  {
    id: 'rcp-cs01', sourceModule: 'vault', sourceRunId: 'rcp-vlt05',
    type: 'reprice', mod: 'vault',
    stamp: 'Verified · Vault reprice draft',
    status: 'pending', statusLabel: 'Awaiting Pricing co-sign',
    runId: 'rcp-cs01', runVersion: 'v1', runWhen: '15 min ago',
    title: 'Reprice 6 Mumbai SKUs · −5 % · unlock ₹3.8 L',
    reasoning: 'Mumbai cohort velocity sliding 18 days. 5 % keeps margin exactly at policy floor; deeper reprice would breach.',
    submittedBy: 'Asha · Inventory',
    stats: [
      { label: 'Unlock',          value: '₹3.8 L', color: 'success' },
      { label: 'SKUs',            value: '6' },
      { label: 'Margin after',    value: '32.0 %' },
      { label: 'Ceiling check',   value: 'at floor' },
    ],
    confidence: 3, confidenceLabel: 'High',
    ceilingCheck: 'at_floor',
    chain: [
      { who: 'Auto · evidence sweep', meta: '3 / 3 claims sourced',         state: 'done' },
      { who: 'Asha · Inventory',      meta: 'Drafted v1 · submitted 15 min ago', state: 'done' },
      { who: 'You · Pricing Lead',    meta: 'Awaits co-sign',                 state: 'now' },
      { who: 'CEO',                   meta: 'Final approval',                 state: 'pending' },
      { who: 'CONNECT · PRICE engine', meta: 'Apply on approval',             state: 'pending' },
    ],
    workflow: ['Queued','Context built','Agent ran','Verified','IM submitted','Pricing co-sign','CEO approval'].map((label, i) => ({
      label,
      step: ['queued','context_built','agent_ran','verified','submitted','cosign_pricing','awaiting_approval'][i],
      meta: ['workflow.start','SKU snapshot','vault_action_agent v2.1','3 / 3 sourced','Asha submitted','PL · review','CEO sign'][i],
      time: ['08:34','08:34','08:34','08:34','08:50','now','—'][i],
      state: i < 5 ? 'done' : i === 5 ? 'now' : 'pending',
    })),
    claims: [
      { text: 'Mumbai cohort velocity sliding 14 d on this cohort.',           source: 'sales.read',           receipt: 'rcp-cs01 / claim 1' },
      { text: '5 % reprice retains weighted margin at 32.0 % (exactly at floor).', source: 'price.calculate',  receipt: 'rcp-cs01 / claim 2' },
      { text: 'Transfer alternative · cost ₹52K · would erode unlock by 14 %.', source: 'price.calculate',     receipt: 'rcp-cs01 / claim 3' },
    ],
    receipts: [
      { tool: 'sql.query',       scope: 'sales.read',     id: 'tool-receipt-pl-1' },
      { tool: 'price.calculate', scope: 'deterministic',  id: 'tool-receipt-pl-2' },
      { tool: 'wiki.lookup',     scope: 'wiki.read',      id: 'tool-receipt-pl-3' },
    ],
    math: [
      { expr: 'margin_after = (price × 0.95 − cost) / (price × 0.95)', value: '32.0 %' },
      { expr: 'ceiling_check = margin_after >= floor (32 %)',          value: 'pass · at floor' },
      { expr: 'unlock = Σ(price × 0.05)',                              value: '₹3,80,000' },
    ],
  },
  {
    id: 'rcp-cs02', sourceModule: 'vault', sourceRunId: 'rcp-vlt06',
    type: 'reprice', mod: 'vault',
    stamp: 'Verified · Vault reprice draft',
    status: 'pending', statusLabel: 'Awaiting Pricing co-sign · ⚠ ceiling breach',
    runId: 'rcp-cs02', runVersion: 'v1', runWhen: '1 h ago',
    title: 'Reprice 1 Pune SKU · −15 % · unlock ₹1.2 L · BREACHES margin floor',
    reasoning: 'Aged 267 days in cooling Pune cohort. 15 % reprice clears inventory but breaks 32 % margin floor (lands at 26 %). Needs explicit Pricing + CEO override.',
    submittedBy: 'Asha · Inventory',
    stats: [
      { label: 'Unlock',          value: '₹1.2 L',  color: 'success' },
      { label: 'SKUs',            value: '1' },
      { label: 'Margin after',    value: '26.4 %', color: 'danger' },
      { label: 'Ceiling check',   value: 'BREACH', color: 'danger' },
    ],
    confidence: 2, confidenceLabel: 'Medium',
    ceilingCheck: 'breach',
    chain: [
      { who: 'Auto · evidence sweep', meta: '3 / 3 claims sourced',           state: 'done' },
      { who: 'Asha · Inventory',      meta: 'Drafted v1 · submitted 1 h ago', state: 'done' },
      { who: 'You · Pricing Lead',    meta: 'Awaits co-sign · ceiling breach', state: 'now' },
      { who: 'CEO',                   meta: 'Final approval · breach override', state: 'pending' },
      { who: 'CONNECT · PRICE engine', meta: 'Apply on approval',              state: 'pending' },
    ],
    workflow: ['Queued','Context built','Agent ran','Verified','IM submitted','Pricing co-sign','CEO approval'].map((label, i) => ({
      label,
      step: ['queued','context_built','agent_ran','verified','submitted','cosign_pricing','awaiting_approval'][i],
      meta: ['workflow.start','SKU snapshot','vault_action_agent v2.1','3 / 3 sourced','Asha submitted','PL · review','CEO sign'][i],
      time: ['07:42','07:42','07:42','07:42','08:00','now','—'][i],
      state: i < 5 ? 'done' : i === 5 ? 'now' : 'pending',
    })),
    claims: [
      { text: 'Pune cohort cooled 14 % over 21 d · this SKU has no demand signal.', source: 'sales.read',     receipt: 'rcp-cs02 / claim 1' },
      { text: '15 % reprice drops margin to 26.4 % · 5.6 pp below policy floor.',     source: 'price.calculate', receipt: 'rcp-cs02 / claim 2' },
      { text: 'Holding 30 more days projects only 12 % chance of organic clearance.', source: 'price.calculate', receipt: 'rcp-cs02 / claim 3' },
    ],
    receipts: [
      { tool: 'sql.query',       scope: 'sales.read',     id: 'tool-receipt-pl-4' },
      { tool: 'price.calculate', scope: 'deterministic',  id: 'tool-receipt-pl-5' },
      { tool: 'wiki.lookup',     scope: 'wiki.read',      id: 'tool-receipt-pl-6' },
    ],
    math: [
      { expr: 'margin_after = (price × 0.85 − cost) / (price × 0.85)', value: '26.4 %' },
      { expr: 'ceiling_check = 26.4 % >= 32 %',                        value: 'FAIL · 5.6 pp below floor' },
      { expr: 'unlock = price × 0.15',                                  value: '₹1,20,000' },
    ],
  },
  {
    id: 'rcp-cs03', sourceModule: 'orbit', sourceRunId: 'rcp-44d4',
    type: 'ceiling_change', mod: 'orbit',
    stamp: 'Verified · Orbit ceiling-policy proposal',
    status: 'pending', statusLabel: 'Awaiting Pricing co-sign',
    runId: 'rcp-cs03', runVersion: 'v2', runWhen: '2 h ago',
    title: 'Raise ceiling by + 2 pp for diamond-heavy SKUs · supply shortage',
    reasoning: 'Two primary vendors confirm 18 % rough shortage. Temporary +2 pp ceiling flexibility on 142 SKUs lets us preserve margin against rising cost basis.',
    submittedBy: 'Priya · HoM',
    stats: [
      { label: 'Affected SKUs',  value: '142' },
      { label: 'Ceiling Δ',      value: '+ 2 pp' },
      { label: 'Margin Δ proj',  value: '+ 0.3 %', color: 'success' },
      { label: 'Validity',       value: '60 d' },
    ],
    confidence: 4, confidenceLabel: 'Verified',
    ceilingCheck: 'policy_change',
    chain: [
      { who: 'Auto · evidence sweep', meta: '4 / 4 claims sourced',                  state: 'done' },
      { who: 'Priya · HoM',           meta: 'Drafted v2 · submitted 2 h ago',         state: 'done' },
      { who: 'You · Pricing Lead',    meta: 'Awaits co-sign on policy change',         state: 'now' },
      { who: 'CEO',                   meta: 'Final approval · policy edit',            state: 'pending' },
      { who: 'CONNECT · PRICE engine', meta: 'Ceiling delta applied on approval',     state: 'pending' },
    ],
    workflow: ['Queued','Context built','Agent ran','Verified','HoM submitted','Pricing co-sign','CEO approval'].map((label, i) => ({
      label,
      step: ['queued','context_built','agent_ran','verified','submitted','cosign_pricing','awaiting_approval'][i],
      meta: ['workflow.start','supply feed','orbit_brief_agent v2.1','4 / 4 sourced','HoM submitted','PL · review','CEO sign'][i],
      time: ['07:40','07:40','07:40','07:40','07:55','now','—'][i],
      state: i < 5 ? 'done' : i === 5 ? 'now' : 'pending',
    })),
    claims: [
      { text: 'Vendor A: 17 % rough drop confirmed · primary on 78 SKUs.',          source: 'connect.vendor', receipt: 'rcp-cs03 / claim 1' },
      { text: 'Vendor B: 19 % rough drop confirmed · primary on 64 SKUs.',          source: 'connect.vendor', receipt: 'rcp-cs03 / claim 2' },
      { text: '142 SKUs total exposure · weighted-cost +1.7 % projected.',           source: 'price.calculate', receipt: 'rcp-cs03 / claim 3' },
      { text: '+ 2 pp ceiling change keeps weighted margin at + 0.3 % delta.',       source: 'price.calculate', receipt: 'rcp-cs03 / claim 4' },
    ],
    receipts: [
      { tool: 'connect.vendor',   scope: 'partner.read',    id: 'tool-receipt-pl-7' },
      { tool: 'sql.query',        scope: 'inventory.read',  id: 'tool-receipt-pl-8' },
      { tool: 'price.calculate',  scope: 'deterministic',   id: 'tool-receipt-pl-9' },
      { tool: 'wiki.lookup',      scope: 'wiki.read',       id: 'tool-receipt-pl-10' },
    ],
    math: [
      { expr: 'cost_delta_weighted = Σ(sku_diamond_pct × rough_drop)', value: '+ 1.7 %' },
      { expr: 'margin_after_ceiling_raise',                            value: '+ 0.3 %' },
      { expr: 'policy.ceiling_max',                                     value: '0.34 (was 0.32)' },
    ],
  },
];


/* ============================================================
   KRAFT BRIEFS · the studio's inbound work queue (Studio OS)
   Briefs arrive from HOM (trends), VAULT (remakes), ORBIT (signals),
   and the CEO (strategic). Each is a first-class object the designer
   triages → accepts → designs → submits, with a feedback loop home.
   Lifecycle: new → accepted → in_progress → submitted →
              (approved → in_production) | changes_requested | parked
   ============================================================ */
const SEED_KRAFT_BRIEFS = [
  {
    id: 'brf-2041', title: 'Rose-gold minimal line for under-30 segment',
    intent: 'Create 1 hero direction + variants for a light, minimal rose-gold line aimed at the under-30 buyer. Everyday wearable, gift-priced.',
    source: { module: 'orbit', role: 'hom', person: 'Priya Shah' },
    origin: { type: 'signal', refId: 'ORB-2255', label: 'Minimal settings +18% · North America' },
    constraints: { pieceType: 'Pendant', metal: 'Rose gold', karat: '18k', weightCeilingG: 4, stone: 'Diamond', motif: 'Minimal', occasion: 'Daily / gift', budget: 45000, currency: '₹' },
    references: [{ kind: 'note', label: 'Match the Orbit "quiet luxury" mood; avoid heavy bridal cues.' }],
    priority: 'high', dueDays: 4, createdAt: '40 min ago', assignee: 'Vikram',
    status: 'new', sessionId: null, launchPackId: null,
    thread: [{ who: 'Priya Shah', role: 'hom', at: '40 min ago', text: 'Sending this from the North America minimal signal — we want a starter line we can scale into studs + bands later.' }],
    history: [{ state: 'new', at: '40 min ago' }],
  },
  {
    id: 'brf-2039', title: 'Remake: Victorian necklace set → current taste',
    intent: 'The Victorian set is 284-day deadstock (₹4.8L gold + stones recoverable). Redesign into a sellable minimal/contemporary line; preserve stone count where possible.',
    source: { module: 'vault', role: 'inventory', person: 'Asha Iyer' },
    origin: { type: 'sku', refId: 'SKU-00471', label: 'Victorian necklace set · aged 284 d' },
    constraints: { pieceType: 'Necklace', metal: 'Yellow gold', karat: '22k', weightCeilingG: 38, stone: 'Diamond', motif: 'Contemporary', occasion: 'Occasion', budget: 480000, currency: '₹' },
    references: [{ kind: 'note', label: 'Reclaim value verified by Price. Studio capacity confirmed.' }],
    priority: 'mid', dueDays: 9, createdAt: '3 h ago', assignee: 'Vikram',
    status: 'new', sessionId: null, launchPackId: null,
    thread: [{ who: 'Asha Iyer', role: 'inventory', at: '3 h ago', text: 'Recovery play — anything sellable beats melting. Keep it under the listed value.' }],
    history: [{ state: 'new', at: '3 h ago' }],
  },
  {
    id: 'brf-2036', title: 'North America custom capsule — peacock-led',
    intent: 'North America custom demand +23%. Need a heritage-inspired ceremonial necklace concept, heirloom feel but lighter. Peacock motif welcome.',
    source: { module: 'orbit', role: 'hom', person: 'Priya Shah' },
    origin: { type: 'signal', refId: 'ORB-2241', label: 'North America custom +23% QoQ' },
    constraints: { pieceType: 'Necklace', metal: 'Yellow gold', karat: '22k', weightCeilingG: 60, stone: 'Diamond', motif: 'Peacock', occasion: 'Bridal', budget: 500000, currency: '₹' },
    references: [{ kind: 'note', label: 'Tie to the heritage-inspired custom necklace exploration already in progress.' }],
    priority: 'high', dueDays: 6, createdAt: 'Yesterday', assignee: 'Vikram',
    status: 'in_progress', sessionId: 's-bridal-haram', launchPackId: null,
    thread: [
      { who: 'Priya Shah', role: 'hom', at: 'Yesterday', text: 'Lighter than the mother\'s set — the buyer is younger.' },
      { who: 'Vikram', role: 'designer', at: 'Yesterday', text: 'Accepted — exploring 4 peacock directions now.' },
    ],
    history: [{ state: 'new', at: 'Yesterday' }, { state: 'accepted', at: 'Yesterday' }, { state: 'in_progress', at: 'Yesterday' }],
  },
  {
    id: 'brf-2030', title: 'Festive flagship collection',
    intent: 'Strategic: a 6-piece festive flagship to anchor the Q4 campaign. High-karat, statement, but manufacturable at scale.',
    source: { module: 'admin', role: 'ceo', person: 'Rohan Patel' },
    origin: { type: 'strategic', refId: 'INIT-Q4', label: 'Q4 festive initiative' },
    constraints: { pieceType: 'Mixed', metal: 'Yellow gold', karat: '22k', weightCeilingG: 80, stone: 'Diamond', motif: 'Temple', occasion: 'Festive', budget: 1200000, currency: '₹' },
    references: [{ kind: 'note', label: 'CEO priority. Coordinate with merchandising on the campaign story.' }],
    priority: 'high', dueDays: 21, createdAt: '2 d ago', assignee: 'Vikram',
    status: 'new', sessionId: null, launchPackId: null,
    thread: [{ who: 'Rohan Patel', role: 'ceo', at: '2 d ago', text: 'Make it the centerpiece. I want options to review by month-end.' }],
    history: [{ state: 'new', at: '2 d ago' }],
  },
  {
    id: 'brf-2025', title: "Men's signet refresh · 22k",
    intent: 'Refresh the signet line with monogram-ready faces, comfort-fit. 4 directions submitted for sign-off.',
    source: { module: 'orbit', role: 'hom', person: 'Priya Shah' },
    origin: { type: 'trend', refId: 'TR-118', label: "Men's gold +9%" },
    constraints: { pieceType: 'Ring', metal: 'Yellow gold', karat: '22k', weightCeilingG: 14, stone: 'Gold only', motif: 'Signet', occasion: 'Daily', budget: 90000, currency: '₹' },
    references: [],
    priority: 'mid', dueDays: 2, createdAt: '2 d ago', assignee: 'Vikram',
    status: 'submitted', sessionId: 's-mens-band', launchPackId: 'rcp-lp-8f12',
    thread: [{ who: 'Vikram', role: 'designer', at: '5 h ago', text: 'Submitted 1 starred direction for CEO sign-off.' }],
    history: [{ state: 'new', at: '2 d ago' }, { state: 'accepted', at: '2 d ago' }, { state: 'in_progress', at: '1 d ago' }, { state: 'submitted', at: '5 h ago' }],
  },
  {
    id: 'brf-2018', title: 'Light daily-wear pendant — diamond-set',
    intent: 'Under-6g 18k pendant, diamond-set. Submitted; CEO asked for a lighter option.',
    source: { module: 'orbit', role: 'hom', person: 'Priya Shah' },
    origin: { type: 'trend', refId: 'TR-104', label: 'Everyday diamond demand' },
    constraints: { pieceType: 'Pendant', metal: 'Yellow gold', karat: '18k', weightCeilingG: 6, stone: 'Diamond', motif: 'Solitaire', occasion: 'Daily', budget: 60000, currency: '₹' },
    references: [],
    priority: 'mid', dueDays: 1, createdAt: '3 d ago', assignee: 'Vikram',
    status: 'changes_requested', sessionId: 's-light-pendant', launchPackId: 'rcp-lp-90c1',
    thread: [
      { who: 'Vikram', role: 'designer', at: 'Yesterday', text: 'Submitted 2 starred directions.' },
      { who: 'Rohan Patel', role: 'ceo', at: '2 h ago', text: 'Love the floating solitaire — can we get it under 5g without losing presence?' },
    ],
    history: [{ state: 'new', at: '3 d ago' }, { state: 'accepted', at: '3 d ago' }, { state: 'submitted', at: 'Yesterday' }, { state: 'changes_requested', at: '2 h ago' }],
  },
  {
    id: 'brf-2009', title: 'Minimal diamond studs — North America',
    intent: 'A minimal stud line to ride the North America minimal trend. Approved and moving to production.',
    source: { module: 'orbit', role: 'hom', person: 'Priya Shah' },
    origin: { type: 'signal', refId: 'ORB-2255', label: 'Minimal settings +18% · North America' },
    constraints: { pieceType: 'Earring', metal: 'White gold', karat: '18k', weightCeilingG: 5, stone: 'Diamond', motif: 'Minimal', occasion: 'Daily', budget: 70000, currency: '₹' },
    references: [],
    priority: 'low', dueDays: -2, createdAt: '6 d ago', assignee: 'Vikram',
    status: 'in_production', sessionId: null, launchPackId: 'rcp-lp-7711',
    thread: [{ who: 'Rohan Patel', role: 'ceo', at: '4 d ago', text: 'Approved — route to manufacturing.' }],
    history: [{ state: 'new', at: '6 d ago' }, { state: 'submitted', at: '5 d ago' }, { state: 'approved', at: '4 d ago' }, { state: 'in_production', at: '4 d ago' }],
  },
  {
    id: 'brf-2002', title: 'Heritage-inspired gifting capsule — North America',
    intent: 'Explore a heritage-inspired gifting line for the North America market. Parked pending budget sign-off.',
    source: { module: 'orbit', role: 'hom', person: 'Priya Shah' },
    origin: { type: 'trend', refId: 'TR-097', label: 'Heritage motif interest · North America' },
    constraints: { pieceType: 'Necklace', metal: 'Yellow gold', karat: '22k', weightCeilingG: 70, stone: 'Ruby', motif: 'Heritage', occasion: 'Festive', budget: 900000, currency: '₹' },
    references: [],
    priority: 'low', dueDays: 14, createdAt: '1 w ago', assignee: 'Vikram',
    status: 'parked', sessionId: null, launchPackId: null,
    thread: [{ who: 'Vikram', role: 'designer', at: '5 d ago', text: 'Parked — revisit after Q4 festive budget is confirmed.' }],
    history: [{ state: 'new', at: '1 w ago' }, { state: 'parked', at: '5 d ago' }],
  },
];

const LOCAL_GPT_KRAFT_RECOVERY_SAMPLE = {
  workflow: 'kraft_recovery_draft',
  inputRef: 'vault.rec-remake',
  context: {
    inventorySituation: 'Victorian necklace set has aged 280+ days in North America with near-zero velocity.',
    designOpportunity: 'Remake recoverable stones and gold into a minimal contemporary line for North America.',
    recoveryGoal: '+$480K expected recovery without presenting the draft as an approved action.',
    constraints: [
      'Keep the recommendation reversible until CEO approval.',
      'Call out evidence that must be attached before execution.',
      'Use jewellery operations language suitable for KRAFT and VAULT.',
    ],
  },
};

const localGptRouteEndpoint = (route) => {
  const params = typeof window !== 'undefined' ? new URLSearchParams(window.location.search) : null;
  const portParam = params?.get('localGptPort') || '8787';
  const port = /^\d{2,5}$/.test(portParam) ? portParam : '8787';
  return `http://127.0.0.1:${port}/api/local-gpt/${route}`;
};
const localGptEndpoint = () => localGptRouteEndpoint('kraft-recovery-draft');
const localGptKraftPromptEnhanceEndpoint = () => localGptRouteEndpoint('kraft-prompt-enhance');

const compactRecoveryRecommendation = (rec = {}) => ({
  id: rec.id || LOCAL_GPT_KRAFT_RECOVERY_SAMPLE.inputRef,
  type: rec.type || 'remake',
  title: rec.title || 'Remake ageing jewellery inventory',
  reason: rec.reason || LOCAL_GPT_KRAFT_RECOVERY_SAMPLE.context.inventorySituation,
  recovery: rec.recovery || LOCAL_GPT_KRAFT_RECOVERY_SAMPLE.context.recoveryGoal,
  confidence: rec.confidence,
  market: rec.market,
  category: rec.category,
  metalType: rec.metalType,
  ageBand: rec.ageBand,
  trendAlign: rec.trendAlign,
  metrics: rec.metrics || [],
  evidencePoints: rec.evidence?.points?.map(([text]) => text) || [],
});

const requestLocalKraftRecoveryDraft = async (rec) => {
  const endpoint = localGptEndpoint();
  let response;
  try {
    response = await fetch(endpoint, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        workflow: LOCAL_GPT_KRAFT_RECOVERY_SAMPLE.workflow,
        recommendation: compactRecoveryRecommendation(rec),
        context: LOCAL_GPT_KRAFT_RECOVERY_SAMPLE.context,
      }),
    });
  } catch (e) {
    const err = new Error(`Local GPT server is not reachable at ${endpoint}. Start it with: node scripts/local-gpt-server.mjs`);
    err.code = 'local_gpt_unreachable';
    throw err;
  }

  let payload = null;
  try {
    payload = await response.json();
  } catch (e) {
    const err = new Error('Local GPT server returned a non-JSON response.');
    err.code = 'local_gpt_bad_response';
    err.status = response.status;
    throw err;
  }

  if (!response.ok || payload?.ok === false) {
    const err = new Error(payload?.error?.message || `Local GPT request failed with HTTP ${response.status}.`);
    err.code = payload?.error?.code || 'local_gpt_request_failed';
    err.status = response.status;
    throw err;
  }

  return payload;
};

const requestLocalKraftPromptEnhanceDraft = async ({
  roughPrompt,
  regionMode = 'usa-north-america',
  category = 'rings',
  categoryLabel = '',
  channelProfile = '',
  categoryDesignNotes = [],
  variationAxes = [],
  cadRhinoNotes = [],
  customerSegment = 'everyday-gifting',
  priceBand = 'accessible-fine',
  marginTarget = '35-45%',
  metal = '',
  stone = '',
  sessionId = '',
  briefTitle = '',
  constraints = null,
} = {}) => {
  const endpoint = localGptKraftPromptEnhanceEndpoint();
  let response;
  try {
    response = await fetch(endpoint, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        workflow: 'kraft_prompt_enhance',
        schemaVersion: 'JewelleryDesignBrief.v1',
        input: {
          roughPrompt,
          regionMode,
          category,
          categoryLabel,
          channelProfile,
          categoryDesignNotes,
          variationAxes,
          cadRhinoNotes,
          customerSegment,
          priceBand,
          marginTarget,
          metal,
          stone,
          sessionId,
          briefTitle,
          constraints,
        },
        guardrails: {
          draftOnly: true,
          noApprovalClaim: true,
          noCadAutomationClaim: true,
          northAmericaV1Only: true,
          noEuAsiaRegionModes: true,
          noBrandCopyProviderPrompts: true,
          neutralChannelProfilesOnly: true,
        },
      }),
    });
  } catch (e) {
    const err = new Error(`Local GPT server is not reachable at ${endpoint}. Start it with: node scripts/local-gpt-server.mjs`);
    err.code = 'local_gpt_unreachable';
    err.endpoint = endpoint;
    throw err;
  }

  let payload = null;
  try {
    payload = await response.json();
  } catch (e) {
    const err = new Error('Local GPT server returned a non-JSON response.');
    err.code = 'local_gpt_bad_response';
    err.status = response.status;
    err.endpoint = endpoint;
    throw err;
  }

  if (!response.ok || payload?.ok === false) {
    const err = new Error(payload?.error?.message || `Local GPT request failed with HTTP ${response.status}.`);
    err.code = payload?.error?.code || 'local_gpt_request_failed';
    err.status = response.status;
    err.endpoint = endpoint;
    throw err;
  }

  return payload;
};


Object.assign(window.K, {
  SEED_DECISIONS, SEED_ACTIVITY, CANONICAL_WORKFLOW,
  SEED_HOM_DRAFTS, SEED_SIGNALS, SEED_OPPORTUNITIES,
  SEED_VAULT_ITEMS, SEED_VAULT_ACTIONS,
  SEED_PRICE_RATES, SEED_PRICE_QUOTES, SEED_PRICE_MARGIN_RISK,
  SEED_PRICING_COSIGN_QUEUE,
  SEED_KRAFT_BRIEFS,
  LOCAL_GPT_KRAFT_RECOVERY_SAMPLE,
  localGptEndpoint,
  localGptKraftPromptEnhanceEndpoint,
  requestLocalKraftRecoveryDraft,
  requestLocalKraftPromptEnhanceDraft,
});
