import React, { useState } from 'react';
import { Layout } from './components/Layout';
import { Dashboard } from './components/Dashboard';
import { RequestsList } from './components/RequestsList';
import { RequestDetail } from './components/RequestDetail';
import { ClaimManagementDetail } from './components/ClaimManagementDetail';
import { WorkNoteView } from './components/WorkNoteView';
import { NewRequestWizard } from './components/NewRequestWizard';
import { ClaimManagementWizard } from './components/ClaimManagementWizard';
import { MyRequests } from './components/MyRequests';
import { ApprovalActionModal } from './components/modals/ApprovalActionModal';
import { Toaster } from './components/ui/sonner';
import { toast } from 'sonner@2.0.3';
import { CUSTOM_REQUEST_DATABASE } from './utils/customRequestDatabase';
import { CLAIM_MANAGEMENT_DATABASE } from './utils/claimManagementDatabase';

type Page = 'dashboard' | 'open-requests' | 'closed-requests' | 'my-requests' | 'request-detail' | 'work-notes' | 'new-request' | 'claim-management';

// Combined Request Database for backward compatibility
// This combines both custom and claim management requests
export const REQUEST_DATABASE: any = {
  ...CUSTOM_REQUEST_DATABASE,
  ...CLAIM_MANAGEMENT_DATABASE
};

