'use client'; import React, { useState } from 'react'; import { INITIAL_TENANTS, INITIAL_PROVIDERS, INITIAL_PATIENTS, INITIAL_APPOINTMENTS, INITIAL_SOAP_NOTES, INITIAL_SUPERBILLS, INITIAL_PRODUCTS, INITIAL_MEMBERSHIPS, INITIAL_PACKAGES, INITIAL_WAITLIST, } from '@/lib/mock-data'; import { ClinicTenant, Appointment, SoapNote, Superbill, Patient, RetailProduct, WellnessMembership, PrePaidPackage, WaitlistEntry, StaffRole, Provider, } from '@/types/clinical'; import { CalendarView } from '@/components/calendar/CalendarView'; import { SoapChartEditor } from '@/components/charting/SoapChartEditor'; import { SuperbillView } from '@/components/billing/SuperbillView'; import { RetentionView } from '@/components/retention/RetentionView'; import { PatientPortalView } from '@/components/intake/PatientPortalView'; import { SuperAdminView } from '@/components/admin/SuperAdminView'; import { RetailInventoryView } from '@/components/pos/RetailInventoryView'; import { MembershipsView } from '@/components/memberships/MembershipsView'; import { TelehealthRoom } from '@/components/telehealth/TelehealthRoom'; import { WaitlistModal } from '@/components/waitlist/WaitlistModal'; import { CourtAuditVaultModal } from '@/components/compliance/CourtAuditVaultModal'; import { CommandPalette } from '@/components/ui/CommandPalette'; import { InactivityLockoutModal } from '@/components/ui/InactivityLockoutModal'; import { ClinicalToastContainer, ToastMessage } from '@/components/ui/ClinicalToast'; import { DoctorOnboardingView } from '@/components/onboarding/DoctorOnboardingView'; import { ClinicGrowthView } from '@/components/growth/ClinicGrowthView'; import { clinicalAudio } from '@/lib/clinical-audio'; import { Calendar, FileText, DollarSign, Users, Building2, Globe, ChevronDown, Stethoscope, Laptop, ShoppingBag, Repeat, Video, Shield, ShieldAlert, UserCheck, Search, Volume2, VolumeX, Sparkles, Scale, Lock, ShieldCheck, TrendingUp, } from 'lucide-react'; export default function Home() { const [tenants, setTenants] = useState(INITIAL_TENANTS); const [activeTenantId, setActiveTenantId] = useState(INITIAL_TENANTS[0].id); // 'clinic' | 'patient' | 'superadmin' | 'onboarding' const [portalMode, setPortalMode] = useState<'clinic' | 'patient' | 'superadmin' | 'onboarding'>('clinic'); // Staff Role: 'doctor' | 'front_desk' | 'billing_admin' const [staffRole, setStaffRole] = useState('doctor'); // Clinic Sub-Tabs: 'calendar' | 'charting' | 'telehealth' | 'retail' | 'memberships' | 'billing' | 'retention' | 'growth' const [clinicTab, setClinicTab] = useState< 'calendar' | 'charting' | 'telehealth' | 'retail' | 'memberships' | 'billing' | 'retention' | 'growth' >('calendar'); const [appointments, setAppointments] = useState(INITIAL_APPOINTMENTS); const [patients, setPatients] = useState(INITIAL_PATIENTS); const [providers, setProviders] = useState(INITIAL_PROVIDERS); const [soapNotes, setSoapNotes] = useState(INITIAL_SOAP_NOTES); const [superbills, setSuperbills] = useState(INITIAL_SUPERBILLS); const [products, setProducts] = useState(INITIAL_PRODUCTS); const [memberships, setMemberships] = useState(INITIAL_MEMBERSHIPS); const [packages, setPackages] = useState(INITIAL_PACKAGES); const [waitlist, setWaitlist] = useState(INITIAL_WAITLIST); const [isWaitlistOpen, setIsWaitlistOpen] = useState(false); const [pendingIntakes, setPendingIntakes] = useState([ { id: 'intake-waiting-1', patientName: 'Jessica Morales', phone: '(555) 302-9912', dob: '1991-08-14', email: 'jess.morales@example.com', chiefComplaint: 'Cervical Spine (Neck), Left Trapezius / Shoulder pain (Sharp / Stabbing)', vasScore: 6, painAreas: ['Cervical Spine (Neck)', 'Left Trapezius / Shoulder'], submittedAt: 'Just now (Mobile Check-in)', providerName: 'Dr. Marcus Vance', service: 'Initial Chiropractic Exam & Adjustment', }, ]); // Polish state: Command Palette, Toasts & Audio const [isCommandPaletteOpen, setIsCommandPaletteOpen] = useState(false); const [isCourtVaultOpen, setIsCourtVaultOpen] = useState(false); const [isTerminalLocked, setIsTerminalLocked] = useState(false); const [toasts, setToasts] = useState([]); const [audioEnabled, setAudioEnabled] = useState(true); const [isMoreMenuOpen, setIsMoreMenuOpen] = useState(false); const [activePatient, setActivePatient] = useState(INITIAL_PATIENTS[0]); const [activeSoapNote, setActiveSoapNote] = useState(INITIAL_SOAP_NOTES[0]); const [activeSuperbill, setActiveSuperbill] = useState(INITIAL_SUPERBILLS[0]); const activeTenant = tenants.find((t) => t.id === activeTenantId) || tenants[0]; const activeProviders = providers.filter((p) => p.tenantId === activeTenant.id); const activeProvider = activeProviders[0] || providers[0]; // Toast notification helper const addToast = (type: 'success' | 'alert' | 'info', title: string, description?: string) => { const id = `toast-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`; const newToast: ToastMessage = { id, type, title, description, timestamp: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' }), }; setToasts((prev) => [...prev, newToast]); setTimeout(() => { setToasts((prev) => prev.filter((t) => t.id !== id)); }, 4500); }; const handleDismissToast = (id: string) => { setToasts((prev) => prev.filter((t) => t.id !== id)); }; // Keyboard shortcut listener for Cmd+K / Ctrl+K React.useEffect(() => { const handleGlobalKeyDown = (e: KeyboardEvent) => { if ((e.metaKey || e.ctrlKey) && e.key === 'k') { e.preventDefault(); setIsCommandPaletteOpen((prev) => !prev); } }; window.addEventListener('keydown', handleGlobalKeyDown); return () => window.removeEventListener('keydown', handleGlobalKeyDown); }, []); const handleToggleAudio = () => { const next = !audioEnabled; setAudioEnabled(next); clinicalAudio.setEnabled(next); if (next) { clinicalAudio.playSuccess(); addToast('info', 'Tactile Audio Active', 'Synthesized Web Audio clicks & chimes enabled'); } else { addToast('info', 'Tactile Audio Muted', 'Sound effects silenced'); } }; const handleSelectAppointment = (apt: Appointment) => { clinicalAudio.playClick(); const patientMatch = patients.find((p) => p.id === apt.patientId) || patients[0]; setActivePatient(patientMatch); const existingSoap = soapNotes.find((s) => s.patientId === apt.patientId && s.appointmentId === apt.id); setActiveSoapNote(existingSoap); if (apt.isTelehealth) { setClinicTab('telehealth'); } else { setClinicTab('charting'); } }; const handleUpdateAppointmentStatus = (aptId: string, status: Appointment['status']) => { clinicalAudio.playClick(); setAppointments((prev) => prev.map((a) => (a.id === aptId ? { ...a, status } : a)) ); addToast('info', 'Encounter Status Updated', `Appointment transitioned to ${status}`); }; const handleSaveSoapNote = (note: SoapNote) => { clinicalAudio.playSuccess(); setSoapNotes((prev) => { const idx = prev.findIndex((s) => s.id === note.id); if (idx >= 0) { const copy = [...prev]; copy[idx] = note; return copy; } return [...prev, note]; }); setActiveSoapNote(note); addToast('success', 'Chart Synced to HIPAA Vault', `${note.patientName} • ${note.status === 'signed' ? 'Signed & Locked' : 'Draft Saved'}`); }; const handleGenerateSuperbillFromNote = (note: SoapNote) => { clinicalAudio.playSuccess(); const newSb: Superbill = { id: `sb-${Date.now()}`, tenantId: activeTenant.id, invoiceNumber: `SB-2026-${Math.floor(1000 + Math.random() * 9000)}`, patientId: activePatient.id, patientName: `${activePatient.firstName} ${activePatient.lastName}`, patientDob: activePatient.dob, patientAddress: activePatient.address, providerName: note.providerName, providerNpi: activeProvider.npi, clinicName: activeTenant.name, clinicAddress: activeTenant.address, clinicTaxId: activeTenant.taxId, dateOfService: note.date, posCode: '11 (Office)', icd10Codes: note.icd10Codes, items: note.cptCodes.map((cpt) => ({ cptCode: cpt.code, description: cpt.description, units: 1, rate: cpt.fee, total: cpt.fee, })), totalAmount: note.cptCodes.reduce((sum, c) => sum + c.fee, 0), patientPaid: note.cptCodes.reduce((sum, c) => sum + c.fee, 0), balanceDue: 0, paymentMethod: 'Stripe Card', generatedAt: new Date().toISOString(), }; setSuperbills((prev) => [newSb, ...prev]); setActiveSuperbill(newSb); setClinicTab('billing'); addToast('success', 'Superbill Claim Created', `${newSb.invoiceNumber} • $${newSb.totalAmount.toFixed(2)} Fee Schedule`); }; const handleMarkPaid = (superbillId: string, method: Superbill['paymentMethod']) => { clinicalAudio.playSuccess(); setSuperbills((prev) => prev.map((sb) => sb.id === superbillId ? { ...sb, balanceDue: 0, patientPaid: sb.totalAmount, paymentMethod: method } : sb ) ); if (activeSuperbill.id === superbillId) { setActiveSuperbill((prev) => ({ ...prev, balanceDue: 0, patientPaid: prev.totalAmount, paymentMethod: method, })); } addToast('success', 'Stripe Payment Captured', `Receipt processed via ${method}`); }; const handlePatientBookingComplete = (newAptData: any) => { clinicalAudio.playSuccess(); const newApt: Appointment = { id: `apt-${Date.now()}`, tenantId: activeTenant.id, patientId: `pat-${Date.now()}`, ...newAptData, }; setAppointments((prev) => [newApt, ...prev]); const newIntakeItem = { id: `intake-${Date.now()}`, patientName: newAptData.patientName || 'New Patient', phone: newAptData.patientPhone || '(555) 000-0000', chiefComplaint: newAptData.notes || newAptData.serviceType || 'Chief complaint documented during check-in', vasScore: 5, painAreas: ['Spine / Core'], submittedAt: 'Just now (Mobile Check-in)', providerName: newAptData.providerName || activeProvider.name, service: newAptData.serviceType || 'Consultation', }; setPendingIntakes((prev) => [newIntakeItem, ...prev]); addToast('success', 'Intake & Booking Confirmed', `${newApt.patientName} scheduled for ${newApt.time}`); }; const handleStartEncounterFromIntake = (intake: any) => { clinicalAudio.playSuccess(); const nameParts = (intake.patientName || 'Jessica Morales').trim().split(' '); const firstName = nameParts[0] || 'Jessica'; const lastName = nameParts.slice(1).join(' ') || 'Morales'; const newPatient: Patient = { id: `pat-intake-${Date.now()}`, tenantId: activeTenant.id, firstName, lastName, email: intake.email || `${firstName.toLowerCase()}.${lastName.toLowerCase()}@example.com`, phone: intake.phone || '(555) 302-9912', dob: intake.dob || '1991-08-14', gender: 'Female', address: '284 Monterey Hwy, San Jose, CA 95112', insuranceName: 'Blue Shield PPO', insuranceId: 'BSP-99214', status: 'active', chiefComplaint: intake.chiefComplaint, daysSinceLastVisit: 0, lastVisitDate: new Date().toISOString().substring(0, 10), vitals: { bloodPressure: '118/76', heartRate: 74, temperature: '98.6°F', oxygenSat: 99, painLevel: intake.vasScore || 6, bmi: '22.8', allergies: ['None reported'], contraindications: ['None reported'], }, carePlan: { title: 'Cervical Stabilization & Postural Restoration', totalVisits: 12, completedVisits: 0, frequency: '3x / week for 4 weeks', targetCondition: 'Cervicalgia & Upper Crossed Syndrome', startDate: new Date().toISOString().substring(0, 10), status: 'on_track', }, }; setPatients((prev) => [newPatient, ...prev]); setActivePatient(newPatient); const newNote: SoapNote = { id: `soap-intake-${Date.now()}`, tenantId: activeTenant.id, patientId: newPatient.id, patientName: `${firstName} ${lastName}`, providerId: activeProvider.id, providerName: activeProvider.name, date: new Date().toISOString().substring(0, 10), status: 'draft', discipline: 'chiropractic', vasScore: intake.vasScore || 6, subjective: `Patient completed digital intake in waiting room. Reports: "${intake.chiefComplaint}". Patient notes sudden sharp exacerbation rated ${intake.vasScore || 6}/10 pain after prolonged desk work. Desires manual alignment and therapeutic decompression.`, objective: 'Cervical inspection demonstrates antalgic head tilt and guarded rotation. Motion palpation identifies acute subluxations at C1 (Right Lateral Mass) and C5 (Posterior Right). Paraspinal tenderness and hypertonicity in upper trapezius.', assessment: 'Acute cervical segmental dysfunction (M99.01) with cervicogenic spasm. Patient suitable for manual chiropractic manipulation.', plan: '1. Diversified adjustment delivered to C1 (Atlas) and C5.\n2. Suboccipital myofascial release (15 min).\n3. Ergonomic posture home stretches prescribed.\n4. Follow-up visit in 48 hours.', spinalAdjustments: [ { vertebra: 'C1 (Atlas)', region: 'Cervical', listing: 'Right Lateral Mass Anterior', technique: 'Diversified', notes: 'Audible cavitation' }, { vertebra: 'C5', region: 'Cervical', listing: 'Posterior Right', technique: 'Diversified', notes: 'Immediate reduction in hypertonicity' }, ], icd10Codes: [ { code: 'M99.01', description: 'Segmental and somatic dysfunction of cervical region' }, { code: 'M54.2', description: 'Cervicalgia / Neck Pain' }, ], cptCodes: [ { code: '98940', description: 'CMT Spinal, 1-2 Regions (Cervical)', fee: 55 }, { code: '97140', description: 'Manual Therapy Techniques (15 min)', fee: 45 }, ], }; setActiveSoapNote(newNote); setPendingIntakes((prev) => prev.filter((i) => i.id !== intake.id)); setClinicTab('charting'); addToast('success', 'Mobile Intake Imported to SOAP', `${intake.patientName}'s pain map and history loaded.`); }; const handleAddTenant = (newTenant: ClinicTenant) => { setTenants((prev) => [...prev, newTenant]); addToast('success', 'New Clinic Deployed', `${newTenant.name} onboarded to Mediusa OS`); }; const handleCompleteOnboarding = (newTenant: ClinicTenant, leadDoctor: Provider) => { setTenants((prev) => [...prev, newTenant]); setProviders((prev) => [...prev, leadDoctor]); setActiveTenantId(newTenant.id); // Seed 1 active patient and encounter for instant clinic operation const samplePatientId = `pat-${Date.now()}`; const samplePatient: Patient = { id: samplePatientId, tenantId: newTenant.id, firstName: 'Michael', lastName: 'Sterling', email: 'm.sterling@example.com', phone: '(555) 349-1102', dob: '1984-06-12', gender: 'Male', address: '742 Evergreen Terrace, McLean, VA 22102', insuranceName: 'CareFirst BlueCross', insuranceId: 'CFB-94021-X', status: 'active', chiefComplaint: 'Acute thoracic and lumbar stiffness following marathon training; radiates to right hamstring', daysSinceLastVisit: 0, lastVisitDate: new Date().toISOString().substring(0, 10), nextAppointmentDate: new Date().toISOString().substring(0, 10), vitals: { bloodPressure: '122/78', heartRate: 68, temperature: '98.4°F', oxygenSat: 99, painLevel: 6, bmi: '23.4', allergies: ['Penicillin', 'Latex'], contraindications: ['High-velocity cervical rotation'], }, carePlan: { title: 'Spinal Alignment & Thoracic Mobility Protocol', totalVisits: 12, completedVisits: 1, frequency: '2x / week for 6 weeks', targetCondition: 'Thoracolumbar Subluxation Complex', startDate: new Date().toISOString().substring(0, 10), status: 'on_track', }, }; const sampleApt: Appointment = { id: `apt-${Date.now()}`, tenantId: newTenant.id, patientId: samplePatientId, patientName: `${samplePatient.firstName} ${samplePatient.lastName}`, patientPhone: samplePatient.phone, providerId: leadDoctor.id, providerName: leadDoctor.name, date: new Date().toISOString().substring(0, 10), time: '10:00 AM', durationMinutes: 45, serviceType: 'Initial Clinical Examination & Spinal Adjustment', status: 'confirmed', room: 'Operatory 1', notes: 'Initial evaluation under newly executed HIPAA BAA enclave. Full spinal visualizer and CMS-1500 queued.', fee: 85, }; setPatients((prev) => [samplePatient, ...prev]); setAppointments((prev) => [sampleApt, ...prev]); setActivePatient(samplePatient); setPortalMode('clinic'); setClinicTab('calendar'); addToast( 'success', 'Clinic Enclave Deployed & BAA Sealed', `${newTenant.name} is online on https://${newTenant.domain}. Lead Doctor: ${leadDoctor.name}.` ); }; const handleSwitchTenant = (tenantId: string) => { clinicalAudio.playClick(); setActiveTenantId(tenantId); setPortalMode('clinic'); setClinicTab('calendar'); // Automatically sync active patient, note, and superbills for the selected clinic const tenantPatients = patients.filter((p) => p.tenantId === tenantId); if (tenantPatients.length > 0) { setActivePatient(tenantPatients[0]); const matchingSoap = soapNotes.find((s) => s.patientId === tenantPatients[0].id) || soapNotes.find((s) => s.tenantId === tenantId); setActiveSoapNote(matchingSoap); } const tenantSuperbills = superbills.filter((sb) => sb.tenantId === tenantId); if (tenantSuperbills.length > 0) { setActiveSuperbill(tenantSuperbills[0]); } }; const handleQuickScheduleAppointment = (newAptData: any) => { clinicalAudio.playSuccess(); const newApt: Appointment = { id: `apt-${Date.now()}`, ...newAptData, }; const existingPatient = patients.find((p) => p.id === newAptData.patientId); if (!existingPatient) { const nameParts = (newAptData.patientName || 'New Patient').split(' '); const firstName = nameParts[0] || 'Walk-In'; const lastName = nameParts.slice(1).join(' ') || 'Patient'; const newPatient: Patient = { id: newAptData.patientId, tenantId: activeTenant.id, firstName, lastName, email: `${firstName.toLowerCase()}.${lastName.toLowerCase()}@example.com`, phone: newAptData.patientPhone || '(555) 000-0000', dob: '1990-01-01', gender: 'Undisclosed', address: activeTenant.cityStateZip, insuranceName: 'Direct / Stripe Connect', insuranceId: 'SELF-PAY', chiefComplaint: newAptData.notes || newAptData.serviceType, daysSinceLastVisit: 0, lastVisitDate: newAptData.date, nextAppointmentDate: newAptData.date, status: 'active', carePlan: { title: 'Acute Relief & Biomechanical Alignment', totalVisits: 6, completedVisits: 1, frequency: '1-2x / week', targetCondition: newAptData.serviceType, startDate: newAptData.date, status: 'on_track', }, }; setPatients((prev) => [newPatient, ...prev]); setActivePatient(newPatient); } else { setActivePatient(existingPatient); } setAppointments((prev) => [newApt, ...prev]); addToast( 'success', 'Encounter Scheduled', `${newApt.patientName} scheduled for ${newApt.time} (${newApt.serviceType})` ); }; const handleEndTelehealthCall = (consultData: { subjective: string; objective: string; assessment: string; plan: string; duration: string; }) => { clinicalAudio.playSuccess(); const today = new Date().toISOString().substring(0, 10); const updatedNote: SoapNote = { id: activeSoapNote?.id || `soap-${Date.now()}`, tenantId: activeTenant.id, patientId: activePatient.id, patientName: `${activePatient.firstName} ${activePatient.lastName}`, providerId: activeProvider.id, providerName: activeProvider.name, date: today, status: 'draft', discipline: 'chiropractic', vasScore: 4, subjective: consultData.subjective, objective: consultData.objective, assessment: consultData.assessment, plan: `${consultData.plan}\n\n[Telehealth Video Consult • Duration: ${consultData.duration} • Encrypted WebRTC Session]`, spinalAdjustments: activeSoapNote?.spinalAdjustments || [], icd10Codes: activeSoapNote?.icd10Codes || [ { code: 'M99.01', description: 'Segmental and somatic dysfunction of cervical region' }, ], cptCodes: [ { code: '99203', description: 'Office/Telehealth Outpatient Visit, 30 min', fee: 110 }, { code: '97110', description: 'Therapeutic Exercises & Ergonomic Protocol', fee: 45 }, ], }; setSoapNotes((prev) => { const idx = prev.findIndex((s) => s.patientId === activePatient.id); if (idx >= 0) { const copy = [...prev]; copy[idx] = updatedNote; return copy; } return [updatedNote, ...prev]; }); setActiveSoapNote(updatedNote); setClinicTab('charting'); addToast( 'success', 'Telehealth Note Synced to Chart', `Clinical findings for ${activePatient.firstName} ${activePatient.lastName} transferred to SOAP editor (${consultData.duration})` ); }; const handleUpdateProductStock = (productId: string, newStock: number) => { clinicalAudio.playClick(); setProducts((prev) => prev.map((p) => (p.id === productId ? { ...p, stockQty: newStock } : p)) ); addToast('info', 'POS Inventory Updated', `Stock quantity adjusted to ${newStock}`); }; const handleEnrollPatientInMembership = (patientId: string, planName: string) => { clinicalAudio.playSuccess(); setPatients((prev) => prev.map((p) => (p.id === patientId ? { ...p, activeMembership: planName } : p)) ); addToast('success', 'Membership Enrolled', `Patient subscribed to ${planName}`); }; const handleAutoFillWaitlistPatient = (entryId: string) => { clinicalAudio.playPing(); const entry = waitlist.find((w) => w.id === entryId); setWaitlist((prev) => prev.map((w) => (w.id === entryId ? { ...w, status: 'notified' } : w)) ); addToast('alert', 'Waitlist SMS Dispatched', `Slot opening sent to ${entry?.patientName || 'patient'}`); }; return (
{/* Top Hospital Command Header */}
{/* Tier 1: System Command & Tenant Navigation */}
{/* Left Cluster: Hospital Brand & Clinic Identity */}
+M
MEDIUSA CLINIC OS v2.5
https://{activeTenant.domain}
{/* Clinic Dropdown Selector */}
{/* Center: Command Palette / Search Bar (Responsive) */}
{/* Right Cluster: Quick Tools + Role Switcher + Portal Switcher */}
{/* Search button on small screens where full bar is hidden */} {/* Utility & Security Actions Cluster */}
{/* Audio Toggle */} {/* Court Vault Button */} {/* Terminal Lock Button */}
{/* Staff Role Switcher (RBAC) */}
{/* Portal Mode Switcher */}
{/* More Views Dropdown */}
{isMoreMenuOpen && ( <>
setIsMoreMenuOpen(false)} />
Administrative Views
)}
{/* Pre-Launch / Pending BAA Banner */} {portalMode === 'clinic' && activeTenant.baaStatus === 'pending' && (
{activeTenant.name}: Scheduling, calendars, and digital intake are active for testing. Ready for doctor BAA sign-off on go-live!
)} {/* Tier 2: Sub-Tabs for Doctor Clinic OS (Cleanly Grouped, No Horizontal Overflow) */} {portalMode === 'clinic' && (
{/* Grouped Clinical Workspace Navigation */}
{/* Group 1: Clinical Operations */}
{staffRole !== 'front_desk' ? ( ) : ( Notes Locked )} {staffRole !== 'front_desk' && ( )}
{/* Group 2: Practice & Revenue */}
{/* Group 3: Patient Retention & Growth */}
{/* Right: Active Clinician Presence Indicator */}
Active: {activeProvider.name}
)}
{/* Main Container */}
{/* Clinic Executive Collections & Billing Pulse Bar */} {portalMode === 'clinic' && (
Today's Collections $2,380.00
+14.2% vs avg
Clean Claim Pass Rate 99.8%
0 NCCI Denials
Average Days in A/R 11.4 Days
3x Industry Speed
Frontier AI Engine GPT-5.4 • Claude 3.7
Active Scribe
)} {portalMode === 'clinic' && (() => { const tenantPatients = patients.filter((p) => !p.tenantId || p.tenantId === activeTenant.id); const tenantSuperbills = superbills.filter((s) => !s.tenantId || s.tenantId === activeTenant.id); return (
{clinicTab === 'calendar' && ( setPortalMode('patient')} onQuickSchedule={handleQuickScheduleAppointment} onOpenWaitlist={() => setIsWaitlistOpen(true)} onStartEncounterFromIntake={handleStartEncounterFromIntake} /> )} {clinicTab === 'charting' && staffRole !== 'front_desk' && ( setClinicTab('telehealth')} onBackToCalendar={() => setClinicTab('calendar')} onOpenCourtVault={() => setIsCourtVaultOpen(true)} /> )} {clinicTab === 'telehealth' && staffRole !== 'front_desk' && ( setClinicTab('calendar')} /> )} {clinicTab === 'retail' && ( )} {clinicTab === 'memberships' && ( )} {clinicTab === 'billing' && ( setClinicTab('calendar')} onSelectSuperbill={(sb) => setActiveSuperbill(sb)} onMarkPaid={handleMarkPaid} /> )} {clinicTab === 'retention' && ( { setActivePatient(patient); const existing = soapNotes.find((s) => s.patientId === patient.id); setActiveSoapNote(existing); setClinicTab('charting'); }} /> )} {clinicTab === 'growth' && ( setPortalMode('patient')} /> )}
); })()} {portalMode === 'patient' && ( )} {portalMode === 'superadmin' && ( )} {portalMode === 'onboarding' && ( setPortalMode('clinic')} /> )}
{/* Cancellation Waitlist Modal */} setIsWaitlistOpen(false)} onAutoFillPatient={handleAutoFillWaitlistPatient} /> {/* Court-Ready Legal & HIPAA Compliance Vault Modal */} setIsCourtVaultOpen(false)} activePatient={activePatient} activeSoapNote={activeSoapNote} activeTenant={activeTenant} /> {/* HIPAA Inactivity & Break-Glass Lockout Modal (45 CFR § 164.312(a)(2)(iii) & § 164.312(a)(2)(ii)) */} setIsTerminalLocked(false)} onManualLock={() => setIsTerminalLocked(true)} doctorName={activeProvider.name} clinicName={activeTenant.name} inactivityTimeoutMinutes={15} /> {/* Global Command Palette (Cmd+K) */} setIsCommandPaletteOpen(false)} patients={patients} onSelectPatient={(p) => { setActivePatient(p); const existing = soapNotes.find((s) => s.patientId === p.id); setActiveSoapNote(existing); }} onNavigateTab={(tab) => setClinicTab(tab)} onOpenWaitlist={() => setIsWaitlistOpen(true)} onSetStaffRole={(role) => { setStaffRole(role); if (role === 'front_desk' && (clinicTab === 'charting' || clinicTab === 'telehealth')) { setClinicTab('calendar'); } }} onToggleAudio={handleToggleAudio} audioEnabled={audioEnabled} onOpenCourtVault={() => setIsCourtVaultOpen(true)} onLockTerminal={() => setIsTerminalLocked(true)} onOpenOnboarding={() => setPortalMode('onboarding')} /> {/* Hospital Clinical Toast Notification System */} {/* Hospital Footer */}
); }