Spaces:
Runtime error
Runtime error
Download src/components/ChatAssistant.tsx from Vignesh5656/transformation-ui: direct link, hf CLI and curl.
- Browser
- Download file 132 kB
-
https://huggingface.co/spaces/Vignesh5656/transformation-ui/resolve/main/src/components/ChatAssistant.tsx
- Command line
-
hf download hf://spaces/Vignesh5656/transformation-ui/src/components/ChatAssistant.tsx
-
curl -L -o ChatAssistant.tsx https://huggingface.co/spaces/Vignesh5656/transformation-ui/resolve/main/src/components/ChatAssistant.tsx
132 kB
import React, { useState, useEffect, useRef } from 'react';
import { useDocument } from '../contexts/DocumentContext';
import ClientLookupComponent from './ClientLookupComponent';
interface Message {
id: string;
text: string;
sender: 'assistant' | 'user';
timestamp: Date;
options?: string[];
showClientLookup?: boolean;
}
interface ChatAssistantProps {
autoStart?: boolean;
}
const ChatAssistant: React.FC<ChatAssistantProps> = ({ autoStart = false }) => {
const [isOpen, setIsOpen] = useState(autoStart);
const [messages, setMessages] = useState<Message[]>([]);
const [isTyping, setIsTyping] = useState(false);
const [sessionEnded, setSessionEnded] = useState(false);
const messagesEndRef = useRef<HTMLDivElement>(null);
// Document context and workflow state
const { documentState, updateClientInformation, setCurrentStep } = useDocument();
const [workflowState, setWorkflowState] = useState<{
isInTab1Workflow: boolean;
isInTab2Workflow: boolean;
isInTab3Workflow: boolean;
isInTab4Workflow: boolean;
isInTab5Workflow: boolean;
currentStep: string;
collectedData: {
clientName?: string;
parentCode?: string;
clientType?: string;
lineOfBusiness?: string;
};
awaitingInput: boolean;
inputType?: string;
hasShownTabWorkflow: boolean; // Track if tab workflow was already shown
sessionId: string; // Track unique session
}>({
isInTab1Workflow: false,
isInTab2Workflow: false,
isInTab3Workflow: false,
isInTab4Workflow: false,
isInTab5Workflow: false,
currentStep: 'initial',
collectedData: {},
awaitingInput: false,
hasShownTabWorkflow: false,
sessionId: Date.now().toString()
});
const scrollToBottom = () => {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
};
useEffect(() => {
scrollToBottom();
}, [messages]);
// Initialize chat when opened
useEffect(() => {
if (isOpen && messages.length === 0 && !sessionEnded) {
initializeChat();
}
}, [isOpen]);
// Auto-start chat if autoStart prop is true
useEffect(() => {
if (autoStart && messages.length === 0 && !sessionEnded) {
// Just set isOpen to true, let the normal initialization handle the rest
// The existing useEffect for isOpen will trigger initializeChat automatically
console.log('🔧 DEBUG: Auto-start triggered, chat will open automatically');
}
}, [autoStart]);
// Auto-trigger workflow when tab changes
useEffect(() => {
if (isOpen && !sessionEnded && messages.length > 0) {
handleTabChange();
}
}, [documentState.currentStep, isOpen]);
const handleTabChange = async () => {
const currentTab = documentState.currentStep;
const lastMessage = messages[messages.length - 1];
// Only trigger if we're not already in a specific workflow and the last message isn't from a tab change
// Also check if we've already shown the tab workflow in this session
if (workflowState.isInTab1Workflow ||
workflowState.isInTab2Workflow ||
workflowState.isInTab3Workflow ||
workflowState.isInTab4Workflow ||
workflowState.isInTab5Workflow ||
workflowState.hasShownTabWorkflow ||
(lastMessage?.text.includes('Welcome to') && Date.now() - lastMessage.timestamp.getTime() < 5000)) {
return;
}
// Detect tab changes and trigger appropriate workflows
if (currentTab === 1) {
await triggerTab1Workflow();
} else if (currentTab === 2) {
await triggerTab2Workflow();
} else if (currentTab === 3) {
await triggerTab3Workflow();
} else if (currentTab === 4) {
await triggerTab4Workflow();
} else if (currentTab === 5) {
await triggerTab5Workflow();
}
};
const triggerTab1Workflow = async () => {
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 1000));
addMessage("🏠 Welcome to Client Information!", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 1500));
addMessage("I can help you configure client details, effective dates, and export settings. What would you like to do?", 'assistant', [
'Onboard new client',
'Use existing client',
'Update client details',
'Help with configuration'
]);
setWorkflowState(prev => ({
...prev,
isInTab1Workflow: true,
currentStep: 'tab1_guidance',
hasShownTabWorkflow: true
}));
setIsTyping(false);
};
const triggerTab2Workflow = async () => {
// Check if standard configuration is enabled
const useStandardConfig = documentState.clientInformation.useStandardConfiguration;
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 1000));
if (useStandardConfig) {
// Simplified workflow for standard configuration
addMessage("💰 Financial Maximums - Configuration", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 1500));
addMessage("Welcome to the Financial Maximums tab. I see that you have selected to use the standard configuration for this. I have preloaded the section with the standard configuration. Please review and confirm once you are ready to move to the next section", 'assistant', [
'Continue to section 3'
]);
} else {
// Original workflow for manual configuration
// Check if financial maximums are selected
let hasSelectedFinancialMaximums = false;
try {
const allParagraphs = document.querySelectorAll('p');
let noOptionsMessage = false;
for (let i = 0; i < allParagraphs.length; i++) {
if (allParagraphs[i].textContent?.includes('Select Financial Maximum options above')) {
noOptionsMessage = true;
break;
}
}
hasSelectedFinancialMaximums = !noOptionsMessage;
} catch (error) {
hasSelectedFinancialMaximums = false;
}
if (!hasSelectedFinancialMaximums) {
addMessage("💰 Welcome to Financial Maximums Configuration!", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 1500));
addMessage("I can help you set up deductibles and out-of-pocket maximums. What would you like to know?", 'assistant', [
'Help me choose deductible amounts',
'Explain embedded vs aggregate benefits',
'What are compliance requirements?',
'Show me best practices',
'Continue to section 3'
]);
} else {
addMessage("💰 Financial Maximums - Configuration Active", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 1500));
addMessage("I can see you have financial maximums configured. Need help with any adjustments or have questions about your current setup?", 'assistant', [
'Review my configuration',
'Compliance check',
'Optimization suggestions',
'Add more options',
'Continue to section 3'
]);
}
}
setWorkflowState(prev => ({
...prev,
isInTab2Workflow: true,
currentStep: 'tab2_guidance',
hasShownTabWorkflow: true
}));
setIsTyping(false);
};
const triggerTab3Workflow = async () => {
// Check if standard configuration is enabled
const useStandardConfig = documentState.clientInformation.useStandardConfiguration;
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 1000));
if (useStandardConfig) {
// Simplified workflow for standard configuration
addMessage("🏥 Benefit Details - Configuration", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 1500));
addMessage("Welcome to the Benefit Details Configuration tab. I see that you have selected to use the standard configuration for this. I have preloaded the section with the standard configuration.", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 1500));
addMessage("Please review and confirm once you are ready to move to the next section", 'assistant', [
'Continue to section 4'
]);
} else {
// Original workflow for manual configuration
// Check if benefit details are configured by looking at the DOM
let hasBenefitDetailsConfigured = false;
try {
console.log('🔧 DEBUG: Checking Tab 3 benefit details configuration...');
// Check for filled input fields that would indicate configuration
const inputs = document.querySelectorAll('input[type="text"], input[type="number"], textarea, select');
let filledInputs = 0;
for (let i = 0; i < inputs.length; i++) {
const input = inputs[i] as HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement;
if (input.value && input.value.trim() !== '') {
filledInputs++;
}
}
// Check for selected radio buttons and checkboxes
const selectedOptions = document.querySelectorAll('input[type="radio"]:checked, input[type="checkbox"]:checked');
// Consider configured if there are multiple filled inputs or selected options
hasBenefitDetailsConfigured = filledInputs > 1 || selectedOptions.length > 2;
console.log('🔧 DEBUG: Filled inputs:', filledInputs, 'Selected options:', selectedOptions.length);
console.log('🔧 DEBUG: Tab 3 configured:', hasBenefitDetailsConfigured);
} catch (error) {
console.log('🔧 DEBUG: Error checking Tab 3:', error);
hasBenefitDetailsConfigured = false;
}
if (!hasBenefitDetailsConfigured) {
addMessage("🏥 Welcome to Benefit Details Configuration!", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 1500));
addMessage("This is where you'll configure comprehensive benefit coverages for your plan. Let me guide you through the available sections:", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("📋 Available Benefit Sections:\n\n• Outpatient Benefits 🏥\n Primary care, specialists, diagnostics, preventive care\n\n• Inpatient Benefits 🏨\n Hospital stays, emergency services, surgical procedures\n\n• Other Benefits 💊\n Pharmacy, vision, dental, mental health services\n\n• Claims & Special Handling 📝\n Special instructions and claims processing rules", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2500));
addMessage("Configuration Process:\n\n1️⃣ Configure copay amounts and coinsurance percentages for each service\n\n2️⃣ Set network requirements and prior authorization rules\n\n3️⃣ Define benefit limits, exclusions, and special handling\n\n4️⃣ Add claims instructions and administrative notes", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("How can I help you configure your benefit details?", 'assistant', [
'Help with outpatient benefits',
'Configure inpatient services',
'Set up other benefits',
'Claims and special handling',
'Best practices for benefit design',
'Continue to section 4'
]);
} else {
addMessage("🏥 Benefit Details - Configuration Active", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 1500));
addMessage("I can see you have benefit details configured. Need help with any adjustments or have questions about your current setup?", 'assistant', [
'Review my configuration',
'Help with outpatient benefits',
'Configure inpatient services',
'Set up other benefits',
'Claims and special handling',
'Best practices for benefit design',
'Continue to section 4'
]);
}
}
setWorkflowState(prev => ({
...prev,
isInTab1Workflow: false,
isInTab2Workflow: false,
isInTab3Workflow: true,
currentStep: 'tab3_guidance',
hasShownTabWorkflow: true
}));
setIsTyping(false);
};
const triggerTab4Workflow = async () => {
// Check if standard configuration is enabled
const useStandardConfig = documentState.clientInformation.useStandardConfiguration;
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 1000));
if (useStandardConfig) {
// Simplified workflow for standard configuration
addMessage("🏗️ MSAG Builder - Configuration", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 1500));
addMessage("Welcome to the MSAG Builder tab. I see that you have selected to use the standard configuration for this. I have preloaded the section with the standard configuration.", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 1500));
addMessage("This section can be used for configuring the fields for the Master Service/Auth Grid (MSAG) Document", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 1500));
addMessage("Please review and confirm once you are ready to move to the next section", 'assistant', [
'Continue to section 5'
]);
} else {
// Original workflow for manual configuration
// Check if MSAG records are configured by looking at the DOM and document state
let hasMSAGRecordsConfigured = false;
let hasAvailableServices = false;
try {
console.log('🔧 DEBUG: Checking Tab 4 MSAG Builder configuration...');
// Check for available services using document state instead of unreliable DOM queries
hasAvailableServices = (
// Check for out-of-pocket services
Boolean(documentState.outOfPocketDetails?.appliesForBenefit) ||
// Check for outpatient benefits
Boolean(documentState.outpatientBenefits?.selectedOptions?.length) ||
// Check for inpatient benefits with rows
Boolean(documentState.inpatientBenefits?.facilityRows?.length) ||
Boolean(documentState.inpatientBenefits?.professionalRows?.length) ||
Boolean(documentState.inpatientBenefits?.alternativeCareRows?.length) ||
// Check for other benefits with rows
Boolean(documentState.otherBenefits?.emergencyRows?.length) ||
Boolean(documentState.otherBenefits?.ectRows?.length) ||
Boolean(documentState.otherBenefits?.otherOutpatientRows?.length) ||
Boolean(documentState.otherBenefits?.otherServicesRows?.length) ||
// Check for other benefits configuration
Boolean(documentState.otherBenefits?.outOfCountry?.coveredBenefit) ||
Boolean(documentState.otherBenefits?.transitionBenefitsConfig?.coveredBenefit)
);
// Check for configured MSAG records
const msagInputs = document.querySelectorAll('input[value], select option:checked, textarea');
let filledMSAGInputs = 0;
for (let i = 0; i < msagInputs.length; i++) {
const input = msagInputs[i] as HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement;
if (input.value && input.value.trim() !== '' && input.value !== 'Select category') {
filledMSAGInputs++;
}
}
// Check for "No MSAG Records Yet" message
const noMSAGMessage = Array.from(document.querySelectorAll('h3')).some(h3 =>
h3.textContent?.includes('No MSAG Records Yet')
);
hasMSAGRecordsConfigured = filledMSAGInputs > 5 && !noMSAGMessage;
console.log('🔧 DEBUG: Available services:', hasAvailableServices);
console.log('🔧 DEBUG: Filled MSAG inputs:', filledMSAGInputs);
console.log('🔧 DEBUG: MSAG configured:', hasMSAGRecordsConfigured);
} catch (error) {
console.log('🔧 DEBUG: Error checking Tab 4 status:', error);
hasMSAGRecordsConfigured = false;
hasAvailableServices = false;
}
if (!hasAvailableServices) {
// Show message when no services are available from previous tabs
addMessage("🏗️ Welcome to MSAG Builder!", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 1500));
addMessage("The MSAG (Medical Services Authorization Guidelines) Builder helps you create detailed service configurations. However, I notice you need to complete previous tabs first:", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("📋 Required Prerequisites:\n\n• Complete Tab 2 - Financial Maximums configuration\n• Complete Tab 3 - Benefit Details configuration\n\n💡 These tabs provide the services that will be available for MSAG record creation", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("What would you like to do?", 'assistant', [
'Go back to complete Tab 2',
'Go back to complete Tab 3',
'Learn about MSAG Builder',
'Continue to section 5'
]);
} else if (!hasMSAGRecordsConfigured) {
// Show comprehensive welcome when services are available but no MSAG records created
addMessage("🏗️ Welcome to MSAG Builder!", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 1500));
addMessage("Perfect! I can see you have configured services from previous tabs. Now let's create detailed MSAG records for proper claims processing and authorization management.", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("🔧 MSAG Record Components:\n\n• Service Type Configuration 📋\n Map services to specific authorization classes\n\n• CPT/HCPCS Code Assignment 💻\n Define procedure and diagnostic codes\n\n• Authorization Classes 🔐\n Set up prior authorization requirements\n\n• Benefit Class Mapping 💰\n Link to cost-sharing structures", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2500));
addMessage("Configuration Process:\n\n1️⃣ Review available services from your benefit configuration\n\n2️⃣ Add services to create MSAG records\n\n3️⃣ Configure detailed service parameters and codes\n\n4️⃣ Set up authorization and claim processing rules\n\n5️⃣ Validate compliance and completeness", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("How can I help you build your MSAG configuration?", 'assistant', [
'Guide me through adding services',
'Explain MSAG components',
'Help with CPT/HCPCS codes',
'Authorization class setup',
'Best practices for MSAG',
'Continue to section 5'
]);
} else {
// Show different messages when MSAG records are already configured
addMessage("🏗️ MSAG Builder - Configuration Active!", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 1500));
addMessage("Excellent! I can see you have MSAG records configured. Need help with any adjustments, validation, or optimization of your current setup?", 'assistant', [
'Review my MSAG configuration',
'Validate CPT/HCPCS codes',
'Optimize authorization classes',
'Add more service records',
'Compliance validation',
'Best practices review',
'Continue to section 5'
]);
}
}
setWorkflowState(prev => ({
...prev,
isInTab1Workflow: false,
isInTab2Workflow: false,
isInTab3Workflow: false,
isInTab4Workflow: true,
currentStep: 'tab4_guidance',
hasShownTabWorkflow: true
}));
setIsTyping(false);
};
const triggerTab5Workflow = async () => {
// Check if standard configuration is enabled
const useStandardConfig = documentState.clientInformation.useStandardConfiguration;
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 1000));
if (useStandardConfig) {
// Simplified workflow for standard configuration
addMessage("🩺 Dx Supplemental Builder - Configuration", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 1500));
addMessage("Welcome to the Diagnostics Supplemental Builder tab.", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 1500));
addMessage("This section is used for configuring the different diagnostic groups and classes for the client", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 1500));
addMessage("I see that you have selected to use the standard configuration for this. I have preloaded the section with the standard configuration.", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 1500));
addMessage("Please review and confirm once you are ready to move to the next section", 'assistant', [
'Continue to section 6'
]);
} else {
// Original workflow for manual configuration
// Check if Dx Supplemental records are configured by looking at the DOM and document state
let hasDxSupplementalRecordsConfigured = false;
let hasPrerequisitesCompleted = false;
try {
console.log('🔧 DEBUG: Checking Tab 5 Dx Supplemental Builder configuration...');
// Check for prerequisites - MSAG records should be available from Tab 4
hasPrerequisitesCompleted = (
// Check for MSAG records or any previous tab configurations
Boolean(documentState.outOfPocketDetails?.appliesForBenefit) ||
Boolean(documentState.outpatientBenefits?.selectedOptions?.length) ||
Boolean(documentState.inpatientBenefits?.facilityRows?.length) ||
Boolean(documentState.inpatientBenefits?.professionalRows?.length) ||
Boolean(documentState.otherBenefits?.emergencyRows?.length)
);
// Check for configured Dx Supplemental records using document state
hasDxSupplementalRecordsConfigured = Boolean(
documentState.dxSupplementalRecords && documentState.dxSupplementalRecords.length > 0
);
// Additionally check DOM for any filled diagnosis records
const diagnosisInputs = document.querySelectorAll('input[placeholder*="diagnosis" i], input[placeholder*="icd" i], select');
let filledDiagnosisInputs = 0;
for (let i = 0; i < diagnosisInputs.length; i++) {
const input = diagnosisInputs[i] as HTMLInputElement | HTMLSelectElement;
if (input.value && input.value.trim() !== '' && input.value !== 'Yes' && input.value !== 'No') {
filledDiagnosisInputs++;
}
}
// Check for "No Diagnosis Records Yet" message
const noDxMessage = Array.from(document.querySelectorAll('h3')).some(h3 =>
h3.textContent?.includes('No Diagnosis Records Yet')
);
// Override if we have filled inputs and no "no records" message
if (filledDiagnosisInputs > 3 && !noDxMessage) {
hasDxSupplementalRecordsConfigured = true;
}
console.log('🔧 DEBUG: Prerequisites completed:', hasPrerequisitesCompleted);
console.log('🔧 DEBUG: Filled diagnosis inputs:', filledDiagnosisInputs);
console.log('🔧 DEBUG: Dx Supplemental configured:', hasDxSupplementalRecordsConfigured);
} catch (error) {
console.log('🔧 DEBUG: Error checking Tab 5 status:', error);
hasDxSupplementalRecordsConfigured = false;
hasPrerequisitesCompleted = false;
}
if (!hasPrerequisitesCompleted) {
// Show message when previous tabs are not completed
addMessage("🩺 Welcome to Dx Supplemental Builder!", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 1500));
addMessage("The Dx Supplemental Builder helps you manage diagnosis codes and coverage decisions. However, I notice you should complete previous configuration steps first:", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("📋 Recommended Prerequisites:\n\n• Complete Tab 2 - Financial Maximums\n• Complete Tab 3 - Benefit Details\n• Complete Tab 4 - MSAG Builder\n\n💡 These provide the foundation for comprehensive diagnosis code management", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("What would you like to do?", 'assistant', [
'Go back to complete previous tabs',
'Learn about Dx Supplemental Builder',
'Start with basic diagnosis setup',
'Complete configuration',
'Continue to section 6'
]);
} else if (!hasDxSupplementalRecordsConfigured) {
// Show comprehensive welcome when prerequisites are met but no diagnosis records created
addMessage("🩺 Welcome to Dx Supplemental Builder!", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 1500));
addMessage("Excellent! You've completed the foundational configuration steps. Now let's set up diagnosis code management for comprehensive coverage control and clinical accuracy.", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("🔧 Dx Supplemental Components:\n\n• Diagnosis Classification 📋\n Organize conditions into clinical categories\n\n• ICD-10 Code Management 💻\n Assign specific diagnostic codes\n\n• Coverage Decisions 🔐\n Define which diagnoses are covered\n\n• Variation Specifications 📝\n Handle special cases and exclusions", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2500));
addMessage("Configuration Process:\n\n1️⃣ Add diagnosis records (default templates or custom entries)\n\n2️⃣ Classify diagnoses into clinical groups\n\n3️⃣ Assign accurate ICD-10 codes using the built-in picker\n\n4️⃣ Set coverage decisions and define variations\n\n5️⃣ Bulk upload for large diagnosis sets", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("How can I help you build your diagnosis supplemental configuration?", 'assistant', [
'Guide me through adding diagnosis records',
'Help with ICD-10 code selection',
'Explain diagnosis classification',
'Coverage decision best practices',
'Bulk upload assistance',
'Complete configuration',
'Continue to section 6'
]);
} else {
// Show different messages when diagnosis records are already configured
addMessage("🩺 Dx Supplemental Builder - Configuration Active!", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 1500));
addMessage("Outstanding! I can see you have diagnosis supplemental records configured. Need help with optimization, validation, or expanding your current diagnosis management setup?", 'assistant', [
'Review my diagnosis configuration',
'Validate ICD-10 code accuracy',
'Optimize coverage decisions',
'Add more diagnosis records',
'Clinical compliance check',
'Best practices review',
'Complete configuration'
]);
}
}
setWorkflowState(prev => ({
...prev,
isInTab1Workflow: false,
isInTab2Workflow: false,
isInTab3Workflow: false,
isInTab4Workflow: false,
isInTab5Workflow: true,
currentStep: 'tab5_guidance',
hasShownTabWorkflow: true
}));
setIsTyping(false);
};
const initializeChat = async () => {
setIsTyping(true);
// Check which tab we're on and handle tab-specific workflows
const isInTab1 = documentState.currentStep === 1;
const isInTab2 = documentState.currentStep === 2;
const isInTab3 = documentState.currentStep === 3;
const isInTab4 = documentState.currentStep === 4;
// Handle Tab 4 - MSAG Builder
if (isInTab4) {
await triggerTab4Workflow();
setIsTyping(false);
return;
}
// Handle Tab 3 - Benefit Details
if (isInTab3) {
await triggerTab3Workflow();
setIsTyping(false);
return;
}
// Handle Tab 2 - Financial Maximums
if (isInTab2) {
// Check if financial maximums are selected by looking at DOM
let hasSelectedFinancialMaximums = false;
try {
// Debug logging to understand the DOM structure
console.log('🔧 DEBUG: Checking Tab 2 financial maximums selection...');
// Primary method: Check for the "no selection" message
const allParagraphs = document.querySelectorAll('p');
let noOptionsMessage = false;
for (let i = 0; i < allParagraphs.length; i++) {
if (allParagraphs[i].textContent?.includes('Select Financial Maximum options above')) {
noOptionsMessage = true;
break;
}
}
console.log('🔧 DEBUG: No options message found:', noOptionsMessage);
// Method 2: Check for configuration sections
const allHeaders = document.querySelectorAll('h4');
let hasConfigSections = false;
for (let i = 0; i < allHeaders.length; i++) {
const headerText = allHeaders[i].textContent || '';
if (headerText.includes('Deductible Details') || headerText.includes('Out-of-Pocket Maximum Details')) {
hasConfigSections = true;
break;
}
}
console.log('🔧 DEBUG: Config sections exist:', hasConfigSections);
// Determine selection status
if (noOptionsMessage) {
hasSelectedFinancialMaximums = false;
} else if (hasConfigSections) {
hasSelectedFinancialMaximums = true;
} else {
hasSelectedFinancialMaximums = false;
}
console.log('🔧 DEBUG: Final result:', hasSelectedFinancialMaximums);
} catch (error) {
console.log('🔧 DEBUG: Error checking financial maximums selection:', error);
// Default to false if there's an error - this will show the welcome message
hasSelectedFinancialMaximums = false;
}
if (!hasSelectedFinancialMaximums) {
// Show Tab 2 specific welcome messages when no financial maximums are selected
await new Promise(resolve => setTimeout(resolve, 1500));
addMessage("👋 Welcome to Financial Maximums Configuration!", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("This is where you'll set up the core cost-sharing structures for your benefit plan. Let me guide you through the available options:", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2500));
addMessage("🏗️ Available Financial Maximum Types:\n\n• Deductible 💰\n Amount members pay before coverage begins\n\n• Out-of-Pocket Maximum 📊\n Annual limit on member costs", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 3000));
addMessage("Getting Started:\n\n1️⃣ Drag and drop the financial maximums you need from \"Available Options\" to \"Selected Options\"\n\n2️⃣ Configure the detailed settings for each selected option\n\n3️⃣ I'll help ensure compliance and optimization throughout!", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("What would you like to know about setting up your financial maximums?", 'assistant', [
'Help me choose deductible amounts',
'Explain embedded vs aggregate benefits',
'What are compliance requirements?',
'Show me best practices',
'Continue to section 3'
]);
setWorkflowState(prev => ({
...prev,
isInTab2Workflow: true,
currentStep: 'tab2_guidance',
hasShownTabWorkflow: true
}));
} else {
// Tab 2 with selected options - show different welcome
await new Promise(resolve => setTimeout(resolve, 1500));
addMessage("💰 Financial Maximums - Configuration Active", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 1500));
addMessage("I can see you have financial maximums configured. Need help with any adjustments or have questions about your current setup?", 'assistant', [
'Review my configuration',
'Compliance check',
'Optimization suggestions',
'Add more options',
'Continue to section 3'
]);
setWorkflowState(prev => ({
...prev,
isInTab2Workflow: true,
currentStep: 'tab2_guidance',
hasShownTabWorkflow: true
}));
}
setIsTyping(false);
return;
}
// Standard workflow for other tabs (Tab 1, Tab 4, etc.)
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Hello! I'm your DIY Benefits Assistant", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2500));
addMessage("I can help you in configuring the DIY Benefits and client onboarding.", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 3000));
addMessage("Please confirm if you need my help in configuring the DIY Agent", 'assistant', ['Continue', 'Exit']);
// Set workflow state but don't proceed until user confirms
if (isInTab1) {
setWorkflowState(prev => ({ ...prev, isInTab1Workflow: true, currentStep: 'awaiting_confirmation' }));
} else {
setWorkflowState(prev => ({ ...prev, isInTab1Workflow: false, currentStep: 'awaiting_confirmation' }));
}
setIsTyping(false);
};
const addMessage = (text: string, sender: 'assistant' | 'user', options?: string[], showClientLookup?: boolean) => {
const newMessage: Message = {
id: Date.now().toString(),
text,
sender,
timestamp: new Date(),
options,
showClientLookup
};
setMessages(prev => [...prev, newMessage]);
};
const handleOptionClick = async (option: string) => {
// Immediate debug log
console.log('🔧 DEBUG CHAT: Button clicked with option:', option);
// Add user's choice
addMessage(option, 'user');
// Remove options from previous message
setMessages(prev => prev.map(msg => ({ ...msg, options: undefined })));
setIsTyping(true);
// Handle Tab 5 specific workflow
if (workflowState.isInTab5Workflow) {
await handleTab5Workflow(option);
}
// Handle Tab 4 specific workflow
else if (workflowState.isInTab4Workflow) {
await handleTab4Workflow(option);
}
// Handle Tab 3 specific workflow
else if (workflowState.isInTab3Workflow) {
await handleTab3Workflow(option);
}
// Handle Tab 2 specific workflow
else if (workflowState.isInTab2Workflow) {
await handleTab2Workflow(option);
}
// Handle Tab 1 specific workflow
else if (workflowState.isInTab1Workflow) {
console.log('🔧 DEBUG CHAT: Entering Tab 1 workflow, current step:', workflowState.currentStep);
await handleTab1Workflow(option);
} else {
// General workflow for other tabs
if (option.toLowerCase() === 'exit') {
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Thank you for visiting! Feel free to reach out anytime if you need assistance with your DIY Benefits configuration. Have a great day! 👋", 'assistant');
setSessionEnded(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Would you like to start a new session?", 'assistant', ['Start New Session']);
} else if (option.toLowerCase() === 'continue') {
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Great! Let's get started on the configuration.", 'assistant');
await new Promise(resolve => setTimeout(resolve, 2500));
addMessage("I'm here to help you through each step of setting up your DIY Benefits. Is there anything specific you'd like assistance with?", 'assistant');
} else if (option.toLowerCase() === 'start new session') {
await new Promise(resolve => setTimeout(resolve, 2000));
setMessages([]);
setSessionEnded(false);
setWorkflowState({
isInTab1Workflow: false,
isInTab2Workflow: false,
isInTab3Workflow: false,
isInTab4Workflow: false,
isInTab5Workflow: false,
currentStep: 'initial',
collectedData: {},
awaitingInput: false,
hasShownTabWorkflow: false,
sessionId: Date.now().toString()
});
initializeChat();
}
}
setIsTyping(false);
};
const handleTab4Workflow = async (option: string) => {
switch (option) {
case 'Go back to complete Tab 2':
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Taking you back to Financial Maximums configuration...", 'assistant');
// Reset workflow state and navigate to Tab 2
setWorkflowState(prev => ({
...prev,
isInTab1Workflow: false,
isInTab2Workflow: false,
isInTab3Workflow: false,
isInTab4Workflow: false,
hasShownTabWorkflow: false
}));
setTimeout(() => {
setCurrentStep(2);
setTimeout(async () => {
await triggerTab2Workflow();
}, 500);
}, 1000);
break;
case 'Go back to complete Tab 3':
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Taking you back to Benefit Details configuration...", 'assistant');
// Reset workflow state and navigate to Tab 3
setWorkflowState(prev => ({
...prev,
isInTab1Workflow: false,
isInTab2Workflow: false,
isInTab3Workflow: false,
isInTab4Workflow: false,
hasShownTabWorkflow: false
}));
setTimeout(() => {
setCurrentStep(3);
setTimeout(async () => {
await triggerTab3Workflow();
}, 500);
}, 1000);
break;
case 'Learn about MSAG Builder':
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("📚 MSAG Builder Overview:", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2500));
addMessage("MSAG (Medical Services Authorization Guidelines) is a comprehensive system that defines:\n\n• Service Type Classifications 📋\n• Authorization Requirements 🔐\n• CPT/HCPCS Code Mappings 💻\n• Benefit Class Associations 💰\n• Claims Processing Rules 📝", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Key Benefits:\n\n• Standardized service definitions\n• Automated authorization workflows\n• Accurate claims processing\n• Regulatory compliance\n• Improved member experience", 'assistant', [
'How does service mapping work?',
'What are authorization classes?',
'Back to main options',
'Continue to section 5'
]);
break;
case 'Guide me through adding services':
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("🎯 Service Addition Guide:", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2500));
addMessage("Step-by-Step Process:\n\n1️⃣ Review Available Services section at the top\n2️⃣ Click '➕ Add Service' button\n3️⃣ Select a service from the dropdown menu\n4️⃣ Configure the MSAG record fields\n5️⃣ Save and validate the configuration", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Important Fields to Configure:\n\n• Service Type: Auto-populated from selection\n• AUTH CLASS: Authorization requirements\n• BENEFIT CLASS: Links to cost-sharing\n• CPT/HCPCS Codes: Procedure identification\n• Modifiers: Additional code specifications", 'assistant', [
'Help with specific field types',
'Show me validation tips',
'Back to main options',
'Continue to section 5'
]);
break;
case 'Explain MSAG components':
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("🔧 MSAG Component Breakdown:", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2500));
addMessage("Core Configuration Fields:\n\n• Service Type: Descriptive name of the medical service\n• AUTH CLASS: Defines authorization requirements (None, Prior Auth, Concurrent)\n• BENEFIT CLASS: Links to deductible/coinsurance rules\n• Rev/HCPCS/CPT: Medical procedure codes (revenue, healthcare common procedure, current procedural terminology)", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Advanced Components:\n\n• Modifiers 1-4: Additional code specifications\n• Add-On Codes: Supplementary procedure codes\n• Place of Service: Where care is delivered (office, hospital, etc.)\n• Coverable Dx Category: Diagnosis categories (Psy, Sub, Psy/Sub)\n• Claim Types: Processing categorization", 'assistant', [
'Help with authorization classes',
'Explain procedure codes',
'Back to main options',
'Continue to section 5'
]);
break;
case 'Help with CPT/HCPCS codes':
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("💻 CPT/HCPCS Code Guidance:", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2500));
addMessage("Code Types Explained:\n\n• CPT Codes: Current Procedural Terminology (10000-99999)\n• HCPCS Codes: Healthcare Common Procedure Coding System (A0000-V9999)\n• Revenue Codes: Hospital billing codes (0001-9999)", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Best Practices:\n\n• Use most specific code available\n• Verify codes are current year\n• Include appropriate modifiers\n• Consider bundling rules\n• Validate against payer policies", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Common Code Categories:\n\n• Evaluation & Management: 99201-99499\n• Mental Health: 90834, 90837, 90847\n• Substance Abuse: 90834, H0001-H9999\n• Preventive Care: 99381-99429", 'assistant', [
'Find codes for specific services',
'Modifier usage guide',
'Back to main options',
'Continue to section 5'
]);
break;
case 'Authorization class setup':
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("🔐 Authorization Class Configuration:", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2500));
addMessage("Authorization Types:\n\n• NONE: No authorization required\n• PRIOR: Prior authorization before service\n• CONCURRENT: Authorization during treatment\n• RETRO: Retrospective review after service\n• NOTIFICATION: Notification only required", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Setup Considerations:\n\n• High-cost services typically require PRIOR\n• Emergency services usually NONE or NOTIFICATION\n• Ongoing treatments may use CONCURRENT\n• Routine services typically NONE\n• Specialty services often PRIOR", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Implementation Tips:\n\n• Balance access with cost management\n• Consider member experience impact\n• Align with network contracts\n• Plan for appeals process\n• Monitor authorization patterns", 'assistant', [
'Emergency service exceptions',
'Prior auth best practices',
'Back to main options',
'Continue to section 5'
]);
break;
case 'Best practices for MSAG':
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("🌟 MSAG Configuration Best Practices:", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2500));
addMessage("Configuration Excellence:\n\n• Consistent naming conventions across all service types\n• Comprehensive code coverage for all benefit areas\n• Clear authorization class definitions\n• Regular updates for new CPT/HCPCS codes\n• Thorough testing before implementation", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2500));
addMessage("Quality Assurance:\n\n• Cross-reference with benefit design\n• Validate against regulatory requirements\n• Test authorization workflows\n• Review claim processing logic\n• Monitor utilization patterns post-implementation", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Ongoing Maintenance:\n\n• Annual CPT code updates\n• Quarterly authorization class reviews\n• Monthly utilization analysis\n• Provider feedback integration\n• Member experience monitoring", 'assistant', [
'Configuration validation checklist',
'Implementation timeline',
'Back to main options',
'Continue to section 5'
]);
break;
case 'Review my MSAG configuration':
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("📊 MSAG Configuration Review:", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2500));
addMessage("I can see you have MSAG records configured. Let me help you validate key areas:\n\n✅ Service type completeness\n✅ Authorization class consistency\n✅ CPT/HCPCS code accuracy\n✅ Benefit class alignment\n✅ Place of service appropriateness", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2000));
// Reset workflow state and navigate to Tab 5 (if it exists)
setWorkflowState(prev => ({
...prev,
isInTab1Workflow: false,
isInTab2Workflow: false,
isInTab3Workflow: false,
isInTab4Workflow: false,
hasShownTabWorkflow: false
}));
setTimeout(() => {
setCurrentStep(5);
console.log('🔧 DEBUG: setCurrentStep(5) called');
}, 1000);
break;
case 'Back to main options':
await new Promise(resolve => setTimeout(resolve, 1500));
addMessage("How else can I help you with MSAG Builder configuration?", 'assistant', [
'Guide me through adding services',
'Explain MSAG components',
'Help with CPT/HCPCS codes',
'Authorization class setup',
'Best practices for MSAG',
'Continue to section 5'
]);
break;
case 'Continue to section 5':
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Excellent! Moving to Dx Supplementary Builder...", 'assistant');
// Debug logging
console.log('🔧 DEBUG: Continue to Section 4 clicked');
console.log('🔧 DEBUG: Current documentState.currentStep:', documentState.currentStep);
console.log('🔧 DEBUG: About to call setCurrentStep(4)');
// Reset workflow state before navigation to ensure new tab workflow triggers
setWorkflowState(prev => ({
...prev,
isInTab1Workflow: false,
isInTab2Workflow: false,
isInTab3Workflow: false,
isInTab4Workflow: false,
hasShownTabWorkflow: false
}));
// Trigger navigation to tab 5
setTimeout(() => {
setCurrentStep(5);
console.log('🔧 DEBUG: setCurrentStep(4) called');
console.log('🔧 DEBUG: New documentState.currentStep should be 4');
// // Trigger Tab 4 workflow after navigation with a delay
// setTimeout(async () => {
// console.log('🔧 DEBUG: Triggering Tab 4 workflow after navigation');
// await triggerTab5Workflow();
// }, 500);
}, 1000);
break;
default:
// Handle sub-options and other detailed cases
if (option.includes('validation') || option.includes('codes') || option.includes('authorization') ||
option.includes('service') || option.includes('configuration')) {
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage(`Great choice! For ${option.toLowerCase()}, I recommend reviewing the MSAG configuration sections above and validating the specific parameters. Each service type has unique considerations for authorization classes, procedure codes, and benefit mappings.`, 'assistant', [
'Back to main options',
'Need more specific guidance',
'Continue to section 5'
]);
} else {
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("I'd be happy to help you with that! Feel free to ask me any specific questions about MSAG Builder configuration, or select from the options below:", 'assistant', [
'Guide me through adding services',
'Explain MSAG components',
'Help with CPT/HCPCS codes',
'Authorization class setup',
'Best practices for MSAG',
'Continue to section 5'
]);
}
break;
}
};
const handleTab3Workflow = async (option: string) => {
switch (option) {
case 'Help with outpatient benefits':
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("🏥 Outpatient Benefits Configuration:", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2500));
addMessage("Key Outpatient Services:\n\n• Primary Care Physician visits\n• Specialist consultations\n• Diagnostic tests and lab work\n• Preventive care services\n• Urgent care visits", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Configuration Options:\n\n• Set copay amounts ($20-$50 typical for PCP)\n• Configure coinsurance percentages (10%-30%)\n• Define prior authorization requirements\n• Establish network tiers and access", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Need help with a specific outpatient service type?", 'assistant', [
'Primary care configuration',
'Specialist visit setup',
'Diagnostic services',
'Back to main options',
'Continue to section 4'
]);
break;
case 'Configure inpatient services':
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("🏨 Inpatient Services Configuration:", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2500));
addMessage("Inpatient Coverage Areas:\n\n• Hospital facility charges\n• Room and board costs\n• Surgical procedures\n• Emergency department visits\n• Ambulance services", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Typical Configuration:\n\n• Per-day copays or coinsurance\n• Annual limits and maximums\n• Pre-certification requirements\n• Network facility restrictions\n• Emergency vs non-emergency handling", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("What aspect of inpatient services would you like to configure?", 'assistant', [
'Hospital facility charges',
'Emergency services',
'Surgical procedures',
'Back to main options',
'Continue to section 4'
]);
break;
case 'Set up pharmacy benefits':
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("💊 Pharmacy Benefits Setup:", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2500));
addMessage("Pharmacy Benefit Structure:\n\n• Generic drugs (Tier 1): $10-$15 copay\n• Preferred brand (Tier 2): $30-$50 copay\n• Non-preferred brand (Tier 3): $60-$100 copay\n• Specialty drugs (Tier 4): 20%-40% coinsurance", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Configuration Considerations:\n\n• Mail-order vs retail pricing\n• Prior authorization requirements\n• Quantity limits and refill restrictions\n• Step therapy protocols\n• Formulary management", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Which pharmacy benefit area needs configuration?", 'assistant', [
'Drug tier setup',
'Mail-order benefits',
'Prior authorization rules',
'Back to main options',
'Continue to section 4'
]);
break;
case 'Set up other benefits':
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("💊 Other Benefits Configuration:", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2500));
addMessage("Additional Benefit Categories:\n\n• Vision Benefits: Eye exams, glasses, contacts\n• Dental Benefits: Preventive, basic, major services\n• Mental Health: Therapy, counseling, psychiatric care\n• Maternity: Prenatal, delivery, postnatal care\n• Wellness Programs: Health screenings, fitness", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Which other benefit would you like to configure?", 'assistant', [
'Vision benefits',
'Dental benefits',
'Mental health services',
'Maternity coverage',
'Back to main options',
'Continue to section 4'
]);
break;
case 'Claims and special handling':
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("📝 Claims & Special Handling Instructions:", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2500));
addMessage("Special Handling Categories:\n\n• Pre-existing condition exclusions\n• Coordination of benefits (COB)\n• Workers' compensation offsets\n• Medicare coordination\n• Third-party liability claims", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Which area needs configuration?", 'assistant', [
'Pre-existing conditions',
'COB procedures',
'Appeal processes',
'Provider requirements',
'Back to main options',
'Continue to section 4'
]);
break;
case 'Explain authorization requirements':
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("🔐 Authorization Requirements Guide:", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2500));
addMessage("Prior Authorization Types:\n\n• Pre-certification: Required before service\n• Pre-determination: Benefit verification only\n• Concurrent review: During treatment\n• Retrospective review: After service delivery", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Common Authorization Services:\n\n• Specialist referrals\n• High-cost imaging (MRI, CT)\n• Surgical procedures\n• Durable medical equipment\n• Specialty medications", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Best Practices:\n\n• Clear criteria and timelines\n• Member and provider communication\n• Appeals process definition\n• Emergency service exceptions", 'assistant', [
'Set up authorization rules',
'Emergency exceptions',
'Appeals process',
'Back to main options',
'Continue to section 4'
]);
break;
case 'Best practices for benefit design':
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("🌟 Benefit Design Best Practices:", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2500));
addMessage("Member Experience Focus:\n\n• Predictable cost-sharing structure\n• Clear communication of benefits\n• Easy access to preventive care\n• Reasonable network access standards\n• Transparent prior authorization", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2500));
addMessage("Cost Management Strategies:\n\n• Tiered network design\n• Value-based benefit structures\n• Generic drug incentives\n• Preventive care investment\n• Care management integration", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Regulatory Compliance:\n\n• ACA essential health benefits\n• State insurance regulations\n• Network adequacy standards\n• Quality reporting requirements", 'assistant', [
'Member communication tips',
'Cost optimization strategies',
'Compliance checklist',
'Back to main options',
'Continue to section 4'
]);
break;
case 'Back to main options':
await new Promise(resolve => setTimeout(resolve, 1500));
addMessage("How else can I help you configure your benefit details?", 'assistant', [
'Help with outpatient benefits',
'Configure inpatient services',
'Set up other benefits',
'Claims and special handling',
'Best practices for benefit design',
'Continue to section 4'
]);
break;
case 'Continue to section 4':
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Excellent! Moving to Approval & Completion (Section 4)...", 'assistant');
// Debug logging
console.log('🔧 DEBUG: Continue to Section 4 clicked');
console.log('🔧 DEBUG: Current documentState.currentStep:', documentState.currentStep);
console.log('🔧 DEBUG: About to call setCurrentStep(4)');
// Reset workflow state before navigation to ensure new tab workflow triggers
setWorkflowState(prev => ({
...prev,
isInTab1Workflow: false,
isInTab2Workflow: false,
isInTab3Workflow: false,
hasShownTabWorkflow: false
}));
// Trigger navigation to tab 4
setTimeout(() => {
setCurrentStep(4);
console.log('🔧 DEBUG: setCurrentStep(4) called');
console.log('🔧 DEBUG: New documentState.currentStep should be 4');
// // Trigger Tab 4 workflow after navigation with a delay (commented out to prevent duplicate messages)
// setTimeout(async () => {
// console.log('🔧 DEBUG: Triggering Tab 4 workflow after navigation');
// await triggerTab4Workflow();
// }, 500);
}, 1000);
break;
default:
// Handle sub-options and other detailed cases
if (option.includes('Primary care') || option.includes('Specialist') || option.includes('Drug tier') ||
option.includes('Hospital') || option.includes('Emergency') || option.includes('authorization')) {
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage(`Great choice! For ${option.toLowerCase()}, I recommend reviewing the benefit design sections above and configuring the specific parameters. Each service type has unique considerations for copays, coinsurance, and authorization requirements.`, 'assistant', [
'Back to main options',
'Need more specific guidance',
'Continue to section 4'
]);
} else {
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("I'd be happy to help you with that! Feel free to ask me any specific questions about benefit details configuration, or select from the options below:", 'assistant', [
'Help with outpatient benefits',
'Configure inpatient services',
'Set up other benefits',
'Claims and special handling',
'Best practices for benefit design',
'Continue to section 4'
]);
}
break;
}
};
const handleTab2Workflow = async (option: string) => {
switch (option) {
case 'Help me choose deductible amounts':
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("💡 Deductible Amount Guidance:", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2500));
addMessage("2026 ACA Compliance Limits:\n\n• Individual: Maximum $1,650\n• Family: Maximum $3,300", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Typical Ranges by Plan Type:\n\n• High Deductible Health Plans (HDHP): $1,500-$1,650 individual\n• Standard Plans: $500-$1,200 individual\n• Premium Plans: $250-$750 individual", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Would you like help with a specific plan type or need more guidance?", 'assistant', [
'HDHP recommendations',
'Standard plan guidance',
'Compliance validation',
'Back to main options',
'Continue to section 3'
]);
break;
case 'Explain embedded vs aggregate benefits':
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("🏠 Embedded vs Aggregate Benefits Explained:", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2500));
addMessage("Embedded Benefit 🏠\n\n• Individual limits within family coverage\n• Example: Individual $2,000, Family $4,000\n• One person can't pay more than $2,000", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2500));
addMessage("Aggregate Benefit 📊\n\n• Family pool approach\n• Example: EE $2,000, Family $4,000\n• Family must reach $4,000 total before coverage kicks in", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("💡 Recommendation: Most family-friendly plans use embedded benefits to protect individual members from high costs.", 'assistant', [
'Which should I choose?',
'Cost impact examples',
'Back to main options',
'Continue to section 3'
]);
break;
case 'What are compliance requirements?':
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("⚖️ 2026 Compliance Requirements:", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2500));
addMessage("ACA Maximum Limits:\n\n• Individual Deductible: $1,650\n• Family Deductible: $3,300\n• Individual Out-of-Pocket: $9,200\n• Family Out-of-Pocket: $18,400", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Key Requirements:\n\n✅ Out-of-pocket maximums must include deductibles\n✅ In-network and out-of-network can have separate limits\n✅ Essential health benefits must count toward maximums", 'assistant', [
'Validate my configuration',
'State-specific requirements',
'Back to main options',
'Continue to section 3'
]);
break;
case 'Show me best practices':
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("🌟 Financial Maximums Best Practices:", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2500));
addMessage("Structure Recommendations:\n\n• Use embedded benefits for family coverage\n• Set out-of-network deductibles 2-3x higher than in-network\n• Ensure out-of-pocket maximum is 3-5x the deductible", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2500));
addMessage("Member Experience:\n\n• Clear communication about combined vs separate limits\n• Consider cost-sharing reduction for lower-income members\n• Provide cost calculators and examples", 'assistant', [
'Member communication tips',
'Cost optimization strategies',
'Back to main options',
'Continue to section 3'
]);
break;
case 'Back to main options':
await new Promise(resolve => setTimeout(resolve, 1500));
addMessage("What else would you like to know about setting up your financial maximums?", 'assistant', [
'Help me choose deductible amounts',
'Explain embedded vs aggregate benefits',
'What are compliance requirements?',
'Show me best practices',
'Continue to section 3'
]);
break;
case 'Continue to section 3':
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Great! Moving to Benefit Details (Section 3)...", 'assistant');
// Debug logging
console.log('🔧 DEBUG: Continue to Section 3 clicked');
console.log('🔧 DEBUG: Current documentState.currentStep:', documentState.currentStep);
console.log('🔧 DEBUG: About to call setCurrentStep(3)');
// Reset workflow state before navigation to ensure new tab workflow triggers
setWorkflowState(prev => ({
...prev,
isInTab1Workflow: false,
isInTab2Workflow: false,
isInTab3Workflow: false,
hasShownTabWorkflow: false
}));
// Trigger navigation to tab 3
setTimeout(() => {
setCurrentStep(3);
console.log('🔧 DEBUG: setCurrentStep(3) called');
console.log('🔧 DEBUG: New documentState.currentStep should be 3');
// // Trigger Tab 3 workflow after navigation with a delay (commented out to prevent duplicate messages)
// setTimeout(async () => {
// console.log('🔧 DEBUG: Triggering Tab 3 workflow after navigation');
// await triggerTab3Workflow();
// }, 500);
}, 1000);
break;
default:
// Handle sub-options and other cases
if (option.includes('HDHP') || option.includes('Standard') || option.includes('Premium')) {
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage(`Great choice! For ${option.toLowerCase()} plans, I recommend starting with the drag-and-drop interface above to select your financial maximums, then I can provide specific amount recommendations based on your selections.`, 'assistant', [
'Back to main options',
'Need more specific guidance',
'Continue to section 3'
]);
} else {
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("I'd be happy to help you with that! Feel free to ask me any specific questions about financial maximums configuration, or select from the options below:", 'assistant', [
'Help me choose deductible amounts',
'Explain embedded vs aggregate benefits',
'What are compliance requirements?',
'Show me best practices',
'Continue to section 3'
]);
}
break;
}
};
const handleTab1Workflow = async (option: string) => {
switch (workflowState.currentStep) {
case 'awaiting_confirmation':
if (option.toLowerCase() === 'continue') {
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Great! Let's get started on the configuration.", 'assistant');
// Check if we've already shown tab workflow in this session
if (!workflowState.hasShownTabWorkflow) {
await new Promise(resolve => setTimeout(resolve, 2500));
addMessage("Do you want to onboard a new client or use an existing client?", 'assistant', ['Onboard new client', 'Use existing client']);
setWorkflowState(prev => ({ ...prev, currentStep: 'initial', hasShownTabWorkflow: true }));
} else {
// Skip to general assistance if workflow was already shown
await new Promise(resolve => setTimeout(resolve, 2500));
addMessage("I'm here to help you through each step of setting up your DIY Benefits. Is there anything specific you'd like assistance with?", 'assistant');
setWorkflowState(prev => ({ ...prev, currentStep: 'completed' }));
}
} else if (option.toLowerCase() === 'exit') {
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Thank you for visiting! Feel free to reach out anytime if you need assistance with your DIY Benefits configuration. Have a great day! 👋", 'assistant');
setSessionEnded(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Would you like to start a new session?", 'assistant', ['Start New Session']);
}
break;
case 'initial':
if (option === 'Onboard new client') {
setWorkflowState(prev => ({ ...prev, currentStep: 'collect_client_name' }));
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Please provide the name of the Client.", 'assistant');
setWorkflowState(prev => ({ ...prev, awaitingInput: true, inputType: 'clientName' }));
} else if (option === 'Use existing client') {
setWorkflowState(prev => ({ ...prev, currentStep: 'show_client_lookup' }));
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Please enter a filter to search for the available clients", 'assistant');
// Show client lookup component
addMessage("", 'assistant', [], true); // Empty message with client lookup flag
}
break;
case 'collect_parent_code':
if (option === 'Continue to next step') {
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("What is the client type?", 'assistant', ['State', 'Employer', 'Health Plan', 'Other']);
setWorkflowState(prev => ({ ...prev, currentStep: 'collect_client_type', awaitingInput: false }));
}
break;
case 'collect_client_type':
setWorkflowState(prev => ({
...prev,
collectedData: { ...prev.collectedData, clientType: option },
currentStep: 'collect_line_of_business'
}));
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Please select the line of Business", 'assistant', ['Medicare', 'Medicaid', 'Commercial']);
break;
case 'collect_line_of_business':
setWorkflowState(prev => ({
...prev,
collectedData: { ...prev.collectedData, lineOfBusiness: option },
currentStep: 'setup_client_info'
}));
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Thank you for providing the details. Let me set up the client information for us to get started", 'assistant');
// Update document context with collected data - FIX: Use correct values from workflowState
updateClientInformation({
clientName: workflowState.collectedData.clientName || '',
parentCode: workflowState.collectedData.parentCode || '',
clientType: workflowState.collectedData.clientType as any, // Use stored client type
lineOfBusiness: option as any // Use the current option for line of business
});
await new Promise(resolve => setTimeout(resolve, 2500));
addMessage("As part of next steps we need to set up the Effective date and Term Date for the Benefit.", 'assistant');
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Do you want to use the current calendar year for the Effective and Term Dates?", 'assistant', ['Yes', 'No']);
setWorkflowState(prev => ({ ...prev, currentStep: 'calendar_year_option' }));
// Trigger focus on the Effective Date field in the client information tab
setTimeout(() => {
const effectiveDateInput = document.querySelector('input[type="date"][placeholder*="effective" i], input[type="date"][name*="effective" i], input[id*="effective" i]') as HTMLInputElement;
if (effectiveDateInput) {
effectiveDateInput.focus();
effectiveDateInput.scrollIntoView({ behavior: 'smooth', block: 'center' });
} else {
// Fallback: try to find any date input in the client information section
const dateInputs = document.querySelectorAll('input[type="date"]');
if (dateInputs.length > 0) {
(dateInputs[0] as HTMLInputElement).focus();
(dateInputs[0] as HTMLInputElement).scrollIntoView({ behavior: 'smooth', block: 'center' });
}
}
}, 500);
break;
case 'calendar_year_option':
if (option === 'Yes') {
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Thanks for the confirmation", 'assistant');
// Set the current calendar year dates
updateClientInformation({
effectiveDate: '2026-01-01',
termDate: '2026-12-31'
});
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Great! I've set the Effective Date to 2026-01-01 and Term Date to 2026-12-31.", 'assistant');
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Now we need to provide the email ids of the Approvers and Core Admin Platform to Complete the Client configuration", 'assistant', ['Continue']);
setWorkflowState(prev => ({ ...prev, currentStep: 'await_approvers' }));
// Focus on the Approver Emails field
setTimeout(() => {
const approverInput = document.querySelector('input[placeholder*="approver" i], input[name*="approver" i], input[type="email"]') as HTMLInputElement;
if (approverInput) {
approverInput.focus();
approverInput.scrollIntoView({ behavior: 'smooth', block: 'center' });
}
}, 500);
} else if (option === 'No') {
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Thanks for the confirmation, please provide the required dates and press continue", 'assistant', ['Continue']);
setWorkflowState(prev => ({ ...prev, currentStep: 'await_dates' }));
// Focus on the first empty date field (effective date or term date)
setTimeout(() => {
const { effectiveDate, termDate } = documentState.clientInformation;
let focusSelector = '';
if (!effectiveDate) {
focusSelector = 'input[type="date"][placeholder*="effective" i], input[type="date"][name*="effective" i], input[id*="effective" i]';
} else if (!termDate) {
focusSelector = 'input[type="date"][placeholder*="term" i], input[type="date"][name*="term" i], input[id*="term" i]';
} else {
// Both fields are empty, focus on effective date first
focusSelector = 'input[type="date"][placeholder*="effective" i], input[type="date"][name*="effective" i], input[id*="effective" i]';
}
const targetInput = document.querySelector(focusSelector) as HTMLInputElement;
if (targetInput) {
targetInput.focus();
targetInput.scrollIntoView({ behavior: 'smooth', block: 'center' });
} else {
// Fallback: try to find any date input in the client information section
const dateInputs = document.querySelectorAll('input[type="date"]');
if (dateInputs.length > 0) {
(dateInputs[0] as HTMLInputElement).focus();
(dateInputs[0] as HTMLInputElement).scrollIntoView({ behavior: 'smooth', block: 'center' });
}
}
}, 500);
}
break;
case 'await_dates':
if (option === 'Continue') {
// Validate effective date and term date before proceeding
const { effectiveDate, termDate } = documentState.clientInformation;
if (!effectiveDate || !termDate) {
await new Promise(resolve => setTimeout(resolve, 2000));
// Determine which specific field is missing and provide targeted guidance
let missingField = '';
let focusSelector = '';
if (!effectiveDate) {
// Effective Date is missing - prioritize this field
missingField = 'Effective Date';
focusSelector = 'input[type="date"][placeholder*="effective" i], input[type="date"][name*="effective" i], input[id*="effective" i]';
} else if (!termDate) {
// Only Term Date is missing
missingField = 'Term Date';
focusSelector = 'input[type="date"][placeholder*="term" i], input[type="date"][name*="term" i], input[id*="term" i]';
}
addMessage(`${missingField} is required. Please provide a valid date.`, 'assistant', ['Continue']);
// Focus on the specific missing field
setTimeout(() => {
const targetInput = document.querySelector(focusSelector) as HTMLInputElement;
if (targetInput) {
targetInput.focus();
targetInput.scrollIntoView({ behavior: 'smooth', block: 'center' });
// Enhanced visual feedback for missing field
targetInput.style.boxShadow = '0 0 0 3px rgba(220, 38, 38, 0.4)';
targetInput.style.borderColor = '#dc2626';
targetInput.style.backgroundColor = '#fef2f2';
setTimeout(() => {
targetInput.style.boxShadow = '';
targetInput.style.borderColor = '';
targetInput.style.backgroundColor = '';
}, 3000);
} else {
// Fallback: target date inputs by position
const allDateInputs = document.querySelectorAll('input[type="date"]');
if (allDateInputs.length > 0) {
// If looking for term date and effective date exists, target second input
const targetIndex = (!termDate && effectiveDate) ? Math.min(1, allDateInputs.length - 1) : 0;
const fallbackInput = allDateInputs[targetIndex] as HTMLInputElement;
fallbackInput.focus();
fallbackInput.scrollIntoView({ behavior: 'smooth', block: 'center' });
}
}
}, 500);
return; // Don't proceed to next step
}
// Both dates provided, proceed to next step
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Great! We just need to provide the email ids of the Approvers and Core Admin Platform to Complete the Client configuration", 'assistant', ['Continue']);
setWorkflowState(prev => ({ ...prev, currentStep: 'await_approvers' }));
// Focus on the Approver Emails field
setTimeout(() => {
const approverInput = document.querySelector('input[placeholder*="approver" i], input[name*="approver" i], input[type="email"]') as HTMLInputElement;
if (approverInput) {
approverInput.focus();
approverInput.scrollIntoView({ behavior: 'smooth', block: 'center' });
}
}, 500);
}
break;
case 'await_approvers':
if (option === 'Continue') {
// Check if Core Admin Platform has been provided
const { exportTargets } = documentState.clientInformation;
if (!exportTargets || exportTargets.length === 0 || exportTargets.every(target => !target || target.trim() === '')) {
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Please select the Core Admin Platform where you want to setup this client", 'assistant', ['CAS', 'Flexcare']);
setWorkflowState(prev => ({ ...prev, currentStep: 'select_core_admin_platform' }));
return; // Don't proceed to next step
}
// Core Admin Platform is provided, proceed to standard configuration question
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Do you want to use the standard configurations based on your client type and line of business for generating your Business documents?", 'assistant', ['Yes', 'No']);
setWorkflowState(prev => ({ ...prev, currentStep: 'standard_configuration' }));
}
break;
case 'select_core_admin_platform':
// Handle CAS or Flexcare selection
await new Promise(resolve => setTimeout(resolve, 1500));
addMessage(`Great! I've selected ${option} as your Core Admin Platform.`, 'assistant');
// Update the exportTargets in document state with the selected platform
updateClientInformation({ exportTargets: [option] });
await new Promise(resolve => setTimeout(resolve, 1500));
addMessage("Do you want to use the standard configurations based on your client type and line of business for generating your Business documents?", 'assistant', ['Yes', 'No']);
setWorkflowState(prev => ({ ...prev, currentStep: 'standard_configuration' }));
break;
case 'standard_configuration':
if (option === 'Yes') {
await new Promise(resolve => setTimeout(resolve, 1500));
addMessage("Setting up the Benefit Design Document Configurations", 'assistant');
// Random delay between 1.5-2.5 seconds
const delay1 = 1500 + Math.random() * 1000;
await new Promise(resolve => setTimeout(resolve, delay1));
addMessage("Setting up the Master Service/Auth Grid (MSAG) Document Configurations", 'assistant');
// Random delay between 1.5-2.5 seconds
const delay2 = 1500 + Math.random() * 1000;
await new Promise(resolve => setTimeout(resolve, delay2));
addMessage("Setting up Diagnostic Supplements Document Configurations", 'assistant');
// Update useStandardConfiguration to true
updateClientInformation({ useStandardConfiguration: true });
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Standard configurations have been applied successfully!", 'assistant');
await new Promise(resolve => setTimeout(resolve, 1500));
addMessage("All Done. Client configuration is all completed. Please confirm if we can proceed to the next section", 'assistant', ['Continue to Section 2']);
setWorkflowState(prev => ({ ...prev, currentStep: 'final_step' }));
} else if (option === 'No') {
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Thank you for your confirmation", 'assistant');
// Update useStandardConfiguration to false
updateClientInformation({ useStandardConfiguration: false });
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Validating configuration...", 'assistant');
// Wait for validation period
await new Promise(resolve => setTimeout(resolve, 3000));
// Show completion message
addMessage("All Done. Client configuration is all completed. Please confirm if we can proceed to the next section", 'assistant', ['Continue to Section 2']);
setWorkflowState(prev => ({ ...prev, currentStep: 'final_step' }));
}
break;
case 'final_step':
if (option === 'Continue to Section 2') {
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Perfect! Client configuration is complete. Moving to the next section...", 'assistant');
// Debug logging
console.log('🔧 DEBUG: Continue to Section 2 clicked');
console.log('🔧 DEBUG: Current documentState.currentStep:', documentState.currentStep);
console.log('🔧 DEBUG: About to call setCurrentStep(2)');
// Reset workflow state before navigation to ensure new tab workflow triggers
setWorkflowState(prev => ({
...prev,
isInTab1Workflow: false,
isInTab2Workflow: false,
isInTab3Workflow: false,
hasShownTabWorkflow: false
}));
// Trigger navigation to tab 2
setTimeout(() => {
setCurrentStep(2);
console.log('🔧 DEBUG: setCurrentStep(2) called');
console.log('🔧 DEBUG: New documentState.currentStep should be 2');
// // Trigger Tab 2 workflow after navigation with a delay (commented out to prevent duplicate messages)
// setTimeout(async () => {
// console.log('🔧 DEBUG: Triggering Tab 2 workflow after navigation');
// await triggerTab2Workflow();
// }, 500);
}, 1000);
}
break;
}
};
const handleTextInput = (input: string) => {
if (!workflowState.awaitingInput) return;
addMessage(input, 'user');
setIsTyping(true);
setTimeout(async () => {
if (workflowState.inputType === 'clientName') {
setWorkflowState(prev => ({
...prev,
collectedData: { ...prev.collectedData, clientName: input },
currentStep: 'collect_parent_code',
awaitingInput: true,
inputType: 'parentCode'
}));
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Please provide a three digit character Parent/Client code that you need to assign. For e.g. MDH for Maryland Department of Health.", 'assistant');
} else if (workflowState.inputType === 'parentCode') {
setWorkflowState(prev => ({
...prev,
collectedData: { ...prev.collectedData, parentCode: input },
awaitingInput: false
}));
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Thank you! Now let's continue with the client type.", 'assistant', ['Continue to next step']);
}
setIsTyping(false);
}, 2000);
};
const handleClientSelection = (client: any) => {
setIsTyping(true);
setTimeout(async () => {
// Update workflow state with selected client data
setWorkflowState(prev => ({
...prev,
collectedData: {
clientName: client.name,
parentCode: client.parentCode,
clientType: 'State',
lineOfBusiness: 'Medicare'
},
currentStep: 'setup_client_info'
}));
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Thank you for providing the details. Let me set up the client information for us to get started", 'assistant');
// Update document context with selected client data
updateClientInformation({
clientName: client.name,
parentCode: client.parentCode,
clientType: 'State',
lineOfBusiness: 'Medicare'
});
await new Promise(resolve => setTimeout(resolve, 2500));
addMessage("As part of next steps we need to set up the Effective date and Term Date for the Benefit.", 'assistant');
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Do you want to use the current calendar year for the Effective and Term Dates?", 'assistant', ['Yes', 'No']);
setWorkflowState(prev => ({ ...prev, currentStep: 'calendar_year_option' }));
// Trigger focus on the Effective Date field in the client information tab
setTimeout(() => {
const effectiveDateInput = document.querySelector('input[type="date"][placeholder*="effective" i], input[type="date"][name*="effective" i], input[id*="effective" i]') as HTMLInputElement;
if (effectiveDateInput) {
effectiveDateInput.focus();
effectiveDateInput.scrollIntoView({ behavior: 'smooth', block: 'center' });
} else {
// Fallback: try to find any date input in the client information section
const dateInputs = document.querySelectorAll('input[type="date"]');
if (dateInputs.length > 0) {
(dateInputs[0] as HTMLInputElement).focus();
}
}
}, 500);
setIsTyping(false);
}, 2000);
};
const toggleChat = () => {
setIsOpen(!isOpen);
};
const resetChat = () => {
setMessages([]);
setSessionEnded(false);
setIsTyping(false);
setWorkflowState({
isInTab1Workflow: false,
isInTab2Workflow: false,
isInTab3Workflow: false,
isInTab4Workflow: false,
isInTab5Workflow: false,
currentStep: 'initial',
collectedData: {},
awaitingInput: false,
hasShownTabWorkflow: false,
sessionId: Date.now().toString()
});
if (isOpen) {
initializeChat();
}
};
const handleTab5Workflow = async (option: string) => {
switch (option) {
case 'Go back to complete previous tabs':
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("I'll help you navigate back to complete the previous configuration steps...", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 1500));
addMessage("Which section would you like to complete first?", 'assistant', [
'Go to Tab 2 - Financial Maximums',
'Go to Tab 3 - Benefit Details',
'Go to Tab 4 - MSAG Builder',
'Back to main options',
'Continue to section 6'
]);
break;
case 'Go to Tab 2 - Financial Maximums':
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Taking you back to Financial Maximums configuration...", 'assistant');
// Reset workflow state and navigate to Tab 2
setWorkflowState(prev => ({
...prev,
isInTab1Workflow: false,
isInTab2Workflow: false,
isInTab3Workflow: false,
isInTab4Workflow: false,
isInTab5Workflow: false,
hasShownTabWorkflow: false
}));
setTimeout(() => {
setCurrentStep(2);
setTimeout(async () => {
await triggerTab2Workflow();
}, 500);
}, 1000);
break;
case 'Go to Tab 3 - Benefit Details':
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Taking you back to Benefit Details configuration...", 'assistant');
// Reset workflow state and navigate to Tab 3
setWorkflowState(prev => ({
...prev,
isInTab1Workflow: false,
isInTab2Workflow: false,
isInTab3Workflow: false,
isInTab4Workflow: false,
isInTab5Workflow: false,
hasShownTabWorkflow: false
}));
setTimeout(() => {
setCurrentStep(3);
setTimeout(async () => {
await triggerTab3Workflow();
}, 500);
}, 1000);
break;
case 'Go to Tab 4 - MSAG Builder':
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Taking you back to MSAG Builder configuration...", 'assistant');
// Reset workflow state and navigate to Tab 4
setWorkflowState(prev => ({
...prev,
isInTab1Workflow: false,
isInTab2Workflow: false,
isInTab3Workflow: false,
isInTab4Workflow: false,
isInTab5Workflow: false,
hasShownTabWorkflow: false
}));
setTimeout(() => {
setCurrentStep(4);
setTimeout(async () => {
await triggerTab4Workflow();
}, 500);
}, 1000);
break;
case 'Learn about Dx Supplemental Builder':
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("📚 Dx Supplemental Builder Overview:", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2500));
addMessage("Dx Supplemental Builder is a comprehensive diagnosis management system that defines:\n\n• Diagnosis Classification Systems 📋\n• ICD-10 Code Assignments 💻\n• Coverage Decision Framework 🔐\n• Clinical Variation Specifications 📝\n• Bulk Management Capabilities 📂", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Key Benefits:\n\n• Standardized diagnosis categorization\n• Accurate ICD-10 code management\n• Flexible coverage decision control\n• Clinical compliance assurance\n• Administrative efficiency", 'assistant', [
'How does diagnosis classification work?',
'What are coverage decisions?',
'ICD-10 code management tips',
'Back to main options',
'Complete configuration',
'Continue to section 6'
]);
break;
case 'Start with basic diagnosis setup':
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("🎯 Basic Diagnosis Setup Guide:", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2500));
addMessage("Getting Started Steps:\n\n1️⃣ Click '➕ Add Default Row' to create a sample diagnosis record\n2️⃣ Review the default diagnosis classification and group\n3️⃣ Click on the ICD-10 field to open the code picker\n4️⃣ Set the coverage decision (Yes/No)\n5️⃣ Define any special variations or notes", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Essential Fields Explained:\n\n• Diagnosis Class: High-level category (e.g., 'Adjustment Disorders')\n• Diagnosis Group: Specific clinical grouping\n• ICD-10: Precise diagnostic code\n• Covered: Coverage decision\n• Define Variation: Special handling notes", 'assistant', [
'Help with diagnosis classification',
'ICD-10 code selection guidance',
'Coverage decision tips',
'Back to main options',
'Complete configuration',
'Continue to section 6'
]);
break;
case 'Guide me through adding diagnosis records':
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("🎯 Diagnosis Record Addition Guide:", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2500));
addMessage("Step-by-Step Process:\n\n1️⃣ Choose your approach:\n • '➕ Add Default Row' for template-based entry\n • '📝 Add Empty Row' for custom entry\n • '📂 Bulk Upload' for multiple records\n\n2️⃣ Configure each record:\n • Enter diagnosis class and group\n • Select ICD-10 codes using the picker\n • Set coverage decisions\n • Define variations as needed", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Management Features:\n\n• 📋 Clone existing records for similar diagnoses\n• 🗑️ Remove records that are no longer needed\n• 📥 Export to CSV for external review\n• 🔄 Bulk operations for efficiency", 'assistant', [
'Help with specific record types',
'ICD-10 picker guidance',
'Bulk upload assistance',
'Back to main options',
'Complete configuration',
'Continue to section 6'
]);
break;
case 'Help with ICD-10 code selection':
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("💻 ICD-10 Code Selection Guidance:", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2500));
addMessage("ICD-10 Picker Features:\n\n• Search by keyword or condition name\n• Browse by category and subcategory\n• Multiple code selection support\n• Range selection for code groups\n• Automatic record duplication for multiple codes", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Best Practices:\n\n• Use most specific code available\n• Verify codes are current and valid\n• Consider related codes for comprehensive coverage\n• Review code descriptions for accuracy\n• Group similar diagnoses for efficiency", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Common Code Categories:\n\n• Mental Health: F00-F99 (e.g., F43.0 - Adjustment Disorders)\n• Endocrine: E00-E89 (e.g., E11 - Type 2 Diabetes)\n• Circulatory: I00-I99 (e.g., I10 - Essential Hypertension)\n• Respiratory: J00-J99 (e.g., J45 - Asthma)", 'assistant', [
'Mental health code guidance',
'Chronic condition codes',
'Preventive care codes',
'Back to main options',
'Complete configuration',
'Continue to section 6'
]);
break;
case 'Explain diagnosis classification':
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("🔧 Diagnosis Classification System:", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2500));
addMessage("Classification Hierarchy:\n\n• Diagnosis Class: Broad clinical categories\n Examples: 'Mental Health', 'Chronic Conditions', 'Acute Care'\n\n• Diagnosis Group: Specific condition groupings\n Examples: 'Anxiety Disorders', 'Diabetes Management', 'Emergency Conditions'", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Classification Benefits:\n\n• Standardized organization across plans\n• Simplified coverage decision making\n• Consistent clinical groupings\n• Efficient utilization analysis\n• Clear communication with providers", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Implementation Tips:\n\n• Use consistent naming conventions\n• Align with clinical standards\n• Consider administrative workflows\n• Plan for reporting needs\n• Enable scalable expansion", 'assistant', [
'Help with classification standards',
'Clinical grouping best practices',
'Administrative considerations',
'Back to main options',
'Complete configuration',
'Continue to section 6'
]);
break;
case 'Coverage decision best practices':
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("🔐 Coverage Decision Best Practices:", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2500));
addMessage("Decision Framework:\n\n• Clinical Evidence Base: Use established medical guidelines\n• Cost-Effectiveness: Balance clinical benefit with cost\n• Member Access: Ensure reasonable access to necessary care\n• Regulatory Compliance: Meet all applicable requirements", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2500));
addMessage("Coverage Categories:\n\n• 'Yes' - Fully covered conditions\n• 'No' - Excluded or non-covered conditions\n• Variations can specify:\n - Partial coverage scenarios\n - Prior authorization requirements\n - Specific provider restrictions", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Implementation Guidelines:\n\n• Document decision rationale clearly\n• Ensure consistent application\n• Plan for appeal processes\n• Monitor utilization patterns\n• Review decisions periodically", 'assistant', [
'Help with specific conditions',
'Prior authorization setup',
'Appeal process planning',
'Back to main options',
'Complete configuration',
'Continue to section 6'
]);
break;
case 'Bulk upload assistance':
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("📂 Bulk Upload Assistance:", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2500));
addMessage("Bulk Upload Process:\n\n1️⃣ Prepare your data in tab-separated format\n2️⃣ Use the specified column order:\n • Diagnosis Class\n • Diagnosis Group\n • ICD-10 Code\n • Covered (Yes/No)\n • Define Variation\n\n3️⃣ Paste into the bulk upload modal\n4️⃣ Review and confirm the upload", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Data Preparation Tips:\n\n• Use spreadsheet software for initial preparation\n• Validate ICD-10 codes before upload\n• Ensure consistent formatting\n• Test with small batches first\n• Keep backup copies of your data", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Example Format:\n```\nAdjustment Disorders\tTrauma Related\tF43.0\tYes\tN/A\nAnxiety Disorders\tGeneralized Anxiety\tF41.1\tYes\tPrior auth required\nDepression\tMajor Depression\tF32.9\tYes\tN/A\n```", 'assistant', [
'Help with data formatting',
'ICD-10 validation tips',
'Error troubleshooting',
'Back to main options',
'Complete configuration',
'Continue to section 6'
]);
break;
case 'Review my diagnosis configuration':
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("📊 Diagnosis Configuration Review:", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2500));
addMessage("I can see you have diagnosis supplemental records configured. Let me help you validate key areas:\n\n✅ Diagnosis classification consistency\n✅ ICD-10 code accuracy and currency\n✅ Coverage decision completeness\n✅ Variation specification clarity\n✅ Clinical compliance standards", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Configuration appears complete! Your diagnosis supplemental setup is ready for implementation.", 'assistant', [
'Final validation checklist',
'Implementation guidance',
'Export configuration',
'Complete configuration',
'Continue to section 6'
]);
break;
case 'Back to main options':
await new Promise(resolve => setTimeout(resolve, 1500));
addMessage("How else can I help you with Dx Supplemental Builder configuration?", 'assistant', [
'Guide me through adding diagnosis records',
'Help with ICD-10 code selection',
'Explain diagnosis classification',
'Coverage decision best practices',
'Bulk upload assistance',
'Complete configuration',
'Continue to section 6'
]);
break;
case 'Complete configuration':
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("🎉 Excellent! Your Dx Supplemental configuration is complete!", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Configuration Summary:\n\n✅ Diagnosis records created and classified\n✅ ICD-10 codes properly assigned\n✅ Coverage decisions defined\n✅ Special variations documented\n\nYour comprehensive benefit configuration is now ready for implementation!", 'assistant');
setIsTyping(true);
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("Would you like me to help with any final reviews or next steps?", 'assistant', [
'Export final configuration',
'Review all sections',
'Implementation guidance',
'Start a new configuration',
'Continue to section 6'
]);
break;
case 'Continue to section 6':
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("🎉 Thank you for using the DIY Agent. You can review and send the configuration here. Please let me know if you have any other questions", 'assistant');
// Reset workflow state and navigate to Tab 6
setWorkflowState(prev => ({
...prev,
isInTab1Workflow: false,
isInTab2Workflow: false,
isInTab3Workflow: false,
isInTab4Workflow: false,
isInTab5Workflow: false,
hasShownTabWorkflow: false
}));
// Navigate to Tab 6
setTimeout(() => {
setCurrentStep(6);
console.log('🔧 DEBUG: setCurrentStep(6) called - Moving to final review section');
// End the chat session after a brief delay
setTimeout(() => {
setIsTyping(true);
setTimeout(() => {
addMessage("Configuration complete! The chat session has ended. Click 'Start Session' to begin a new conversation.", 'assistant', ['Start New Session']);
setSessionEnded(true);
setIsTyping(false);
// Automatically close the chat agent after 1 second
setTimeout(() => {
setIsOpen(false);
}, 1000);
}, 1500);
}, 2000);
}, 1000);
break;
default:
// Handle sub-options and other detailed cases
if (option.includes('validation') || option.includes('codes') || option.includes('classification') ||
option.includes('coverage') || option.includes('diagnosis') || option.includes('implementation')) {
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage(`Great choice! For ${option.toLowerCase()}, I recommend reviewing the diagnosis supplemental configuration sections above and validating the specific parameters. Each diagnosis record should have accurate classification, valid ICD-10 codes, and clear coverage decisions.`, 'assistant', [
'Back to main options',
'Need more specific guidance',
'Complete configuration',
'Continue to section 6'
]);
} else {
await new Promise(resolve => setTimeout(resolve, 2000));
addMessage("I'd be happy to help you with that! Feel free to ask me any specific questions about Dx Supplemental Builder configuration, or select from the options below:", 'assistant', [
'Guide me through adding diagnosis records',
'Help with ICD-10 code selection',
'Explain diagnosis classification',
'Coverage decision best practices',
'Bulk upload assistance',
'Complete configuration',
'Continue to section 6'
]);
}
break;
}
};
return (
<>
{/* Chat Widget */}
{isOpen && (
<div className="chat-widget-mobile" style={{
position: 'fixed',
bottom: '100px',
right: '20px',
width: '380px',
height: '500px',
backgroundColor: 'white',
borderRadius: '20px',
boxShadow: '0 10px 40px rgba(0, 0, 0, 0.15)',
border: '1px solid #e5e7eb',
display: 'flex',
flexDirection: 'column',
zIndex: 1000,
animation: 'slideUp 0.3s ease-out',
overflow: 'hidden'
}}>
{/* Header */}
<div className="chat-header-mobile" style={{
background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
color: 'white',
padding: '20px',
borderRadius: '20px 20px 0 0',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center'
}}>
<div>
<h3 style={{ margin: 0, fontSize: '18px', fontWeight: '600' }}>
🤖 DIY Benefits Assistant
</h3>
<p style={{ margin: '4px 0 0 0', fontSize: '12px', opacity: 0.9 }}>
Online • Ready to help
</p>
</div>
<div style={{ display: 'flex', gap: '8px' }}>
{/* End Session / Start Session Button */}
<button
onClick={sessionEnded ? () => {
setMessages([]);
setSessionEnded(false);
setWorkflowState({
isInTab1Workflow: false,
isInTab2Workflow: false,
isInTab3Workflow: false,
isInTab4Workflow: false,
isInTab5Workflow: false,
currentStep: 'initial',
collectedData: {},
awaitingInput: false,
hasShownTabWorkflow: false,
sessionId: Date.now().toString()
});
initializeChat();
} : () => {
setSessionEnded(true);
setIsTyping(true);
setTimeout(() => {
addMessage("Session ended. Click 'Start Session' to begin a new conversation.", 'assistant');
setIsTyping(false);
}, 1500);
}}
style={{
background: 'rgba(255, 255, 255, 0.2)',
border: 'none',
borderRadius: '6px',
color: 'white',
padding: '4px 8px',
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
fontSize: '10px',
fontWeight: '500',
minWidth: '70px',
height: '28px'
}}
title={sessionEnded ? "Start new session" : "End current session"}
>
{sessionEnded ? '▶ Start' : '⏹ End'}
</button>
{sessionEnded && (
<button
onClick={resetChat}
className="chat-reset-btn-mobile"
style={{
background: 'rgba(255, 255, 255, 0.2)',
border: 'none',
borderRadius: '6px',
color: 'white',
width: '28px',
height: '28px',
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
fontSize: '12px'
}}
title="Reset Chat"
>
🔄
</button>
)}
<button
onClick={toggleChat}
className="chat-close-btn-mobile"
style={{
background: 'rgba(255, 255, 255, 0.2)',
border: 'none',
borderRadius: '6px',
color: 'white',
width: '28px',
height: '28px',
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
fontSize: '12px'
}}
>
✕
</button>
</div>
</div>
{/* Messages */}
<div className="chat-messages-mobile" style={{
flex: 1,
padding: '20px',
overflowY: 'auto',
display: 'flex',
flexDirection: 'column',
gap: '16px'
}}>
{messages.map((message) => (
<div key={message.id} className="chat-message-mobile" style={{
display: 'flex',
flexDirection: 'column',
alignItems: message.sender === 'assistant' ? 'flex-start' : 'flex-end'
}}>
<div className="chat-message-text-mobile" style={{
maxWidth: '80%',
padding: '12px 16px',
borderRadius: message.sender === 'assistant' ? '18px 18px 18px 4px' : '18px 18px 4px 18px',
backgroundColor: message.sender === 'assistant' ? '#f3f4f6' : '#667eea',
color: message.sender === 'assistant' ? '#374151' : 'white',
fontSize: '14px',
lineHeight: '1.5',
wordWrap: 'break-word'
}}>
{message.text}
</div>
{/* Options */}
{message.options && (
<div className="chat-options-mobile" style={{
display: 'flex',
gap: '8px',
marginTop: '12px',
flexWrap: 'wrap'
}}>
{message.options.map((option, index) => (
<button
key={index}
onClick={() => handleOptionClick(option)}
className="chat-option-button-mobile"
style={{
padding: '8px 16px',
backgroundColor: '#667eea',
color: 'white',
border: 'none',
borderRadius: '20px',
fontSize: '13px',
fontWeight: '500',
cursor: 'pointer',
transition: 'all 0.2s ease',
boxShadow: '0 2px 8px rgba(102, 126, 234, 0.3)'
}}
onMouseOver={(e) => {
e.currentTarget.style.backgroundColor = '#5b6ad1';
e.currentTarget.style.transform = 'translateY(-1px)';
}}
onMouseOut={(e) => {
e.currentTarget.style.backgroundColor = '#667eea';
e.currentTarget.style.transform = 'translateY(0)';
}}
>
{option}
</button>
))}
</div>
)}
{/* Client Lookup Component */}
{message.showClientLookup && (
<div style={{
marginTop: '12px',
padding: '16px',
backgroundColor: '#f8f9fa',
borderRadius: '12px',
border: '1px solid #e5e7eb'
}}>
<ClientLookupComponent
onClientSelect={handleClientSelection}
placeholder="Search for existing clients..."
/>
</div>
)}
<div style={{
fontSize: '11px',
color: '#9ca3af',
marginTop: '4px',
alignSelf: message.sender === 'assistant' ? 'flex-start' : 'flex-end'
}}>
{message.timestamp.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
</div>
</div>
))}
{/* Typing Indicator */}
{isTyping && (
<div className="chat-typing-indicator-mobile" style={{
display: 'flex',
alignItems: 'flex-start'
}}>
<div style={{
maxWidth: '80%',
padding: '12px 16px',
borderRadius: '18px 18px 18px 4px',
backgroundColor: '#f3f4f6',
color: '#374151',
fontSize: '14px',
lineHeight: '1.5',
display: 'flex',
alignItems: 'center',
gap: '8px'
}}>
<div style={{ display: 'flex', gap: '3px', alignItems: 'center' }}>
<div className="chat-typing-dot-mobile" style={{
width: '8px',
height: '8px',
borderRadius: '50%',
backgroundColor: '#667eea',
animation: 'typing 1.4s infinite ease-in-out',
animationDelay: '0s'
}}></div>
<div className="chat-typing-dot-mobile" style={{
width: '8px',
height: '8px',
borderRadius: '50%',
backgroundColor: '#667eea',
animation: 'typing 1.4s infinite ease-in-out',
animationDelay: '0.2s'
}}></div>
<div className="chat-typing-dot-mobile" style={{
width: '8px',
height: '8px',
borderRadius: '50%',
backgroundColor: '#667eea',
animation: 'typing 1.4s infinite ease-in-out',
animationDelay: '0.4s'
}}></div>
</div>
<span style={{ fontSize: '13px', color: '#6b7280', fontStyle: 'italic' }}>
Assistant is typing...
</span>
</div>
</div>
)}
{/* Text Input for Free Text Responses */}
{workflowState.awaitingInput && (
<div style={{
display: 'flex',
flexDirection: 'column',
gap: '8px'
}}>
<div style={{
padding: '12px 16px',
backgroundColor: '#f0f9ff',
borderRadius: '12px',
border: '1px solid #bae6fd',
fontSize: '13px',
color: '#0369a1'
}}>
💬 Please type your response below:
</div>
<div style={{ display: 'flex', gap: '8px' }}>
<input
type="text"
placeholder={workflowState.inputType === 'clientName' ? 'Enter client name...' : 'Enter parent code...'}
style={{
flex: 1,
padding: '10px 12px',
border: '1px solid #d1d5db',
borderRadius: '8px',
fontSize: '14px',
outline: 'none'
}}
onKeyPress={(e) => {
if (e.key === 'Enter' && e.currentTarget.value.trim()) {
handleTextInput(e.currentTarget.value.trim());
e.currentTarget.value = '';
}
}}
/>
<button
onClick={(e) => {
const input = e.currentTarget.previousElementSibling as HTMLInputElement;
if (input?.value.trim()) {
handleTextInput(input.value.trim());
input.value = '';
}
}}
style={{
padding: '10px 16px',
backgroundColor: '#667eea',
color: 'white',
border: 'none',
borderRadius: '8px',
fontSize: '14px',
fontWeight: '500',
cursor: 'pointer'
}}
>
Send
</button>
</div>
</div>
)}
<div ref={messagesEndRef} />
</div>
</div>
)}
{/* Floating Chat Button */}
<button
onClick={toggleChat}
style={{
position: 'fixed',
bottom: '20px',
right: '20px',
width: '60px',
height: '60px',
borderRadius: '50%',
background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
color: 'white',
border: 'none',
cursor: 'pointer',
boxShadow: '0 8px 25px rgba(102, 126, 234, 0.4)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
fontSize: '24px',
zIndex: 999,
transition: 'all 0.3s ease',
animation: isOpen ? 'none' : 'pulse 2s infinite'
}}
onMouseOver={(e) => {
if (!isOpen) {
e.currentTarget.style.transform = 'scale(1.1)';
e.currentTarget.style.boxShadow = '0 12px 35px rgba(102, 126, 234, 0.6)';
}
}}
onMouseOut={(e) => {
if (!isOpen) {
e.currentTarget.style.transform = 'scale(1)';
e.currentTarget.style.boxShadow = '0 8px 25px rgba(102, 126, 234, 0.4)';
}
}}
>
{isOpen ? '✕' : '💬'}
</button>
{/* CSS Animations */}
<style>
{`
@keyframes slideUp {
from {
opacity: 0;
transform: translateY(20px) scale(0.95);
}
to {
opacity: 1;
transform: translateY(0) scale(1);
}
}
@keyframes pulse {
0% {
box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
}
50% {
box-shadow: 0 8px 25px rgba(102, 126, 234, 0.6);
}
100% {
box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
}
}
@keyframes typing {
0%, 100% {
transform: scale(1);
opacity: 0.3;
}
50% {
transform: scale(1.3);
opacity: 1;
}
}
/* Mobile-specific styles for ChatAssistant */
@media (max-width: 768px) {
.chat-widget-mobile {
position: fixed !important;
bottom: 0 !important;
left: 0 !important;
right: 0 !important;
width: 100vw !important;
height: 70vh !important;
max-height: 500px !important;
border-radius: 20px 20px 0 0 !important;
margin: 0 !important;
z-index: 1000 !important;
}
.chat-header-mobile {
padding: 16px 20px !important;
border-radius: 20px 20px 0 0 !important;
font-size: 16px !important;
}
.chat-messages-mobile {
padding: 12px 16px !important;
height: calc(100% - 120px) !important;
overflow-y: auto !important;
}
.chat-message-mobile {
margin-bottom: 16px !important;
max-width: 85% !important;
}
.chat-message-text-mobile {
padding: 12px 16px !important;
font-size: 15px !important;
line-height: 1.4 !important;
border-radius: 16px !important;
}
.chat-options-mobile {
flex-direction: column !important;
gap: 8px !important;
align-items: stretch !important;
margin-top: 12px !important;
}
.chat-option-button-mobile {
padding: 12px 16px !important;
font-size: 14px !important;
border-radius: 12px !important;
text-align: center !important;
width: 100% !important;
min-height: 44px !important;
box-sizing: border-box !important;
}
.chat-input-container-mobile {
padding: 16px !important;
border-top: 1px solid #e5e7eb !important;
}
.chat-input-mobile {
width: 100% !important;
padding: 12px 16px !important;
font-size: 16px !important;
border-radius: 12px !important;
border: 1px solid #d1d5db !important;
box-sizing: border-box !important;
}
.chat-typing-indicator-mobile {
padding: 8px 16px !important;
}
.chat-typing-dot-mobile {
width: 6px !important;
height: 6px !important;
margin: 0 2px !important;
}
.chat-button-mobile {
width: 50px !important;
height: 50px !important;
bottom: 16px !important;
right: 16px !important;
font-size: 20px !important;
}
.chat-close-btn-mobile {
width: 36px !important;
height: 36px !important;
font-size: 18px !important;
}
.chat-reset-btn-mobile {
width: 36px !important;
height: 36px !important;
font-size: 14px !important;
}
}
@media (max-width: 480px) {
.chat-widget-mobile {
height: 80vh !important;
border-radius: 16px 16px 0 0 !important;
}
.chat-header-mobile {
padding: 12px 16px !important;
font-size: 15px !important;
}
.chat-messages-mobile {
padding: 10px 12px !important;
}
.chat-message-text-mobile {
padding: 10px 14px !important;
font-size: 14px !important;
}
.chat-option-button-mobile {
padding: 10px 14px !important;
font-size: 13px !important;
min-height: 40px !important;
}
.chat-button-mobile {
width: 46px !important;
height: 46px !important;
bottom: 12px !important;
right: 12px !important;
}
}
`}
</style>
</>
);
};
export default ChatAssistant;
import React, { useState, useEffect, useRef } from 'react';
import { useDocument } from '../contexts/DocumentContext';
import ClientLookupComponent from './ClientLookupComponent';
interface Message {
id: string;
text: string;
sender: 'assistant' | 'user';
timestamp: Date;
options?: string[];
showClientLookup?: boolean;
}
interface ChatAssistantProps {
autoStart?: boolean;
}
const ChatAssistant: React.FC<ChatAssistantProps> = ({ autoStart = false }) => {
const [isOpen, setIsOpen] = useState(autoStart);
const [messages, setMessages] = useState<Message[]>([]);
const [isTyping, setIsTyping] = useState(false);
const [sessionEnded, setSessionEnded] = useState(false);
const messagesEndRef = useRef<HTMLDivElement>(null);
// Document context and workflow state
const { documentState, updateClientInformation, setCurrentStep } = useDocument();
const [workflowState, setWorkflowState] = useState<{
isInTab1Workflow: boolean;
isInTab2Workflow: boolean;
isInTab3Workflow: boolean;
isInTab4Workflow: boolean;
isInTab5Workflow: boolean;
currentStep: string;
collectedData: {
clientName?: string;
parentCode?: string;
clientType?: string;
lineOfBusiness?: string;
};
awaitingInput: boolean;
inputType?: string;
hasShownTabWorkflow: boolean; // Track if tab workflow was already shown
sessionId: string; // Track unique session
}>({
isInTab1Workflow: false,
isInTab2Workflow: false,
isInTab3Workflow: false,
isInTab4Workflow: false,
isInTab5Workflow: false,
currentStep: 'initial',
collectedData: {},
awaitingInput: false,
hasShownTabWorkflow: false,
sessionId: Date.now().toString()
});
const scrollToBottom = () => {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
};
useEffect(() => {
scrollToBottom();
}, [messages]);
// Initialize chat when opened
useEffect(() => {
if (isOpen && messages.length === 0 && !sessionEnded) {
initializeChat();
}
}, [isOpen]);
// Auto-start chat if autoStart prop is true
useEffect(() => {
if (autoStart && messages.length === 0 && !sessionEnded) {
// Just set isOpen to true, let the normal initialization handle the rest
// The existing useEffect for isOpen will trigger initializeChat automatically
console.log('🔧 DEBUG: Auto-start triggered, chat will open automatically');
}
}, [autoStart]);
// Auto-trigger workflow when tab changes
useEffect(() => {
if (isOpen && !sessionEnded && messages.length > 0) {
handleTabChange();
}
}, [documentState.currentStep, isOpen]);
const handleTabChange = async () => {
const currentTab = documentState.currentStep;
const lastMessage = messages[messages.length - 1];
// Only trigger if we're not already in a specific workflow and the last message isn't from a tab change
// Also check if we've already shown the tab workflow in this session
if (workflowState.isInTab1Workflow ||
workflowState.isInTab2Workflow ||
workflowState.isInTab3Workflow ||
workflowState.isInTab4Workflow ||
workflowState.isInTab5Workflow ||
workflowState.hasShownTabWorkflow ||
(lastMessage?.text.includes('Welcome to') && Date.now() - lastMessage.timestamp.getTime() < 5000)) {