// Legacy database - keeping for reference (will be removed in future)
const LEGACY_REQUEST_DATABASE: any = {
  // ========== TEMPLATE-BASED REQUESTS - Claim Management ==========
  'RE-REQ-2024-CM-001': {
    id: 'RE-REQ-2024-CM-001',
    title: 'Dealer Marketing Activity Claim - Diwali Festival Campaign',
    description: 'Claim request for dealer-led Diwali festival marketing campaign including showroom decoration, test ride events, customer engagement activities, and promotional merchandise distribution. Activity conducted at Royal Motors Mumbai dealership.',
    category: 'Dealer Operations',
    subcategory: 'Claim Management',
    status: 'pending',
    priority: 'standard',
    amount: 'TBD',
    slaProgress: 35,
    slaRemaining: '4 days 12 hours',
    slaEndDate: 'Oct 16, 2024 5:00 PM',
    currentStep: 1,
    totalSteps: 8,
    templateType: 'claim-management',
    templateName: 'Claim Management',
    initiator: {
      name: 'Sneha Patil',
      role: 'Regional Marketing Coordinator',
      department: 'Marketing - West Zone',
      email: 'sneha.patil@royalenfield.com',
      phone: '+91 98765 43250',
      avatar: 'SP'
    },
    department: 'Marketing - West Zone',
    createdAt: 'Oct 7, 2024 9:30 AM',
    updatedAt: 'Oct 7, 2024 9:30 AM',
    dueDate: '2024-10-16T17:00:00Z',
    conclusionRemark: '',
    claimDetails: {
      activityName: 'Diwali Festival Campaign 2024',
      activityType: 'Marketing Activity',
      activityDate: 'Oct 5, 2024',
      location: 'Mumbai, Maharashtra',
      dealerCode: 'RE-MH-001',
      dealerName: 'Royal Motors Mumbai',
      dealerEmail: 'dealer@royalmotorsmumbai.com',
      dealerPhone: '+91 98765 12345',
      requestDescription: 'Marketing campaign for Diwali festival including showroom decoration, test ride events, customer engagement activities, and promotional merchandise distribution at Royal Motors Mumbai dealership.',
      estimatedBudget: '₹2,45,000',
      periodStart: 'Oct 1, 2024',
      periodEnd: 'Oct 10, 2024'
    },
    approvalFlow: [
      {
        step: 1,
        approver: 'Royal Motors Mumbai (Dealer)',
        role: 'Dealer - Document Upload',
        status: 'pending',
        tatHours: 72,
        elapsedHours: 12,
        assignedAt: '2024-10-07T09:30:00Z',
        comment: null,
        timestamp: null,
        description: 'Dealer uploads proposal document, cost breakup, timeline for closure, and other supporting documents'
      },
      {
        step: 2,
        approver: 'Sneha Patil (Initiator)',
        role: 'Initiator Evaluation',
        status: 'waiting',
        tatHours: 48,
        elapsedHours: 0,
        assignedAt: null,
        comment: null,
        timestamp: null,
        description: 'Initiator reviews dealer documents and approves or requests modifications'
      },
      {
        step: 3,
        approver: 'System Auto-Process',
        role: 'IO Confirmation',
        status: 'waiting',
        tatHours: 1,
        elapsedHours: 0,
        assignedAt: null,
        comment: null,
        timestamp: null,
        description: 'Automatic IO (Internal Order) confirmation generated upon initiator approval'
      },
      {
        step: 4,
        approver: 'Rajesh Kumar',
        role: 'Department Lead Approval',
        status: 'waiting',
        tatHours: 72,
        elapsedHours: 0,
        assignedAt: null,
        comment: null,
        timestamp: null,
        description: 'Department head approves and blocks budget in IO for this activity'
      },
      {
        step: 5,
        approver: 'Royal Motors Mumbai (Dealer)',
        role: 'Dealer - Completion Documents',
        status: 'waiting',
        tatHours: 120,
        elapsedHours: 0,
        assignedAt: null,
        comment: null,
        timestamp: null,
        description: 'Dealer submits activity completion documents and description'
      },
      {
        step: 6,
        approver: 'Sneha Patil (Initiator)',
        role: 'Initiator Verification',
        status: 'waiting',
        tatHours: 48,
        elapsedHours: 0,
        assignedAt: null,
        comment: null,
        timestamp: null,
        description: 'Initiator verifies completion documents and can modify approved amount'
      },
      {
        step: 7,
        approver: 'System Auto-Process',
        role: 'E-Invoice Generation',
        status: 'waiting',
        tatHours: 1,
        elapsedHours: 0,
        assignedAt: null,
        comment: null,
        timestamp: null,
        description: 'Auto-generate e-invoice based on final approved amount'
      },
      {
        step: 8,
        approver: 'Meera Patel',
        role: 'Finance - Credit Note Issuance',
        status: 'waiting',
        tatHours: 48,
        elapsedHours: 0,
        assignedAt: null,
        comment: null,
        timestamp: null,
        description: 'Finance team issues credit note to dealer'
      }
    ],
    documents: [
      { name: 'Claim_Proposal_Diwali_2024.pdf', size: '1.8 MB', type: 'PDF', uploadedBy: 'Sneha Patil', uploadedAt: 'Oct 7, 2024 9:35 AM' },
      { name: 'Cost_Breakup_Detailed.xlsx', size: '450 KB', type: 'Excel', uploadedBy: 'Sneha Patil', uploadedAt: 'Oct 7, 2024 9:38 AM' },
      { name: 'Activity_Timeline.pdf', size: '320 KB', type: 'PDF', uploadedBy: 'Sneha Patil', uploadedAt: 'Oct 7, 2024 9:40 AM' }
    ],
    spectators: [
      { name: 'Arjun Menon', role: 'Brand Manager', avatar: 'AM' },
      { name: 'Finance Team', role: 'Budget Monitoring', avatar: 'FT' }
    ],
    auditTrail: [
      { type: 'created', action: 'Claim Request Created', details: 'Diwali festival campaign claim initiated using Claim Management template', user: 'Sneha Patil', timestamp: 'Oct 7, 2024 9:30 AM' },
      { type: 'assigned', action: 'Assigned to Initiator for Review', details: 'Initiator to review and confirm all claim details', user: 'System', timestamp: 'Oct 7, 2024 9:31 AM' }
    ],
    tags: ['claim-management', 'dealer-activity', 'marketing', 'diwali-campaign', 'template']
  },

  // ========== OPEN/PENDING REQUESTS - High Priority & Current ==========
  'RE-REQ-2024-001': {
    id: 'RE-REQ-2024-001',
    title: 'Himalayan 450 Launch Campaign - Digital Media Blitz',
    description: 'Comprehensive digital marketing campaign for Himalayan 450 adventure motorcycle launch. Includes social media campaigns, influencer partnerships, performance marketing, content creation, and digital advertising across platforms. Target: Reach 10M adventure enthusiasts across India.',
    category: 'Marketing & Campaigns',
    subcategory: 'Digital Marketing',
    status: 'pending',
    priority: 'express',
    amount: '₹3,75,00,000',
    slaProgress: 65,
    slaRemaining: '8 hours 45 minutes',
    slaEndDate: 'Oct 9, 2024 5:00 PM',
    currentStep: 1,
    totalSteps: 3,
    initiator: {
      name: 'Priya Sharma',
      role: 'Senior Digital Marketing Manager',
      department: 'Marketing',
      email: 'priya.sharma@royalenfield.com',
      phone: '+91 98765 43210',
      avatar: 'PS'
    },
    department: 'Marketing',
    createdAt: 'Oct 6, 2024 10:30 AM',
    updatedAt: 'Oct 7, 2024 2:15 PM',
    dueDate: '2024-10-09T17:00:00Z',
    conclusionRemark: '',
    approvalFlow: [
      {
        step: 1,
        approver: 'Rajesh Kumar',
        role: 'Marketing Director - India',
        status: 'pending',
        tatHours: 24,
        elapsedHours: 22,
        assignedAt: '2024-10-06T10:30:00Z',
        comment: null,
        timestamp: null,
        reminderHistory: [
          { type: 'auto', sentAt: 'Oct 7, 2024 8:30 AM', sentBy: 'System' },
          { type: 'manual', sentAt: 'Oct 7, 2024 2:15 PM', sentBy: 'Priya Sharma' }
        ]
      },
      {
        step: 2,
        approver: 'Meera Patel',
        role: 'VP Finance & Strategy',
        status: 'waiting',
        tatHours: 48,
        elapsedHours: 0,
        assignedAt: null,
        comment: null,
        timestamp: null
      },
      {
        step: 3,
        approver: 'Vinod Dasari',
        role: 'Chief Executive Officer',
        status: 'waiting',
        tatHours: 24,
        elapsedHours: 0,
        assignedAt: null,
        comment: null,
        timestamp: null
      }
    ],
    documents: [
      { name: 'Digital_Campaign_Strategy_2024.pdf', size: '2.4 MB', type: 'PDF', uploadedBy: 'Priya Sharma', uploadedAt: 'Oct 6, 2024 10:45 AM' },
      { name: 'Budget_Breakdown_Q4.xlsx', size: '850 KB', type: 'Excel', uploadedBy: 'Priya Sharma', uploadedAt: 'Oct 6, 2024 11:00 AM' },
      { name: 'ROI_Projections_H450.pptx', size: '3.2 MB', type: 'PowerPoint', uploadedBy: 'Arjun Menon', uploadedAt: 'Oct 6, 2024 2:30 PM' },
      { name: 'Competitor_Analysis_Report.pdf', size: '1.8 MB', type: 'PDF', uploadedBy: 'Priya Sharma', uploadedAt: 'Oct 7, 2024 9:15 AM' }
    ],
    spectators: [
      { name: 'Arjun Menon', role: 'Brand Manager', avatar: 'AM' },
      { name: 'Kavya Nair', role: 'Creative Director', avatar: 'KN' }
    ],
    auditTrail: [
      { type: 'created', action: 'Request Created', details: 'Initial request submitted for Himalayan 450 campaign', user: 'Priya Sharma', timestamp: 'Oct 6, 2024 10:30 AM' },
      { type: 'assigned', action: 'Assigned to Rajesh Kumar', details: 'Request forwarded to Marketing Director for review', user: 'System', timestamp: 'Oct 6, 2024 10:31 AM' },
      { type: 'updated', action: 'Documents Added', details: 'Added competitor analysis report', user: 'Priya Sharma', timestamp: 'Oct 7, 2024 9:15 AM' },
      { type: 'reminder', action: 'Reminder Sent', details: 'Automated reminder sent to current approver', user: 'System', timestamp: 'Oct 7, 2024 2:15 PM' }
    ],
    tags: ['urgent', 'product-launch', 'budget-approval', 'himalayan-450']
  },

  'RE-REQ-2024-002': {
    id: 'RE-REQ-2024-002',
    title: 'Premium Dealership Expansion - Mumbai Central',
    description: 'Establishment of flagship Royal Enfield premium dealership in Mumbai Central business district. Prime 8000 sq ft location with experience center, café, merchandise store, and premium service bay. Expected to serve 500+ customers monthly.',
    category: 'Dealer & Sales',
    subcategory: 'Premium Store Expansion',
    status: 'in-review',
    priority: 'urgent',
    amount: '₹2,45,00,000',
    slaProgress: 78,
    slaRemaining: '1 day 6 hours',
    slaEndDate: 'Oct 11, 2024 5:00 PM',
    currentStep: 2,
    totalSteps: 3,
    initiator: {
      name: 'Amit Rathi',
      role: 'Regional Sales Manager - West',
      department: 'Sales & Distribution',
      email: 'amit.rathi@royalenfield.com',
      phone: '+91 98765 43220',
      avatar: 'AR'
    },
    department: 'Sales & Distribution',
    createdAt: 'Oct 4, 2024 2:20 PM',
    updatedAt: 'Oct 7, 2024 4:30 PM',
    dueDate: '2024-10-11T17:00:00Z',
    conclusionRemark: '',
    approvalFlow: [
      {
        step: 1,
        approver: 'Sunita Nair',
        role: 'Area Sales Manager - Maharashtra',
        status: 'approved',
        tatHours: 48,
        actualHours: 31,
        assignedAt: '2024-10-04T14:20:00Z',
        comment: 'Location assessment completed. Excellent footfall potential in premium catchment area. ROI projections look strong.',
        timestamp: '2024-10-05T21:20:00Z'
      },
      {
        step: 2,
        approver: 'Vikram Singh',
        role: 'National Sales Director',
        status: 'pending',
        tatHours: 72,
        elapsedHours: 58,
        assignedAt: '2024-10-05T21:20:00Z',
        comment: null,
        timestamp: null,
        reminderHistory: [
          { type: 'auto', sentAt: 'Oct 6, 2024 9:20 PM', sentBy: 'System' },
          { type: 'manual', sentAt: 'Oct 7, 2024 11:30 AM', sentBy: 'Amit Rathi' }
        ]
      },
      {
        step: 3,
        approver: 'B. Govindarajan',
        role: 'COO - Sales & Marketing',
        status: 'waiting',
        tatHours: 48,
        elapsedHours: 0,
        assignedAt: null,
        comment: null,
        timestamp: null
      }
    ],
    documents: [
      { name: 'Location_Survey_Mumbai.pdf', size: '4.2 MB', type: 'PDF', uploadedBy: 'Amit Rathi', uploadedAt: 'Oct 4, 2024 2:30 PM' },
      { name: 'Market_Analysis_West_Region.xlsx', size: '1.5 MB', type: 'Excel', uploadedBy: 'Market Research Team', uploadedAt: 'Oct 4, 2024 3:45 PM' },
      { name: 'Dealer_Investment_Profile.pdf', size: '900 KB', type: 'PDF', uploadedBy: 'Sunita Nair', uploadedAt: 'Oct 5, 2024 10:15 AM' },
      { name: 'Premium_Store_Layout_Plan.pdf', size: '2.8 MB', type: 'PDF', uploadedBy: 'Design Team', uploadedAt: 'Oct 5, 2024 4:20 PM' }
    ],
    spectators: [
      { name: 'Ravi Shankar', role: 'Regional Manager - West', avatar: 'RS' },
      { name: 'Deepika Shah', role: 'Brand Experience Manager', avatar: 'DS' }
    ],
    auditTrail: [
      { type: 'created', action: 'Request Created', details: 'New premium dealership proposal submitted', user: 'Amit Rathi', timestamp: 'Oct 4, 2024 2:20 PM' },
      { type: 'assigned', action: 'Assigned to Sunita Nair', details: 'Forwarded to Area Sales Manager for location assessment', user: 'System', timestamp: 'Oct 4, 2024 2:21 PM' },
      { type: 'approved', action: 'Approved by Sunita Nair', details: 'Location assessment approved with positive recommendation', user: 'Sunita Nair', timestamp: 'Oct 5, 2024 9:20 PM' },
      { type: 'assigned', action: 'Assigned to Vikram Singh', details: 'Forwarded to National Sales Director for strategic review', user: 'System', timestamp: 'Oct 5, 2024 9:21 PM' }
    ],
    tags: ['dealer-expansion', 'mumbai', 'premium-store', 'flagship']
  },

  'RE-REQ-2024-003': {
    id: 'RE-REQ-2024-003',
    title: 'Critical Production Line Maintenance - Chennai Plant',
    description: 'Emergency maintenance approval for Assembly Line 3 hydraulic system failure. Production of Classic 350 and Meteor 350 models affected. Estimated 48-hour downtime without immediate intervention. Critical for meeting Q4 production targets.',
    category: 'Operations & Manufacturing',
    subcategory: 'Emergency Maintenance',
    status: 'pending',
    priority: 'express',
    amount: '₹28,50,000',
    slaProgress: 95,
    slaRemaining: '2 hours overdue',
    slaEndDate: 'Oct 6, 2024 8:00 AM',
    currentStep: 1,
    totalSteps: 1,
    initiator: {
      name: 'Senthil Kumar',
      role: 'Plant Manager - Chennai',
      department: 'Manufacturing',
      email: 'senthil.kumar@royalenfield.com',
      phone: '+91 98765 43230',
      avatar: 'SK'
    },
    department: 'Manufacturing',
    createdAt: 'Oct 5, 2024 4:45 PM',
    updatedAt: 'Oct 7, 2024 11:30 AM',
    dueDate: '2024-10-06T08:00:00Z',
    conclusionRemark: '',
    approvalFlow: [
      {
        step: 1,
        approver: 'Manoj Gupta',
        role: 'VP Manufacturing & Quality',
        status: 'pending',
        tatHours: 16,
        elapsedHours: 42,
        assignedAt: '2024-10-05T16:45:00Z',
        comment: null,
        timestamp: null,
        reminderHistory: [
          { type: 'auto', sentAt: 'Oct 6, 2024 8:45 AM', sentBy: 'System' },
          { type: 'auto', sentAt: 'Oct 6, 2024 12:00 PM', sentBy: 'System' },
          { type: 'manual', sentAt: 'Oct 6, 2024 4:30 PM', sentBy: 'Senthil Kumar' },
          { type: 'auto', sentAt: 'Oct 7, 2024 8:45 AM', sentBy: 'System' },
          { type: 'manual', sentAt: 'Oct 7, 2024 11:30 AM', sentBy: 'Plant Operations Team' }
        ]
      }
    ],
    documents: [
      { name: 'Equipment_Failure_Report_Line3.pdf', size: '3.5 MB', type: 'PDF', uploadedBy: 'Senthil Kumar', uploadedAt: 'Oct 5, 2024 5:00 PM' },
      { name: 'Maintenance_Vendor_Quote.pdf', size: '1.2 MB', type: 'PDF', uploadedBy: 'Procurement Team', uploadedAt: 'Oct 5, 2024 6:30 PM' },
      { name: 'Production_Impact_Analysis.xlsx', size: '950 KB', type: 'Excel', uploadedBy: 'Planning Team', uploadedAt: 'Oct 6, 2024 8:15 AM' },
      { name: 'Alternative_Solutions_Report.pdf', size: '1.8 MB', type: 'PDF', uploadedBy: 'Engineering Team', uploadedAt: 'Oct 6, 2024 2:45 PM' }
    ],
    spectators: [
      { name: 'Rajesh Nair', role: 'Head of Production Planning', avatar: 'RN' },
      { name: 'Kavitha Krishnan', role: 'Quality Assurance Manager', avatar: 'KK' }
    ],
    auditTrail: [
      { type: 'created', action: 'Emergency Request Created', details: 'Critical maintenance request for production line failure', user: 'Senthil Kumar', timestamp: 'Oct 5, 2024 4:45 PM' },
      { type: 'escalated', action: 'Auto-Escalated', details: 'Request auto-escalated due to emergency priority', user: 'System', timestamp: 'Oct 5, 2024 4:46 PM' },
      { type: 'reminder', action: 'Multiple Reminders Sent', details: 'Urgent reminders sent due to TAT breach', user: 'System', timestamp: 'Oct 6, 2024 12:00 PM' },
      { type: 'updated', action: 'Alternative Solutions Added', details: 'Engineering team provided alternative maintenance approaches', user: 'Engineering Team', timestamp: 'Oct 6, 2024 2:45 PM' }
    ],
    tags: ['emergency', 'production-critical', 'chennai-plant', 'overdue']
  },

  'RE-REQ-2024-004': {
    id: 'RE-REQ-2024-004',
    title: 'Vendor Partnership - Premium Engine Components',
    description: 'Strategic partnership with Mahindra Forging Limited for premium engine components supply. Multi-year contract for pistons, connecting rods, and crankshafts. Negotiated 12% cost reduction with quality improvements and faster delivery cycles.',
    category: 'Procurement & Vendors',
    subcategory: 'Strategic Partnership',
    status: 'pending',
    priority: 'standard',
    amount: '₹85,50,00,000',
    slaProgress: 25,
    slaRemaining: '5 days 14 hours',
    slaEndDate: 'Oct 18, 2024 5:00 PM',
    currentStep: 1,
    totalSteps: 4,
    initiator: {
      name: 'Arjun Reddy',
      role: 'Senior Procurement Manager',
      department: 'Supply Chain',
      email: 'arjun.reddy@royalenfield.com',
      phone: '+91 98765 43240',
      avatar: 'AR'
    },
    department: 'Supply Chain',
    createdAt: 'Oct 5, 2024 9:15 AM',
    updatedAt: 'Oct 7, 2024 3:45 PM',
    dueDate: '2024-10-18T17:00:00Z',
    conclusionRemark: '',
    approvalFlow: [
      {
        step: 1,
        approver: 'Kavitha Krishnan',
        role: 'Supply Chain Director',
        status: 'pending',
        tatHours: 72,
        elapsedHours: 54,
        assignedAt: '2024-10-05T09:15:00Z',
        comment: null,
        timestamp: null
      },
      {
        step: 2,
        approver: 'Rohit Gupta',
        role: 'Chief Operations Officer',
        status: 'waiting',
        tatHours: 96,
        elapsedHours: 0,
        assignedAt: null,
        comment: null,
        timestamp: null
      },
      {
        step: 3,
        approver: 'Siddhartha Lal',
        role: 'Executive Chairman',
        status: 'waiting',
        tatHours: 72,
        elapsedHours: 0,
        assignedAt: null,
        comment: null,
        timestamp: null
      },
      {
        step: 4,
        approver: 'Board Committee',
        role: 'Investment Committee',
        status: 'waiting',
        tatHours: 168,
        elapsedHours: 0,
        assignedAt: null,
        comment: null,
        timestamp: null
      }
    ],
    documents: [
      { name: 'Strategic_Partnership_Proposal.pdf', size: '5.2 MB', type: 'PDF', uploadedBy: 'Arjun Reddy', uploadedAt: 'Oct 5, 2024 9:30 AM' },
      { name: 'Cost_Benefit_Analysis_5Year.xlsx', size: '2.1 MB', type: 'Excel', uploadedBy: 'Finance Team', uploadedAt: 'Oct 5, 2024 11:45 AM' },
      { name: 'Vendor_Technical_Capability_Assessment.pdf', size: '3.8 MB', type: 'PDF', uploadedBy: 'Technical Team', uploadedAt: 'Oct 5, 2024 2:30 PM' },
      { name: 'Quality_Certification_Documents.pdf', size: '4.5 MB', type: 'PDF', uploadedBy: 'Quality Team', uploadedAt: 'Oct 6, 2024 10:15 AM' }
    ],
    spectators: [
      { name: 'Ravi Kumar', role: 'Head of Quality', avatar: 'RK' },
      { name: 'Priya Menon', role: 'Legal Counsel', avatar: 'PM' }
    ],
    auditTrail: [
      { type: 'created', action: 'Request Created', details: 'Strategic vendor partnership proposal submitted', user: 'Arjun Reddy', timestamp: 'Oct 5, 2024 9:15 AM' },
      { type: 'assigned', action: 'Assigned to Kavitha Krishnan', details: 'Forwarded to Supply Chain Director for evaluation', user: 'System', timestamp: 'Oct 5, 2024 9:16 AM' },
      { type: 'updated', action: 'Quality Certifications Added', details: 'Vendor quality certifications and compliance documents added', user: 'Quality Team', timestamp: 'Oct 6, 2024 10:15 AM' }
    ],
    tags: ['vendor-management', 'strategic-partnership', 'cost-optimization', 'engine-components']
  },

  // ========== CLOSED/COMPLETED REQUESTS - Approved ==========
  'RE-REQ-2024-005': {
    id: 'RE-REQ-2024-005',
    title: 'Classic 350 Heritage Edition - Limited Production',
    description: 'Limited edition Classic 350 with heritage-inspired design elements, premium finishes, and exclusive colorways. Production run of 7,500 units for festive season. Premium pricing strategy with enhanced margin targets.',
    category: 'Product Development',
    subcategory: 'Special Editions',
    status: 'approved',
    priority: 'urgent',
    amount: '₹18,75,00,000',
    slaProgress: 100,
    slaRemaining: 'Completed',
    slaEndDate: 'Oct 5, 2024 5:00 PM',
    currentStep: 3,
    totalSteps: 3,
    initiator: {
      name: 'Ananya Das',
      role: 'Senior Product Manager',
      department: 'Product Development',
      email: 'ananya.das@royalenfield.com',
      phone: '+91 98765 43250',
      avatar: 'AD'
    },
    department: 'Product Development',
    createdAt: 'Sep 28, 2024 11:00 AM',
    completedAt: 'Oct 2, 2024 3:30 PM',
    updatedAt: 'Oct 2, 2024 3:30 PM',
    dueDate: '2024-10-05T17:00:00Z',
    conclusionRemark: 'Approved for immediate production planning. Heritage Edition expected to command 15-20% premium over standard Classic 350. Production to commence November 2024 for December market launch.',
    approvalFlow: [
      {
        step: 1,
        approver: 'Karthik Raman',
        role: 'Head of Product Development',
        status: 'approved',
        tatHours: 48,
        actualHours: 22,
        assignedAt: '2024-09-28T11:00:00Z',
        comment: 'Excellent concept aligning with heritage brand positioning. Design elements are distinctive and marketable. Approved for market validation.',
        timestamp: '2024-09-29T09:00:00Z'
      },
      {
        step: 2,
        approver: 'Deepika Sharma',
        role: 'VP Sales & Marketing',
        status: 'approved',
        tatHours: 72,
        actualHours: 45,
        assignedAt: '2024-09-29T09:00:00Z',
        comment: 'Market research indicates strong demand in premium segment. Festive timing is optimal. Recommend premium pricing with exclusive dealer network.',
        timestamp: '2024-10-01T06:00:00Z'
      },
      {
        step: 3,
        approver: 'Siddhartha Lal',
        role: 'Executive Chairman',
        status: 'approved',
        tatHours: 48,
        actualHours: 57,
        assignedAt: '2024-10-01T06:00:00Z',
        comment: 'Outstanding initiative showcasing our heritage DNA. This will strengthen brand premium positioning. Proceed with production planning immediately.',
        timestamp: '2024-10-02T15:30:00Z'
      }
    ],
    documents: [
      { name: 'Heritage_Edition_Concept_Design.pdf', size: '8.5 MB', type: 'PDF', uploadedBy: 'Design Team', uploadedAt: 'Sep 28, 2024 11:15 AM' },
      { name: 'Market_Research_Premium_Segment.pptx', size: '4.2 MB', type: 'PowerPoint', uploadedBy: 'Market Research', uploadedAt: 'Sep 29, 2024 2:30 PM' },
      { name: 'Production_Feasibility_Timeline.xlsx', size: '1.8 MB', type: 'Excel', uploadedBy: 'Manufacturing', uploadedAt: 'Sep 30, 2024 10:45 AM' },
      { name: 'Premium_Pricing_Strategy.pdf', size: '2.1 MB', type: 'PDF', uploadedBy: 'Pricing Team', uploadedAt: 'Oct 1, 2024 9:15 AM' }
    ],
    spectators: [
      { name: 'Vikram Pawah', role: 'President - Global Markets', avatar: 'VP' },
      { name: 'Mario Ricci', role: 'Head of Design', avatar: 'MR' }
    ],
    auditTrail: [
      { type: 'created', action: 'Request Created', details: 'Heritage Edition product proposal submitted', user: 'Ananya Das', timestamp: 'Sep 28, 2024 11:00 AM' },
      { type: 'approved', action: 'Approved by Karthik Raman', details: 'Product development approval with design validation', user: 'Karthik Raman', timestamp: 'Sep 29, 2024 9:00 AM' },
      { type: 'approved', action: 'Approved by Deepika Sharma', details: 'Marketing approval with premium positioning strategy', user: 'Deepika Sharma', timestamp: 'Oct 1, 2024 6:00 AM' },
      { type: 'approved', action: 'Final Approval by Siddhartha Lal', details: 'Executive approval for production planning', user: 'Siddhartha Lal', timestamp: 'Oct 2, 2024 3:30 PM' },
      { type: 'completed', action: 'Request Completed', details: 'Heritage Edition approved for production', user: 'System', timestamp: 'Oct 2, 2024 3:30 PM' }
    ],
    tags: ['special-edition', 'heritage', 'approved', 'premium-positioning']
  },

  'RE-REQ-2024-006': {
    id: 'RE-REQ-2024-006',
    title: 'Advanced Manufacturing Training Initiative',
    description: 'Comprehensive skill development program for 350+ manufacturing employees across all plants. Focus on Industry 4.0 practices, lean manufacturing, quality systems, and safety protocols. Partnership with leading technical institutes.',
    category: 'Human Resources',
    subcategory: 'Training & Development',
    status: 'approved',
    priority: 'standard',
    amount: '₹1,25,00,000',
    slaProgress: 100,
    slaRemaining: 'Completed',
    slaEndDate: 'Oct 8, 2024 5:00 PM',
    currentStep: 2,
    totalSteps: 2,
    initiator: {
      name: 'Rekha Joshi',
      role: 'Head of Learning & Development',
      department: 'Human Resources',
      email: 'rekha.joshi@royalenfield.com',
      phone: '+91 98765 43260',
      avatar: 'RJ'
    },
    department: 'Human Resources',
    createdAt: 'Sep 25, 2024 1:30 PM',
    completedAt: 'Oct 1, 2024 11:15 AM',
    updatedAt: 'Oct 1, 2024 11:15 AM',
    dueDate: '2024-10-08T17:00:00Z',
    conclusionRemark: 'Training program approved with enhanced focus on digital manufacturing skills. Expected to improve productivity by 15% and reduce quality issues by 25%. Implementation to begin November 2024.',
    approvalFlow: [
      {
        step: 1,
        approver: 'Rajesh Nair',
        role: 'Chief Human Resources Officer',
        status: 'approved',
        tatHours: 72,
        actualHours: 48,
        assignedAt: '2024-09-25T13:30:00Z',
        comment: 'Essential investment in workforce capability. Training modules align with manufacturing excellence goals. Budget allocation is justified.',
        timestamp: '2024-09-27T13:30:00Z'
      },
      {
        step: 2,
        approver: 'Lalit Malik',
        role: 'Chief Operating Officer',
        status: 'approved',
        tatHours: 96,
        actualHours: 94,
        assignedAt: '2024-09-27T13:30:00Z',
        comment: 'Strategic investment in human capital. This will enhance our manufacturing competitiveness. Approved for immediate implementation.',
        timestamp: '2024-10-01T11:15:00Z'
      }
    ],
    documents: [
      { name: 'Training_Curriculum_Detailed.pdf', size: '6.2 MB', type: 'PDF', uploadedBy: 'L&D Team', uploadedAt: 'Sep 25, 2024 1:45 PM' },
      { name: 'Institute_Partnership_Agreements.pdf', size: '3.8 MB', type: 'PDF', uploadedBy: 'Legal Team', uploadedAt: 'Sep 26, 2024 10:30 AM' },
      { name: 'Training_Budget_ROI_Analysis.xlsx', size: '1.5 MB', type: 'Excel', uploadedBy: 'Finance Team', uploadedAt: 'Sep 26, 2024 3:45 PM' },
      { name: 'Implementation_Timeline_2024.pdf', size: '2.1 MB', type: 'PDF', uploadedBy: 'Rekha Joshi', uploadedAt: 'Sep 27, 2024 9:20 AM' }
    ],
    spectators: [
      { name: 'Manufacturing Heads', role: 'Plant Managers', avatar: 'MH' },
      { name: 'Skills Council', role: 'Industry Partners', avatar: 'SC' }
    ],
    auditTrail: [
      { type: 'created', action: 'Request Created', details: 'Advanced manufacturing training program proposal', user: 'Rekha Joshi', timestamp: 'Sep 25, 2024 1:30 PM' },
      { type: 'approved', action: 'Approved by Rajesh Nair', details: 'HR approval with budget validation', user: 'Rajesh Nair', timestamp: 'Sep 27, 2024 1:30 PM' },
      { type: 'approved', action: 'Final Approval by Lalit Malik', details: 'COO approval for implementation', user: 'Lalit Malik', timestamp: 'Oct 1, 2024 11:15 AM' },
      { type: 'completed', action: 'Request Completed', details: 'Training program approved for rollout', user: 'System', timestamp: 'Oct 1, 2024 11:15 AM' }
    ],
    tags: ['hr', 'training', 'manufacturing', 'approved', 'skill-development']
  },

  'RE-REQ-2024-007': {
    id: 'RE-REQ-2024-007',
    title: 'International Market Expansion - Southeast Asia',
    description: 'Strategic expansion into Thailand, Vietnam, and Indonesia markets. Includes market entry strategy, local partnerships, distribution network setup, and regulatory compliance. Target: 5,000 units in Year 1.',
    category: 'Business Development',
    subcategory: 'Market Expansion',
    status: 'approved',
    priority: 'urgent',
    amount: '₹45,80,00,000',
    slaProgress: 100,
    slaRemaining: 'Completed',
    slaEndDate: 'Sep 30, 2024 5:00 PM',
    currentStep: 4,
    totalSteps: 4,
    initiator: {
      name: 'Vikram Pawah',
      role: 'President - International Business',
      department: 'Global Markets',
      email: 'vikram.pawah@royalenfield.com',
      phone: '+91 98765 43270',
      avatar: 'VP'
    },
    department: 'Global Markets',
    createdAt: 'Sep 10, 2024 10:00 AM',
    completedAt: 'Sep 28, 2024 4:45 PM',
    updatedAt: 'Sep 28, 2024 4:45 PM',
    dueDate: '2024-09-30T17:00:00Z',
    conclusionRemark: 'Southeast Asia expansion approved with phased approach. Thailand launch in Q1 2025 followed by Vietnam and Indonesia. Local assembly considerations approved for long-term cost optimization.',
    approvalFlow: [
      {
        step: 1,
        approver: 'Deepika Sharma',
        role: 'VP Sales & Marketing',
        status: 'approved',
        tatHours: 72,
        actualHours: 58,
        assignedAt: '2024-09-10T10:00:00Z',
        comment: 'Market research shows strong potential for Royal Enfield in adventure segment. Brand positioning strategy is well-defined.',
        timestamp: '2024-09-12T20:00:00Z'
      },
      {
        step: 2,
        approver: 'Lalit Malik',
        role: 'COO - Global Operations',
        status: 'approved',
        tatHours: 96,
        actualHours: 78,
        assignedAt: '2024-09-12T20:00:00Z',
        comment: 'Supply chain and manufacturing feasibility confirmed. Local partnership strategy is sound.',
        timestamp: '2024-09-16T02:00:00Z'
      },
      {
        step: 3,
        approver: 'Vinod Dasari',
        role: 'Chief Executive Officer',
        status: 'approved',
        tatHours: 72,
        actualHours: 65,
        assignedAt: '2024-09-16T02:00:00Z',
        comment: 'Strategic expansion aligns with global growth objectives. Phased approach mitigates risks effectively.',
        timestamp: '2024-09-18T19:00:00Z'
      },
      {
        step: 4,
        approver: 'Board of Directors',
        role: 'Investment Committee',
        status: 'approved',
        tatHours: 168,
        actualHours: 145,
        assignedAt: '2024-09-18T19:00:00Z',
        comment: 'Board approves international expansion with quarterly review milestones. Investment committee endorses the initiative.',
        timestamp: '2024-09-28T16:45:00Z'
      }
    ],
    documents: [
      { name: 'SEA_Market_Entry_Strategy.pdf', size: '12.5 MB', type: 'PDF', uploadedBy: 'Strategy Team', uploadedAt: 'Sep 10, 2024 10:30 AM' },
      { name: 'Regulatory_Compliance_Analysis.pdf', size: '8.2 MB', type: 'PDF', uploadedBy: 'Legal Team', uploadedAt: 'Sep 11, 2024 2:15 PM' },
      { name: 'Financial_Projections_5Year.xlsx', size: '3.5 MB', type: 'Excel', uploadedBy: 'Finance Team', uploadedAt: 'Sep 12, 2024 11:30 AM' },
      { name: 'Local_Partnership_Agreements.pdf', size: '15.8 MB', type: 'PDF', uploadedBy: 'BD Team', uploadedAt: 'Sep 15, 2024 4:20 PM' }
    ],
    spectators: [
      { name: 'Regional Teams', role: 'SEA Operations', avatar: 'RT' },
      { name: 'Export Team', role: 'International Sales', avatar: 'ET' }
    ],
    auditTrail: [
      { type: 'created', action: 'Request Created', details: 'Southeast Asia expansion proposal submitted', user: 'Vikram Pawah', timestamp: 'Sep 10, 2024 10:00 AM' },
      { type: 'approved', action: 'Marketing Approval', details: 'Sales & Marketing validation completed', user: 'Deepika Sharma', timestamp: 'Sep 12, 2024 8:00 PM' },
      { type: 'approved', action: 'Operations Approval', details: 'COO approval with supply chain validation', user: 'Lalit Malik', timestamp: 'Sep 16, 2024 2:00 AM' },
      { type: 'approved', action: 'CEO Approval', details: 'Strategic approval for expansion initiative', user: 'Vinod Dasari', timestamp: 'Sep 18, 2024 7:00 PM' },
      { type: 'approved', action: 'Board Approval', details: 'Investment committee final approval', user: 'Board of Directors', timestamp: 'Sep 28, 2024 4:45 PM' }
    ],
    tags: ['international-expansion', 'southeast-asia', 'approved', 'strategic-initiative']
  },

  // ========== REJECTED REQUESTS ==========
  'RE-REQ-2024-008': {
    id: 'RE-REQ-2024-008',
    title: 'Premium Accessories Line - Luxury Leather Collection',
    description: 'Launch of premium leather accessories including custom jackets, riding gloves, boots, and travel bags. Targeting affluent customer segment with hand-crafted Italian leather products. Exclusive Royal Enfield branding and limited edition numbering.',
    category: 'Product Development',
    subcategory: 'Accessories',
    status: 'rejected',
    priority: 'standard',
    amount: '₹2,15,00,000',
    slaProgress: 100,
    slaRemaining: 'Completed',
    slaEndDate: 'Oct 4, 2024 5:00 PM',
    currentStep: 2,
    totalSteps: 3,
    initiator: {
      name: 'Neha Agarwal',
      role: 'Accessories Product Manager',
      department: 'Product Development',
      email: 'neha.agarwal@royalenfield.com',
      phone: '+91 98765 43280',
      avatar: 'NA'
    },
    department: 'Product Development',
    createdAt: 'Sep 20, 2024 10:00 AM',
    completedAt: 'Sep 26, 2024 2:20 PM',
    updatedAt: 'Sep 26, 2024 2:20 PM',
    dueDate: '2024-10-04T17:00:00Z',
    conclusionRemark: 'Request rejected pending comprehensive market research. Current data insufficient to justify premium positioning. Recommend focus on core motorcycle accessories before luxury segment entry.',
    approvalFlow: [
      {
        step: 1,
        approver: 'Vikash Sharma',
        role: 'Head of Accessories',
        status: 'approved',
        tatHours: 48,
        actualHours: 35,
        assignedAt: '2024-09-20T10:00:00Z',
        comment: 'Concept has merit but requires thorough market validation. Design direction is appealing. Moving forward for strategic review.',
        timestamp: '2024-09-21T21:00:00Z'
      },
      {
        step: 2,
        approver: 'Suresh Krishnan',
        role: 'VP Product Strategy',
        status: 'rejected',
        tatHours: 120,
        actualHours: 113,
        assignedAt: '2024-09-21T21:00:00Z',
        comment: 'Market research indicates limited demand in luxury accessories segment. Customer priority is performance-oriented accessories. Recommend resubmission with comprehensive market analysis and customer validation.',
        timestamp: '2024-09-26T14:20:00Z'
      },
      {
        step: 3,
        approver: 'Karthik Raman',
        role: 'Head of Product Development',
        status: 'waiting',
        tatHours: 72,
        elapsedHours: 0,
        assignedAt: null,
        comment: null,
        timestamp: null
      }
    ],
    documents: [
      { name: 'Luxury_Accessories_Concept.pdf', size: '9.2 MB', type: 'PDF', uploadedBy: 'Design Team', uploadedAt: 'Sep 20, 2024 10:15 AM' },
      { name: 'Italian_Leather_Supplier_Proposal.pdf', size: '4.5 MB', type: 'PDF', uploadedBy: 'Sourcing Team', uploadedAt: 'Sep 20, 2024 2:30 PM' },
      { name: 'Premium_Segment_Analysis.xlsx', size: '2.1 MB', type: 'Excel', uploadedBy: 'Market Research', uploadedAt: 'Sep 21, 2024 11:45 AM' },
      { name: 'Competitive_Luxury_Brands_Study.pdf', size: '6.8 MB', type: 'PDF', uploadedBy: 'Strategy Team', uploadedAt: 'Sep 22, 2024 3:15 PM' }
    ],
    spectators: [
      { name: 'Retail Team', role: 'Merchandising', avatar: 'RT' },
      { name: 'Brand Team', role: 'Brand Strategy', avatar: 'BT' }
    ],
    auditTrail: [
      { type: 'created', action: 'Request Created', details: 'Premium leather accessories proposal submitted', user: 'Neha Agarwal', timestamp: 'Sep 20, 2024 10:00 AM' },
      { type: 'approved', action: 'Approved by Vikash Sharma', details: 'Head of Accessories conditional approval', user: 'Vikash Sharma', timestamp: 'Sep 21, 2024 9:00 PM' },
      { type: 'rejected', action: 'Rejected by Suresh Krishnan', details: 'VP Strategy rejection due to insufficient market validation', user: 'Suresh Krishnan', timestamp: 'Sep 26, 2024 2:20 PM' },
      { type: 'completed', action: 'Request Rejected', details: 'Final status: Rejected pending market research', user: 'System', timestamp: 'Sep 26, 2024 2:20 PM' }
    ],
    tags: ['accessories', 'luxury', 'rejected', 'market-research-needed']
  },

  // ========== MY REQUESTS (Current User's Requests) ==========
  'RE-REQ-2024-009': {
    id: 'RE-REQ-2024-009',
    title: 'Service Center Network Expansion - Western Region',
    description: 'Expansion of service network in Western India with 12 new service centers across Maharashtra, Gujarat, and Rajasthan. Focus on Tier-2 cities with growing Royal Enfield customer base. Enhanced service capabilities including performance tuning.',
    category: 'Service & Support',
    subcategory: 'Infrastructure Expansion',
    status: 'pending',
    priority: 'urgent',
    amount: '₹3,25,00,000',
    slaProgress: 85,
    slaRemaining: '12 hours overdue',
    slaEndDate: 'Oct 10, 2024 5:00 PM',
    currentStep: 1,
    totalSteps: 3,
    initiator: {
      name: 'Current User',
      role: 'Regional Service Manager - West',
      department: 'After Sales Service',
      email: 'current.user@royalenfield.com',
      phone: '+91 98765 43290',
      avatar: 'CU'
    },
    department: 'After Sales Service',
    createdAt: 'Oct 3, 2024 8:45 AM',
    updatedAt: 'Oct 7, 2024 10:30 AM',
    dueDate: '2024-10-10T17:00:00Z',
    conclusionRemark: '',
    approvalFlow: [
      {
        step: 1,
        approver: 'Ramesh Kulkarni',
        role: 'Head of After Sales Service',
        status: 'pending',
        tatHours: 72,
        elapsedHours: 84,
        assignedAt: '2024-10-03T08:45:00Z',
        comment: null,
        timestamp: null,
        reminderHistory: [
          { type: 'auto', sentAt: 'Oct 5, 2024 8:45 AM', sentBy: 'System' },
          { type: 'manual', sentAt: 'Oct 6, 2024 10:30 AM', sentBy: 'Current User' },
          { type: 'auto', sentAt: 'Oct 6, 2024 5:45 PM', sentBy: 'System' },
          { type: 'manual', sentAt: 'Oct 7, 2024 9:15 AM', sentBy: 'Current User' }
        ]
      },
      {
        step: 2,
        approver: 'Arun Pandey',
        role: 'VP Customer Experience',
        status: 'waiting',
        tatHours: 96,
        elapsedHours: 0,
        assignedAt: null,
        comment: null,
        timestamp: null
      },
      {
        step: 3,
        approver: 'Lalit Malik',
        role: 'Chief Operating Officer',
        status: 'waiting',
        tatHours: 48,
        elapsedHours: 0,
        assignedAt: null,
        comment: null,
        timestamp: null
      }
    ],
    documents: [
      { name: 'Western_Region_Expansion_Plan.pdf', size: '7.5 MB', type: 'PDF', uploadedBy: 'Current User', uploadedAt: 'Oct 3, 2024 9:00 AM' },
      { name: 'Service_Center_Requirements.xlsx', size: '2.8 MB', type: 'Excel', uploadedBy: 'Planning Team', uploadedAt: 'Oct 3, 2024 11:30 AM' },
      { name: 'Customer_Demand_Analysis.pptx', size: '4.2 MB', type: 'PowerPoint', uploadedBy: 'Analytics Team', uploadedAt: 'Oct 4, 2024 2:15 PM' },
      { name: 'ROI_Projections_Service_Network.xlsx', size: '1.9 MB', type: 'Excel', uploadedBy: 'Finance Team', uploadedAt: 'Oct 5, 2024 10:45 AM' }
    ],
    spectators: [
      { name: 'Regional Managers', role: 'Service Operations', avatar: 'RM' },
      { name: 'Training Team', role: 'Technician Development', avatar: 'TT' }
    ],
    auditTrail: [
      { type: 'created', action: 'Request Created', details: 'Service center expansion proposal submitted', user: 'Current User', timestamp: 'Oct 3, 2024 8:45 AM' },
      { type: 'assigned', action: 'Assigned to Ramesh Kulkarni', details: 'Forwarded to Head of After Sales Service', user: 'System', timestamp: 'Oct 3, 2024 8:46 AM' },
      { type: 'reminder', action: 'Reminder Sent', details: 'TAT breach reminder sent to approver', user: 'System', timestamp: 'Oct 6, 2024 5:45 PM' },
      { type: 'updated', action: 'Additional Documents', details: 'ROI projections added by finance team', user: 'Finance Team', timestamp: 'Oct 5, 2024 10:45 AM' }
    ],
    tags: ['service-expansion', 'western-region', 'tier2-cities', 'overdue']
  },

  'RE-REQ-2024-010': {
    id: 'RE-REQ-2024-010',
    title: 'Rider Fest 2024 - Premium Event Sponsorship',
    description: 'Title sponsorship for Royal Enfield Rider Fest 2024 - Multi-city motorcycle rally and festival. Expected participation of 25,000+ riders across Mumbai, Delhi, Bangalore, and Chennai. Enhanced brand engagement and community building.',
    category: 'Marketing & Campaigns',
    subcategory: 'Event Sponsorship',
    status: 'approved',
    priority: 'urgent',
    amount: '₹4,50,00,000',
    slaProgress: 100,
    slaRemaining: 'Completed',
    slaEndDate: 'Sep 29, 2024 5:00 PM',
    currentStep: 2,
    totalSteps: 2,
    initiator: {
      name: 'Current User',
      role: 'Regional Service Manager - West',
      department: 'Marketing',
      email: 'current.user@royalenfield.com',
      phone: '+91 98765 43290',
      avatar: 'CU'
    },
    department: 'Marketing',
    createdAt: 'Sep 15, 2024 4:20 PM',
    completedAt: 'Sep 22, 2024 10:45 AM',
    updatedAt: 'Sep 22, 2024 10:45 AM',
    dueDate: '2024-09-29T17:00:00Z',
    conclusionRemark: 'Event sponsorship approved with enhanced activation budget. Expected to reach 5M+ digital impressions and strengthen rider community engagement. Excellent brand building opportunity.',
    approvalFlow: [
      {
        step: 1,
        approver: 'Nikhil Sharma',
        role: 'Events Marketing Manager',
        status: 'approved',
        tatHours: 48,
        actualHours: 28,
        assignedAt: '2024-09-15T16:20:00Z',
        comment: 'Outstanding brand exposure opportunity with strong community engagement potential. Event format aligns perfectly with brand values.',
        timestamp: '2024-09-16T20:20:00Z'
      },
      {
        step: 2,
        approver: 'Deepika Sharma',
        role: 'VP Sales & Marketing',
        status: 'approved',
        tatHours: 120,
        actualHours: 86,
        assignedAt: '2024-09-16T20:20:00Z',
        comment: 'Perfect alignment with brand positioning and community strategy. Multi-city approach maximizes reach. Approved for immediate execution.',
        timestamp: '2024-09-22T10:45:00Z'
      }
    ],
    documents: [
      { name: 'Rider_Fest_2024_Proposal.pdf', size: '11.8 MB', type: 'PDF', uploadedBy: 'Current User', uploadedAt: 'Sep 15, 2024 4:35 PM' },
      { name: 'Multi_City_Event_Plan.pdf', size: '8.5 MB', type: 'PDF', uploadedBy: 'Events Team', uploadedAt: 'Sep 16, 2024 9:15 AM' },
      { name: 'Brand_Activation_Strategy.pptx', size: '6.2 MB', type: 'PowerPoint', uploadedBy: 'Brand Team', uploadedAt: 'Sep 16, 2024 3:30 PM' },
      { name: 'Expected_ROI_Analysis.xlsx', size: '2.1 MB', type: 'Excel', uploadedBy: 'Analytics Team', uploadedAt: 'Sep 17, 2024 11:20 AM' }
    ],
    spectators: [
      { name: 'Community Managers', role: 'Rider Engagement', avatar: 'CM' },
      { name: 'Event Partners', role: 'Logistics Support', avatar: 'EP' }
    ],
    auditTrail: [
      { type: 'created', action: 'Request Created', details: 'Rider Fest sponsorship proposal submitted', user: 'Current User', timestamp: 'Sep 15, 2024 4:20 PM' },
      { type: 'approved', action: 'Approved by Nikhil Sharma', details: 'Events team approval with strong recommendation', user: 'Nikhil Sharma', timestamp: 'Sep 16, 2024 8:20 PM' },
      { type: 'approved', action: 'Final Approval by Deepika Sharma', details: 'VP Marketing approval for execution', user: 'Deepika Sharma', timestamp: 'Sep 22, 2024 10:45 AM' },
      { type: 'completed', action: 'Request Approved', details: 'Event sponsorship approved for implementation', user: 'System', timestamp: 'Sep 22, 2024 10:45 AM' }
    ],
    tags: ['event-sponsorship', 'rider-fest', 'approved', 'community-engagement']
  },

  'RE-REQ-2024-011': {
    id: 'RE-REQ-2024-011',
    title: 'Digital Transformation - Customer Service Platform',
    description: 'Implementation of AI-powered customer service platform with chatbot integration, CRM enhancement, and mobile app connectivity. Projected 40% improvement in response times and 25% increase in customer satisfaction scores.',
    category: 'Information Technology',
    subcategory: 'Digital Transformation',
    status: 'in-review',
    priority: 'standard',
    amount: '₹5,75,00,000',
    slaProgress: 45,
    slaRemaining: '3 days 8 hours',
    slaEndDate: 'Oct 18, 2024 5:00 PM',
    currentStep: 2,
    totalSteps: 3,
    initiator: {
      name: 'Rahul Mishra',
      role: 'IT Director - Customer Systems',
      department: 'Information Technology',
      email: 'rahul.mishra@royalenfield.com',
      phone: '+91 98765 43300',
      avatar: 'RM'
    },
    department: 'Information Technology',
    createdAt: 'Sep 30, 2024 2:00 PM',
    updatedAt: 'Oct 7, 2024 11:45 AM',
    dueDate: '2024-10-18T17:00:00Z',
    conclusionRemark: '',
    approvalFlow: [
      {
        step: 1,
        approver: 'Swati Bansal',
        role: 'Chief Information Officer',
        status: 'approved',
        tatHours: 120,
        actualHours: 89,
        assignedAt: '2024-09-30T14:00:00Z',
        comment: 'Technology architecture is sound and aligns with digital strategy roadmap. Platform selection is appropriate for scalability.',
        timestamp: '2024-10-04T11:00:00Z'
      },
      {
        step: 2,
        approver: 'Arun Pandey',
        role: 'VP Customer Experience',
        status: 'pending',
        tatHours: 96,
        elapsedHours: 76,
        assignedAt: '2024-10-04T11:00:00Z',
        comment: null,
        timestamp: null
      },
      {
        step: 3,
        approver: 'Vinod Dasari',
        role: 'Chief Executive Officer',
        status: 'waiting',
        tatHours: 72,
        elapsedHours: 0,
        assignedAt: null,
        comment: null,
        timestamp: null
      }
    ],
    documents: [
      { name: 'Digital_Platform_Technical_Specs.pdf', size: '9.8 MB', type: 'PDF', uploadedBy: 'Technical Team', uploadedAt: 'Sep 30, 2024 2:15 PM' },
      { name: 'Vendor_Evaluation_Comparison.xlsx', size: '3.2 MB', type: 'Excel', uploadedBy: 'Procurement Team', uploadedAt: 'Oct 1, 2024 10:30 AM' },
      { name: 'Implementation_Roadmap_2024-25.pdf', size: '4.5 MB', type: 'PDF', uploadedBy: 'Project Team', uploadedAt: 'Oct 2, 2024 3:45 PM' },
      { name: 'Customer_Experience_Impact.pptx', size: '5.8 MB', type: 'PowerPoint', uploadedBy: 'CX Team', uploadedAt: 'Oct 3, 2024 9:20 AM' }
    ],
    spectators: [
      { name: 'Service Teams', role: 'End Users', avatar: 'ST' },
      { name: 'Analytics Team', role: 'Data Integration', avatar: 'AT' }
    ],
    auditTrail: [
      { type: 'created', action: 'Request Created', details: 'Digital customer service platform proposal', user: 'Rahul Mishra', timestamp: 'Sep 30, 2024 2:00 PM' },
      { type: 'assigned', action: 'Assigned to Swati Bansal', details: 'Technical evaluation by CIO', user: 'System', timestamp: 'Sep 30, 2024 2:01 PM' },
      { type: 'approved', action: 'Approved by Swati Bansal', details: 'Technical architecture approval', user: 'Swati Bansal', timestamp: 'Oct 4, 2024 11:00 AM' },
      { type: 'assigned', action: 'Assigned to Arun Pandey', details: 'Customer experience evaluation', user: 'System', timestamp: 'Oct 4, 2024 11:01 AM' }
    ],
    tags: ['digital-transformation', 'customer-service', 'ai-platform', 'crm-enhancement']
  },

  'RE-REQ-2024-012': {
    id: 'RE-REQ-2024-012',
    title: 'Sustainable Manufacturing Initiative - Green Energy',
    description: 'Installation of solar power systems and energy efficiency upgrades across Chennai and Vallam Vadagal plants. Target: 40% renewable energy by 2025. Includes waste reduction programs and carbon footprint optimization.',
    category: 'Sustainability',
    subcategory: 'Green Energy',
    status: 'rejected',
    priority: 'standard',
    amount: '₹12,50,00,000',
    slaProgress: 100,
    slaRemaining: 'Completed',
    slaEndDate: 'Oct 5, 2024 5:00 PM',
    currentStep: 3,
    totalSteps: 3,
    initiator: {
      name: 'Current User',
      role: 'Regional Service Manager - West',
      department: 'Sustainability',
      email: 'current.user@royalenfield.com',
      phone: '+91 98765 43290',
      avatar: 'CU'
    },
    department: 'Sustainability',
    createdAt: 'Sep 18, 2024 11:30 AM',
    completedAt: 'Oct 3, 2024 3:15 PM',
    updatedAt: 'Oct 3, 2024 3:15 PM',
    dueDate: '2024-10-05T17:00:00Z',
    conclusionRemark: 'Request rejected due to budget constraints in current fiscal year. Approved for inclusion in next fiscal year sustainability budget. ROI timeline needs optimization for board approval.',
    approvalFlow: [
      {
        step: 1,
        approver: 'Environmental Team',
        role: 'Sustainability Manager',
        status: 'approved',
        tatHours: 72,
        actualHours: 48,
        assignedAt: '2024-09-18T11:30:00Z',
        comment: 'Excellent initiative aligning with corporate sustainability goals. Environmental impact assessment is comprehensive.',
        timestamp: '2024-09-20T11:30:00Z'
      },
      {
        step: 2,
        approver: 'Lalit Malik',
        role: 'Chief Operating Officer',
        status: 'approved',
        tatHours: 96,
        actualHours: 82,
        assignedAt: '2024-09-20T11:30:00Z',
        comment: 'Operations team supports the initiative. Implementation plan is feasible. Moving to financial evaluation.',
        timestamp: '2024-09-23T21:30:00Z'
      },
      {
        step: 3,
        approver: 'Finance Committee',
        role: 'CFO & Investment Committee',
        status: 'rejected',
        tatHours: 168,
        actualHours: 152,
        assignedAt: '2024-09-23T21:30:00Z',
        comment: 'While the initiative is commendable, current fiscal constraints require deferral. Recommend resubmission for FY25 budget with optimized ROI timeline.',
        timestamp: '2024-10-03T15:15:00Z'
      }
    ],
    documents: [
      { name: 'Sustainability_Initiative_Master_Plan.pdf', size: '15.2 MB', type: 'PDF', uploadedBy: 'Current User', uploadedAt: 'Sep 18, 2024 11:45 AM' },
      { name: 'Solar_Installation_Technical_Specs.pdf', size: '8.8 MB', type: 'PDF', uploadedBy: 'Engineering Team', uploadedAt: 'Sep 19, 2024 2:30 PM' },
      { name: 'Environmental_Impact_Assessment.pdf', size: '6.5 MB', type: 'PDF', uploadedBy: 'Environmental Team', uploadedAt: 'Sep 20, 2024 9:15 AM' },
      { name: 'ROI_Analysis_Green_Energy.xlsx', size: '2.8 MB', type: 'Excel', uploadedBy: 'Finance Team', uploadedAt: 'Sep 25, 2024 4:45 PM' }
    ],
    spectators: [
      { name: 'Plant Managers', role: 'Implementation Leads', avatar: 'PM' },
      { name: 'Vendor Partners', role: 'Solar Installation', avatar: 'VP' }
    ],
    auditTrail: [
      { type: 'created', action: 'Request Created', details: 'Green energy initiative proposal submitted', user: 'Current User', timestamp: 'Sep 18, 2024 11:30 AM' },
      { type: 'approved', action: 'Environmental Approval', details: 'Sustainability team endorsement', user: 'Environmental Team', timestamp: 'Sep 20, 2024 11:30 AM' },
      { type: 'approved', action: 'Operations Approval', details: 'COO approval for implementation feasibility', user: 'Lalit Malik', timestamp: 'Sep 23, 2024 9:30 PM' },
      { type: 'rejected', action: 'Finance Committee Rejection', details: 'Budget constraints - defer to next fiscal year', user: 'Finance Committee', timestamp: 'Oct 3, 2024 3:15 PM' }
    ],
    tags: ['sustainability', 'green-energy', 'rejected', 'budget-constraints']
  }
};

