import type {MessagePart} from '@/features/loyaly-ai/types/chat';

/**
 * Stand-in assistant answers, until the model endpoint exists.
 *
 * Every reply is markdown that exercises a different renderer path — a table,
 * a list, a code block, plain prose — because a chat surface that has only
 * ever rendered one paragraph is a chat surface whose table styling is
 * untested. These are fixtures in the same sense as the dashboard's: server
 * -side, replaced wholesale by the real thing, and never imported by a
 * component.
 */

interface ReplyTemplate {
  /** Lowercased substrings that select this reply. */
  match: string[];
  parts: MessagePart[];
}

const REPLIES: ReplyTemplate[] = [
  {
    match: ['report', 'today', 'summary', 'sales'],
    parts: [
      {
        type: 'report',
        title: "Today's Business Performance Report",
        summary:
          "Network total revenue reached **₹3.4L** today (+2.8% vs yesterday). **Indiranagar Flagship** led footfall conversion at 23.8%, while **Whitefield Main** experienced an evening conversion slowdown due to staff coverage.",
        kpis: [
          {
            id: 'rev',
            title: 'Daily Revenue',
            value: '₹3,40,000',
            trend: '+2.8%',
            trendDirection: 'up',
            iconName: 'revenue',
            sparkline: [2.8, 3.1, 2.9, 3.2, 3.4],
          },
          {
            id: 'footfall',
            title: 'Total Visitors',
            value: '1,284',
            trend: '+4.2%',
            trendDirection: 'up',
            iconName: 'visitors',
            sparkline: [1150, 1200, 1180, 1240, 1284],
          },
          {
            id: 'orders',
            title: 'Completed Orders',
            value: '276',
            trend: '-1.1%',
            trendDirection: 'down',
            iconName: 'purchases',
            sparkline: [290, 285, 280, 278, 276],
          },
          {
            id: 'lyt',
            title: 'LYTs Issued',
            value: '34,100',
            trend: '+6.0%',
            trendDirection: 'up',
            iconName: 'lyt',
            sparkline: [28000, 30000, 31500, 32000, 34100],
          },
        ],
        charts: [
          {
            title: 'Intraday Revenue & Visitors',
            subtitle: 'Hourly performance across all active outlets',
            chartType: 'area',
            xKey: 'time',
            data: [
              {time: '10:00', Revenue: 25000, Visitors: 120},
              {time: '12:00', Revenue: 62000, Visitors: 240},
              {time: '14:00', Revenue: 85000, Visitors: 310},
              {time: '16:00', Revenue: 78000, Visitors: 280},
              {time: '18:00', Revenue: 90000, Visitors: 334},
            ],
            series: [
              {key: 'Revenue', label: 'Revenue (₹)'},
              {key: 'Visitors', label: 'Footfall'},
            ],
          },
        ],
        insights: [
          {
            id: 'i1',
            type: 'growth',
            title: 'Flagship Store Outperformance',
            explanation:
              'Indiranagar Flagship generated 41% of network daily revenue on 28% of overall footfall.',
            confidence: 96,
            recommendedAction: 'Replicate flagship evening promotion strategy across Koramangala.',
          },
          {
            id: 'i2',
            type: 'opportunity',
            title: 'Evening Shift Conversion Gap',
            explanation:
              'Conversion rate dropped 4.2% after 18:00 IST at Whitefield Main due to roster gaps.',
            confidence: 91,
            recommendedAction: 'Adjust floor staff roster for 18:00 - 21:00 peak hours.',
          },
        ],
        actions: [
          {id: 'a1', label: 'Open Full Dashboard', actionType: 'open_dashboard', iconName: 'dashboard'},
          {id: 'a2', label: 'Compare Outlet Performance', actionType: 'compare_stores', iconName: 'stores'},
          {id: 'a3', label: 'Export Report CSV', actionType: 'export_csv', iconName: 'download'},
        ],
      },
    ],
  },
  {
    match: ['compare', 'store', 'outlet'],
    parts: [
      {
        type: 'report',
        title: 'Multi-Store Network Comparison (30 Days)',
        summary:
          'Comparison of 4 active outlets over the last 30 days. **Indiranagar Flagship** leads across all key metrics, while **Whitefield Main** shows significant conversion upside potential.',
        kpis: [
          {id: 'c1', title: 'Top Store Revenue', value: '₹9.1L', trend: 'Indiranagar', iconName: 'stores'},
          {id: 'c2', title: 'Network Average Conversion', value: '21.1%', trend: '+1.4%', iconName: 'conversion'},
          {id: 'c3', title: 'Outlets Tracked', value: '4 Active', iconName: 'stores'},
        ],
        tables: [
          {
            title: 'Store Performance Breakdown',
            columns: [
              {key: 'store', header: 'Store Location'},
              {key: 'visitors', header: 'Visitors', align: 'end'},
              {key: 'revenue', header: 'Revenue', align: 'end'},
              {key: 'conversion', header: 'Conversion', align: 'end'},
              {key: 'status', header: 'Status', align: 'center'},
            ],
            rows: [
              {store: 'Indiranagar Flagship', visitors: '12,400', revenue: '₹9,10,000', conversion: '23.8%', status: 'active'},
              {store: 'Koramangala 80ft', visitors: '7,800', revenue: '₹5,20,000', conversion: '21.4%', status: 'active'},
              {store: 'Jayanagar 4th Block', visitors: '6,100', revenue: '₹4,00,000', conversion: '20.9%', status: 'active'},
              {store: 'Whitefield Main', visitors: '4,200', revenue: '₹3,30,000', conversion: '18.2%', status: 'maintenance'},
            ],
          },
        ],
        insights: [
          {
            id: 'ci1',
            type: 'best_performer',
            title: 'Indiranagar Leading Network',
            explanation: '23.8% conversion rate exceeds network benchmark by 2.7 percentage points.',
            confidence: 98,
          },
          {
            id: 'ci2',
            type: 'risk',
            title: 'Whitefield Conversion Underperformance',
            explanation: 'Whitefield is 5.6 points behind flagship despite high visitor traffic per staff seat.',
            confidence: 89,
            recommendedAction: 'Conduct staff training on checkout upsell workflows.',
          },
        ],
        actions: [
          {id: 'ca1', label: 'View Stores Directory', actionType: 'compare_stores', iconName: 'stores'},
          {id: 'ca2', label: 'Download Comparison Data', actionType: 'export_csv', iconName: 'download'},
        ],
      },
    ],
  },
  {
    match: ['reward', 'lyt', 'redeem', 'loyalty'],
    parts: [
      {
        type: 'report',
        title: 'Rewards & LYT Liability Performance',
        summary:
          'Analysis of active merchant reward campaigns. High claim rates on BOGO create unredeemed liability, while **Weekend Double LYTs** drives the highest actual redemption velocity.',
        kpis: [
          {id: 'r1', title: 'Total Claims', value: '1,442', trend: '+14%', iconName: 'lyt'},
          {id: 'r2', title: 'Redemption Rate', value: '54.2%', trend: '+3.1%', iconName: 'conversion'},
          {id: 'r3', title: 'Outstanding LYTs', value: '1.2L LYTs', trend: '₹1.2L liability', iconName: 'lyt'},
        ],
        tables: [
          {
            title: 'Campaign Performance Summary',
            columns: [
              {key: 'campaign', header: 'Reward Campaign'},
              {key: 'claims', header: 'Total Claims', align: 'end'},
              {key: 'redemption', header: 'Redemption Rate', align: 'end'},
              {key: 'status', header: 'Status', align: 'center'},
            ],
            rows: [
              {campaign: 'Buy 1 Get 1 Free', claims: '688', redemption: '19.0%', status: 'warning'},
              {campaign: 'Combo 20% Off', claims: '420', redemption: '61.0%', status: 'active'},
              {campaign: 'Weekend Double LYTs', claims: '334', redemption: '74.0%', status: 'active'},
            ],
          },
        ],
        insights: [
          {
            id: 'ri1',
            type: 'opportunity',
            title: 'Shorten BOGO Redemption Window',
            explanation:
              '81% of BOGO claims remain unredeemed after 14 days, creating unfulfilled customer expectations and pending liability.',
            confidence: 94,
            recommendedAction: 'Reduce expiry window from 14 days to 5 days to trigger immediate store visits.',
          },
        ],
        actions: [
          {id: 'ra1', label: 'Manage Rewards & LYTs', actionType: 'view_rewards', iconName: 'lyts'},
          {id: 'ra2', label: 'Export Redemption Log', actionType: 'export_csv', iconName: 'download'},
        ],
      },
    ],
  },
  {
    match: ['staff', 'team', 'attendance', 'roster'],
    parts: [
      {
        type: 'report',
        title: 'Staff Roster & Productivity Leaderboard',
        summary:
          'Current roster status: **35 of 49** staff active on floor. **Sneha R** leads network productivity with 312 completed transactions and a 94 performance score.',
        kpis: [
          {id: 'st1', title: 'Active Floor Staff', value: '35 / 49', trend: '14 Absent', iconName: 'staff'},
          {id: 'st2', title: 'Network Avg Score', value: '88.4', trend: '+2.1', iconName: 'leaderboard'},
          {id: 'st3', title: 'Total Shift Txns', value: '1,240', iconName: 'purchases'},
        ],
        tables: [
          {
            title: 'Top Staff Leaderboard',
            columns: [
              {key: 'name', header: 'Staff Member'},
              {key: 'store', header: 'Assigned Outlet'},
              {key: 'txns', header: 'Transactions', align: 'end'},
              {key: 'score', header: 'Score', align: 'end'},
              {key: 'status', header: 'Shift Status', align: 'center'},
            ],
            rows: [
              {name: 'Sneha R', store: 'Indiranagar Flagship', txns: '312', score: '94', status: 'active'},
              {name: 'Rohit K', store: 'Koramangala 80ft', txns: '287', score: '91', status: 'active'},
              {name: 'Ravi M', store: 'Jayanagar 4th Block', txns: '264', score: '88', status: 'active'},
              {name: 'Priya Sharma', store: 'Whitefield Main', txns: '198', score: '82', status: 'active'},
            ],
          },
        ],
        insights: [
          {
            id: 'sti1',
            type: 'risk',
            title: 'Whitefield Roster Shortage',
            explanation: 'Absence is concentrated at Whitefield Main (4 staff members missing during peak hours).',
            confidence: 93,
            recommendedAction: 'Reassign 2 floaters from Koramangala shift roster.',
          },
        ],
        actions: [
          {id: 'sta1', label: 'Open Staff Roster', actionType: 'open_dashboard', iconName: 'staff'},
        ],
      },
    ],
  },
  {
    match: ['customer', 'retention', 'churn'],
    parts: [
      {
        type: 'report',
        title: 'Customer Retention & Cohort Analytics',
        summary:
          'Retention rate sits at **38% repeat customers** over 90 days with a median visit cycle of 17 days. 1,240 previously active monthly buyers are currently flagged at-risk.',
        kpis: [
          {id: 'ret1', title: '90-Day Repeat Rate', value: '38.0%', trend: '+1.8%', iconName: 'conversion'},
          {id: 'ret2', title: 'Median Visit Gap', value: '17 Days', trend: '-2 Days', iconName: 'sessions'},
          {id: 'ret3', title: 'At-Risk Customers', value: '1,240', trend: '₹2.1L Prior Spend', iconName: 'alert'},
        ],
        insights: [
          {
            id: 'reti1',
            type: 'opportunity',
            title: 'At-Risk Customer Winback Campaign',
            explanation:
              '1,240 customers who spent ₹2.1L have not visited in 45+ days. A targeted 100-LYT winback bonus will recover an estimated ₹85,000 in revenue.',
            confidence: 95,
            recommendedAction: 'Launch Automated Winback Campaign in LYT Rewards Manager.',
          },
        ],
        actions: [
          {id: 'reta1', label: 'View Rewards Manager', actionType: 'view_rewards', iconName: 'lyts'},
          {id: 'reta2', label: 'Export At-Risk Cohort CSV', actionType: 'export_csv', iconName: 'download'},
        ],
      },
    ],
  },
];

const FALLBACK: MessagePart[] = [
  {
    type: 'report',
    title: 'Loyaly AI Assistant Overview',
    summary:
      'I can generate rich business reports and insights for your **stores, sales, customer retention, staff performance, and rewards**.',
    kpis: [
      {id: 'fb1', title: 'Network Outlets', value: '4 Active', iconName: 'stores'},
      {id: 'fb2', title: 'Monthly Revenue', value: '₹14.99L', trend: '+4.8%', iconName: 'revenue'},
      {id: 'fb3', title: 'Total Customers', value: '14,250', iconName: 'visitors'},
    ],
    actions: [
      {id: 'fba1', label: 'Open Main Dashboard', actionType: 'open_dashboard', iconName: 'dashboard'},
      {id: 'fba2', label: 'Compare Stores', actionType: 'compare_stores', iconName: 'stores'},
    ],
  },
];

/** Pick the reply whose keywords the prompt matches, else the fallback. */
export function replyFor(prompt: string): MessagePart[] {
  const q = prompt.toLowerCase();
  const hit = REPLIES.find((r) => r.match.some((m) => q.includes(m)));
  return hit ? hit.parts : FALLBACK;
}