export default function App() {
  const [currentPage, setCurrentPage] = useState<Page>('dashboard');
  const [selectedRequestId, setSelectedRequestId] = useState<string>('');
  const [activeModal, setActiveModal] = useState<string>('');
  const [approvalAction, setApprovalAction] = useState<'approve' | 'reject' | null>(null);
  const [selectedRequestTitle, setSelectedRequestTitle] = useState<string>('');
  const [dynamicRequests, setDynamicRequests] = useState<any[]>([]);

  const handleNavigate = (page: string) => {
    setCurrentPage(page as Page);
  };

  const handleViewRequest = (requestId: string, requestTitle?: string) => {
    setSelectedRequestId(requestId);
    
    // Determine request type by checking databases and dynamic requests
    const isClaimRequest = CLAIM_MANAGEMENT_DATABASE[requestId];
    const isCustomRequest = CUSTOM_REQUEST_DATABASE[requestId];
    const dynamicRequest = dynamicRequests.find((req: any) => req.id === requestId);
    
    // Get title from appropriate source
    const request = isClaimRequest || isCustomRequest || dynamicRequest;
    setSelectedRequestTitle(requestTitle || request?.title || 'Unknown Request');
    setCurrentPage('request-detail');
  };

  const handleBack = () => {
    setCurrentPage('dashboard');
  };

  const handleNewRequest = () => {
    setCurrentPage('new-request');
  };

  const handleNewRequestSubmit = (requestData: any) => {
    // Check if this is a template selection (from Existing Template button)
    if (requestData.templateType) {
      // Navigate to the specific template wizard
      if (requestData.templateType === 'claim-management') {
        setCurrentPage('claim-management');
      }
      return;
    }
    
    // Regular custom request submission
    // Generate unique ID for the new custom request
    const requestId = `RE-REQ-2024-${String(Object.keys(CUSTOM_REQUEST_DATABASE).length + dynamicRequests.length + 1).padStart(3, '0')}`;
    
    // Create full custom request object
    const newCustomRequest = {
      id: requestId,
      title: requestData.title,
      description: requestData.description || '',
      category: requestData.category || 'General',
      subcategory: requestData.subcategory || '',
      status: 'pending',
      priority: requestData.priority || 'standard',
      amount: requestData.budget || 'N/A',
      slaProgress: 0,
      slaRemaining: '5 days',
      slaEndDate: new Date(Date.now() + 5 * 24 * 60 * 60 * 1000).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric', hour: 'numeric', minute: 'numeric', hour12: true }),
      currentStep: 1,
      totalSteps: requestData.approvers?.length || 1,
      currentApprover: requestData.approvers?.[0]?.name || requestData.approvers?.[0]?.email?.split('@')[0] || 'Pending Assignment',
      approverLevel: `1 of ${requestData.approvers?.length || 1}`,
      template: 'custom',
      initiator: {
        name: 'Current User',
        role: requestData.initiatorRole || 'Employee',
        department: requestData.department || 'General',
        email: 'current.user@royalenfield.com',
        phone: '+91 98765 43290',
        avatar: 'CU'
      },
      department: requestData.department || 'General',
      createdAt: new Date().toLocaleDateString('en-US', { 
        month: 'short', 
        day: 'numeric', 
        year: 'numeric', 
        hour: 'numeric', 
        minute: 'numeric',
        hour12: true 
      }),
      updatedAt: new Date().toLocaleDateString('en-US', { 
        month: 'short', 
        day: 'numeric', 
        year: 'numeric', 
        hour: 'numeric', 
        minute: 'numeric',
        hour12: true 
      }),
      dueDate: new Date(Date.now() + 5 * 24 * 60 * 60 * 1000).toISOString(),
      submittedDate: new Date().toISOString(),
      estimatedCompletion: new Date(Date.now() + 5 * 24 * 60 * 60 * 1000).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }),
      conclusionRemark: '',
      approvalFlow: (requestData.approvers || []).filter((a: any) => a).map((approver: any, index: number) => {
        // Extract name from email if name is not available
        const approverName = approver?.name || approver?.email?.split('@')[0] || `Approver ${index + 1}`;
        const approverEmail = approver?.email || '';
        
        return {
          step: index + 1,
          approver: `${approverName}${approverEmail ? ` (${approverEmail})` : ''}`,
          role: approver?.role || `Level ${approver?.level || index + 1} Approver`,
          status: index === 0 ? 'pending' : 'waiting',
          tatHours: approver?.tat ? (typeof approver.tat === 'string' ? parseInt(approver.tat) : approver.tat) : 48,
          elapsedHours: index === 0 ? 0 : 0,
          assignedAt: index === 0 ? new Date().toISOString() : null,
          comment: null,
          timestamp: null
        };
      }),
      documents: [],
      spectators: (requestData.spectators || [])
        .filter((s: any) => s && (s.name || s.email))
        .map((spectator: any) => {
          const name = spectator?.name || spectator?.email?.split('@')[0] || 'Observer';
          return {
            name: name,
            role: spectator?.role || spectator?.department || 'Observer',
            avatar: name.split(' ').map((n: string) => n[0]).join('').toUpperCase().slice(0, 2) || 'OB'
          };
        }),
      auditTrail: [
        { 
          type: 'created', 
          action: 'Request Created', 
          details: `Custom request "${requestData.title}" created`, 
          user: 'Current User', 
          timestamp: new Date().toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric', hour: 'numeric', minute: 'numeric', hour12: true })
        },
        { 
          type: 'assignment', 
          action: 'Assigned to Approver', 
          details: `Request assigned to ${requestData.approvers?.[0]?.name || requestData.approvers?.[0]?.email || 'first approver'}`, 
          user: 'System', 
          timestamp: new Date().toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric', hour: 'numeric', minute: 'numeric', hour12: true })
        }
      ],
      tags: requestData.tags || ['custom-request']
    };
    
    // Add to dynamic requests
    setDynamicRequests([...dynamicRequests, newCustomRequest]);
    
    console.log('New custom request created:', newCustomRequest);
    setCurrentPage('my-requests');
    toast.success('Request Submitted Successfully!', {
      description: `Your request "${requestData.title}" (${requestId}) has been created and sent for approval.`,
      duration: 5000,
    });
  };

  const handleApprovalSubmit = (action: 'approve' | 'reject', comment: string) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        if (action === 'approve') {
          toast.success('Request Approved', {
            description: 'The request has been approved and forwarded to the next step.',
            duration: 5000,
          });
        } else {
          toast.error('Request Rejected', {
            description: 'The request has been rejected and returned to the initiator.',
            duration: 5000,
          });
        }
        
        console.log(`${action} action completed with comment:`, comment);
        setApprovalAction(null);
        resolve(true);
      }, 1000);
    });
  };

  const handleCloseApprovalModal = () => {
    setApprovalAction(null);
  };

  const handleOpenModal = (modal: string) => {
    setActiveModal(modal);
    switch (modal) {
      case 'work-note':
        setCurrentPage('work-notes');
        break;
      case 'internal-chat':
        // Simplified access control: Allow access for "My Requests" and for approvers/initiators
        if (currentPage === 'my-requests') {
          // All requests in "My Requests" are created by current user, so full access
          toast.success('Internal Chat Opened', {
            description: 'Internal chat opened for your request stakeholders.',
          });
        } else {
          // For other pages, check if user is initiator or approver
          const request = REQUEST_DATABASE[selectedRequestId as keyof typeof REQUEST_DATABASE];
          const isInitiator = request && request.initiator.name === 'Current User';
          const isApprover = request && request.approvalFlow.some(step => 
            step.approver === 'Current User' || step.status === 'pending'
          );
          
          if (isInitiator || isApprover) {
            toast.success('Internal Chat Opened', {
              description: 'Internal chat opened for request stakeholders.',
            });
          } else {
            toast.error('Access Restricted', {
              description: 'Internal chat is only accessible to request initiators and approvers.',
            });
          }
        }
        break;
      case 'approval-list':
        toast.info('Approval List', {
          description: 'Detailed approval workflow would be displayed.',
        });
        break;
      case 'approve':
        setApprovalAction('approve');
        break;
      case 'reject':
        setApprovalAction('reject');
        break;
      case 'escalate':
        toast.warning('Request Escalated', {
          description: 'The request has been escalated to higher authority.',
        });
        break;
      case 'reminder':
        toast.info('Reminder Sent', {
          description: 'Reminder notification sent to current approver.',
        });
        break;
      case 'add-approver':
        toast.info('Add Approver', {
          description: 'Add approver functionality would be implemented here.',
        });
        break;
      case 'add-spectator':
        toast.info('Add Spectator', {
          description: 'Add spectator functionality would be implemented here.',
        });
        break;
      case 'modify-sla':
        toast.info('Modify SLA', {
          description: 'SLA modification functionality would be implemented here.',
        });
        break;
      default:
        break;
    }
  };

  const renderCurrentPage = () => {
    switch (currentPage) {
      case 'dashboard':
        return <Dashboard onNavigate={handleNavigate} onNewRequest={handleNewRequest} />;
      case 'open-requests':
        return <RequestsList type="open" onViewRequest={handleViewRequest} />;
      case 'closed-requests':
        return <RequestsList type="closed" onViewRequest={handleViewRequest} />;
      case 'my-requests':
        return <MyRequests onViewRequest={handleViewRequest} dynamicRequests={dynamicRequests} />;
      case 'request-detail':
        // Determine which component to render based on request type
        // Check static databases first
        const isClaimRequest = CLAIM_MANAGEMENT_DATABASE[selectedRequestId];
        const isCustomRequest = CUSTOM_REQUEST_DATABASE[selectedRequestId];
        
        // Check dynamic requests
        const dynamicRequest = dynamicRequests.find((req: any) => req.id === selectedRequestId);
        const isDynamicClaim = dynamicRequest?.templateType === 'claim-management' || dynamicRequest?.template === 'claim-management';
        const isDynamicCustom = dynamicRequest && !isDynamicClaim;
        
        if (isClaimRequest || isDynamicClaim) {
          // Render Claim Management Detail for claim management requests
          return (
            <ClaimManagementDetail
              requestId={selectedRequestId}
              onBack={handleBack}
              onOpenModal={handleOpenModal}
              dynamicRequests={dynamicRequests}
            />
          );
        } else if (isCustomRequest || isDynamicCustom) {
          // Render Request Detail for custom requests
          return (
            <RequestDetail
              requestId={selectedRequestId}
              onBack={handleBack}
              onOpenModal={handleOpenModal}
              dynamicRequests={dynamicRequests}
            />
          );
        } else {
          // Handle legacy requests from old database
          return (
            <RequestDetail
              requestId={selectedRequestId}
              onBack={handleBack}
              onOpenModal={handleOpenModal}
              dynamicRequests={dynamicRequests}
            />
          );
        }
      case 'work-notes':
        return (
          <WorkNoteView
            requestId={selectedRequestId}
            onBack={handleBack}
          />
        );
      case 'new-request':
        return (
          <NewRequestWizard
            onBack={handleBack}
            onSubmit={handleNewRequestSubmit}
          />
        );
      case 'claim-management':
        return (
          <ClaimManagementWizard
            onBack={() => setCurrentPage('new-request')}
            onSubmit={(claimData) => {
              // Generate unique ID for the new claim request
              const requestId = `RE-REQ-2024-CM-${String(dynamicRequests.length + 2).padStart(3, '0')}`;
              
              // Create full request object
              const newRequest = {
                id: requestId,
                title: `${claimData.activityName} - Claim Request`,
                description: claimData.requestDescription,
                category: 'Dealer Operations',
                subcategory: 'Claim Management',
                status: 'pending',
                priority: 'standard',
                amount: 'TBD',
                slaProgress: 0,
                slaRemaining: '7 days',
                slaEndDate: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString(),
                currentStep: 1,
                totalSteps: 8,
                templateType: 'claim-management',
                templateName: 'Claim Management',
                initiator: {
                  name: 'Current User',
                  role: 'Regional Marketing Coordinator',
                  department: 'Marketing',
                  email: 'current.user@royalenfield.com',
                  phone: '+91 98765 43290',
                  avatar: 'CU'
                },
                department: 'Marketing',
                createdAt: new Date().toLocaleString('en-US', { 
                  month: 'short', 
                  day: 'numeric', 
                  year: 'numeric', 
                  hour: 'numeric', 
                  minute: 'numeric',
                  hour12: true 
                }),
                updatedAt: new Date().toLocaleString('en-US', { 
                  month: 'short', 
                  day: 'numeric', 
                  year: 'numeric', 
                  hour: 'numeric', 
                  minute: 'numeric',
                  hour12: true 
                }),
                dueDate: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString(),
                conclusionRemark: '',
                claimDetails: {
                  activityName: claimData.activityName,
                  activityType: claimData.activityType,
                  activityDate: claimData.activityDate ? new Date(claimData.activityDate).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }) : '',
                  location: claimData.location,
                  dealerCode: claimData.dealerCode,
                  dealerName: claimData.dealerName,
                  dealerEmail: claimData.dealerEmail || 'N/A',
                  dealerPhone: claimData.dealerPhone || 'N/A',
                  dealerAddress: claimData.dealerAddress || 'N/A',
                  requestDescription: claimData.requestDescription,
                  estimatedBudget: claimData.estimatedBudget || 'TBD',
                  periodStart: claimData.periodStartDate ? new Date(claimData.periodStartDate).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }) : '',
                  periodEnd: claimData.periodEndDate ? new Date(claimData.periodEndDate).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }) : ''
                },
                approvalFlow: claimData.workflowSteps || [
                  {
                    step: 1,
                    approver: `${claimData.dealerName} (Dealer)`,
                    role: 'Dealer - Document Upload',
                    status: 'pending',
                    tatHours: 72,
                    elapsedHours: 0,
                    assignedAt: new Date().toISOString(),
                    comment: null,
                    timestamp: null,
                    description: 'Dealer uploads proposal document, cost breakup, timeline for closure, and other supporting documents'
                  },
                  {
                    step: 2,
                    approver: 'Current User (Initiator)',
                    role: 'Initiator Evaluation',
                    status: 'waiting',
                    tatHours: 48,
                    elapsedHours: 0,
                    assignedAt: null,
                    comment: null,
                    timestamp: null,
                    description: 'Initiator reviews dealer documents and approves or requests modifications'
                  },
                  {
                    step: 3,
                    approver: 'System Auto-Process',
                    role: 'IO Confirmation',
                    status: 'waiting',
                    tatHours: 1,
                    elapsedHours: 0,
                    assignedAt: null,
                    comment: null,
                    timestamp: null,
                    description: 'Automatic IO (Internal Order) confirmation generated upon initiator approval'
                  },
                  {
                    step: 4,
                    approver: 'Rajesh Kumar',
                    role: 'Department Lead Approval',
                    status: 'waiting',
                    tatHours: 72,
                    elapsedHours: 0,
                    assignedAt: null,
                    comment: null,
                    timestamp: null,
                    description: 'Department head approves and blocks budget in IO for this activity'
                  },
                  {
                    step: 5,
                    approver: `${claimData.dealerName} (Dealer)`,
                    role: 'Dealer - Completion Documents',
                    status: 'waiting',
                    tatHours: 120,
                    elapsedHours: 0,
                    assignedAt: null,
                    comment: null,
                    timestamp: null,
                    description: 'Dealer submits activity completion documents and description'
                  },
                  {
                    step: 6,
                    approver: 'Current User (Initiator)',
                    role: 'Initiator Verification',
                    status: 'waiting',
                    tatHours: 48,
                    elapsedHours: 0,
                    assignedAt: null,
                    comment: null,
                    timestamp: null,
                    description: 'Initiator verifies completion documents and can modify approved amount'
                  },
                  {
                    step: 7,
                    approver: 'System Auto-Process',
                    role: 'E-Invoice Generation',
                    status: 'waiting',
                    tatHours: 1,
                    elapsedHours: 0,
                    assignedAt: null,
                    comment: null,
                    timestamp: null,
                    description: 'Auto-generate e-invoice based on final approved amount'
                  },
                  {
                    step: 8,
                    approver: 'Finance Team',
                    role: 'Credit Note Issuance',
                    status: 'waiting',
                    tatHours: 48,
                    elapsedHours: 0,
                    assignedAt: null,
                    comment: null,
                    timestamp: null,
                    description: 'Finance team issues credit note to dealer'
                  }
                ],
                documents: [],
                spectators: [],
                auditTrail: [
                  { 
                    type: 'created', 
                    action: 'Request Created', 
                    details: `Claim request for ${claimData.activityName} created`, 
                    user: 'Current User', 
                    timestamp: new Date().toLocaleString('en-US', { 
                      month: 'short', 
                      day: 'numeric', 
                      year: 'numeric', 
                      hour: 'numeric', 
                      minute: 'numeric',
                      hour12: true 
                    })
                  }
                ],
                tags: ['claim-management', 'new-request', claimData.activityType?.toLowerCase().replace(/\s+/g, '-')]
              };
              
              // Add to dynamic requests
              setDynamicRequests(prev => [...prev, newRequest]);
              
              // Also add to REQUEST_DATABASE for immediate viewing
              (REQUEST_DATABASE as any)[requestId] = newRequest;
              
              toast.success('Claim Request Submitted', {
                description: 'Your claim management request has been created successfully.',
              });
              setCurrentPage('my-requests');
            }}
          />
        );
      default:
        return <Dashboard onNavigate={handleNavigate} onNewRequest={handleNewRequest} />;
    }
  };

  return (
    <div className="min-h-screen h-screen flex flex-col overflow-hidden bg-background">
      {(currentPage === 'new-request' || currentPage === 'claim-management') ? (
        renderCurrentPage()
      ) : (
        <Layout
          currentPage={currentPage}
          onNavigate={handleNavigate}
          onNewRequest={handleNewRequest}
        >
          {renderCurrentPage()}
        </Layout>
      )}

      <Toaster 
        position="top-right"
        toastOptions={{
          style: {
            background: 'var(--card)',
            color: 'var(--card-foreground)',
            border: '1px solid var(--border)',
          },
        }}
      />

      {/* Approval Action Modal */}
      {approvalAction && (
        <ApprovalActionModal
          isOpen={!!approvalAction}
          onClose={handleCloseApprovalModal}
          action={approvalAction}
          requestId={selectedRequestId}
          requestTitle={selectedRequestTitle}
          onSubmit={handleApprovalSubmit}
        />
      )}
    </div>
  );
}