const { useState, useRef, useEffect } = React; // ============================================ // ICONS (Inline SVG for accessibility) // ============================================ const Icons = { Shield: () => ( ), Package: () => ( ), Home: () => ( ), Plus: () => ( ), X: () => ( ), Check: () => ( ), AlertCircle: () => ( ), Camera: () => ( ), User: () => ( ), Settings: () => ( ), Loader: () => ( ) }; // ============================================ // USER CONTEXT HOOK - Persistent Storage // ============================================ function useUserContext() { const [userContext, setUserContext] = useState(() => { const saved = localStorage.getItem('gmtracker_user_context'); if (saved) { try { return JSON.parse(saved); } catch { return null; } } return null; }); const saveUserContext = (context) => { setUserContext(context); localStorage.setItem('gmtracker_user_context', JSON.stringify(context)); }; const clearUserContext = () => { setUserContext(null); localStorage.removeItem('gmtracker_user_context'); }; return { userContext, saveUserContext, clearUserContext }; } // ============================================ // USER PROFILE SETUP COMPONENT // ============================================ function UserProfileSetup({ userContext, onSave, onClose }) { const [formData, setFormData] = useState(userContext || { age: '', location: '', dietary_restrictions: [], allergies: [], health_conditions: [], language_preference: 'english' }); const [customAllergy, setCustomAllergy] = useState(''); const [customCondition, setCustomCondition] = useState(''); const [customDiet, setCustomDiet] = useState(''); const commonAllergies = ['Peanuts', 'Tree nuts', 'Milk', 'Eggs', 'Wheat', 'Soy', 'Fish', 'Shellfish', 'Sesame']; const commonConditions = ['Diabetes', 'High blood pressure', 'Heart disease', 'Kidney disease', 'Liver disease', 'Pregnant', 'Breastfeeding', 'Asthma']; const commonDiets = ['Vegetarian', 'Vegan', 'Gluten-free', 'Low sodium', 'Low sugar', 'Halal', 'Kosher']; const toggleArrayItem = (array, item) => { if (array.includes(item)) { return array.filter(i => i !== item); } return [...array, item]; }; const handleAddCustom = (type, value, setter) => { if (value.trim()) { setFormData({ ...formData, [type]: [...formData[type], value.trim()] }); setter(''); } }; const handleSubmit = (e) => { e.preventDefault(); const cleanedData = { ...formData, age: formData.age ? parseInt(formData.age) : null }; onSave(cleanedData); }; return (

Your Profile

Help us personalize product recommendations for you

{/* Age and Location */}
setFormData({...formData, age: e.target.value})} className="w-full p-3 text-lg border-2 border-gray-300 rounded-lg focus:border-blue-500" placeholder="e.g., 65" />
setFormData({...formData, location: e.target.value})} className="w-full p-3 text-lg border-2 border-gray-300 rounded-lg focus:border-blue-500" placeholder="e.g., India, USA" />
{/* Health Conditions */}
Health Conditions
{commonConditions.map(condition => ( ))}
setCustomCondition(e.target.value)} className="flex-1 p-2 border-2 border-gray-300 rounded-lg" placeholder="Add other condition..." />
{formData.health_conditions.filter(c => !commonConditions.map(cc => cc.toLowerCase()).includes(c)).length > 0 && (
{formData.health_conditions.filter(c => !commonConditions.map(cc => cc.toLowerCase()).includes(c)).map(c => ( {c} ))}
)}
{/* Allergies */}
Allergies
{commonAllergies.map(allergy => ( ))}
setCustomAllergy(e.target.value)} className="flex-1 p-2 border-2 border-gray-300 rounded-lg" placeholder="Add other allergy..." />
{formData.allergies.filter(a => !commonAllergies.map(ca => ca.toLowerCase()).includes(a)).length > 0 && (
{formData.allergies.filter(a => !commonAllergies.map(ca => ca.toLowerCase()).includes(a)).map(a => ( {a} ))}
)}
{/* Dietary Restrictions */}
Dietary Preferences
{commonDiets.map(diet => ( ))}
setCustomDiet(e.target.value)} className="flex-1 p-2 border-2 border-gray-300 rounded-lg" placeholder="Add other dietary preference..." />
{/* Summary */} {(formData.health_conditions.length > 0 || formData.allergies.length > 0 || formData.dietary_restrictions.length > 0) && (

Your Profile Summary:

{formData.age &&

Age: {formData.age}

} {formData.location &&

Location: {formData.location}

} {formData.health_conditions.length > 0 && (

Health Conditions: {formData.health_conditions.join(', ')}

)} {formData.allergies.length > 0 && (

Allergies: {formData.allergies.join(', ')}

)} {formData.dietary_restrictions.length > 0 && (

Dietary: {formData.dietary_restrictions.join(', ')}

)}
)} {/* Buttons */}
); } // ============================================ // FEATURE 1: SAFETY COACH COMPONENT // ============================================ function SafetyCoach() { const [isOpen, setIsOpen] = useState(false); const [step, setStep] = useState(1); const [symptom, setSymptom] = useState(''); const [context, setContext] = useState({ alcohol_recent: false, caffeine_recent: false, meal_within_1h: false }); const [result, setResult] = useState(null); const [loading, setLoading] = useState(false); const [liveRegion, setLiveRegion] = useState(''); const dialogRef = useRef(null); const openButtonRef = useRef(null); useEffect(() => { if (isOpen && dialogRef.current) { dialogRef.current.focus(); } }, [isOpen]); const handleOpen = () => { setIsOpen(true); setStep(1); setSymptom(''); setContext({ alcohol_recent: false, caffeine_recent: false, meal_within_1h: false }); setResult(null); setLiveRegion('Safety check dialog opened'); }; const handleClose = () => { setIsOpen(false); setResult(null); setLiveRegion('Safety check dialog closed'); if (openButtonRef.current) { openButtonRef.current.focus(); } }; const handleCheckSafety = async () => { setLoading(true); setLiveRegion('Checking medication safety...'); try { const response = await fetch('/api/safety/check', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ symptom, context }) }); const data = await response.json(); setResult(data); setStep(2); setLiveRegion(`Safety result: ${data.status}. ${data.message}`); } catch (error) { setLiveRegion('Error checking safety. Please try again.'); console.error('Safety check error:', error); } finally { setLoading(false); } }; const handleLogDose = async () => { if (!result) return; setLiveRegion('Logging dose...'); try { const doseMatch = result.message.match(/(\d+)\s*mg/); const doseMg = doseMatch ? parseInt(doseMatch[1]) : 500; const medMatch = result.message.match(/of\s+(\w+)/); const medName = medMatch ? medMatch[1] : 'medication'; await fetch('/api/doses', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ item_name: medName, amount_mg: doseMg, source: 'safety_check' }) }); setLiveRegion(`Logged ${doseMg} milligrams of ${medName}`); setTimeout(handleClose, 1500); } catch (error) { setLiveRegion('Error logging dose'); console.error('Log dose error:', error); } }; if (!isOpen) { return (

Medication Safety Coach

Get personalized guidance on what medications are safe to take right now based on your recent doses and health factors.

); } return (

{step === 1 ? 'Safety Check' : 'Safety Result'}

{step === 1 && (
{['headache', 'cold', 'stomach pain', 'sleep', 'other'].map(option => ( ))}
Additional Context (Optional)
)} {step === 2 && result && (

Status: {result.status}

{result.message}

{result.recommendations && result.recommendations.length > 0 && (

Recommendations:

    {result.recommendations.filter(r => r).map((rec, idx) => (
  • {rec}
  • ))}
)}
{result.status === 'safe' && ( )}
)}
{liveRegion}
); } // ============================================ // FEATURE 2: MY ITEMS (MEDICATION PROFILES) // ============================================ function MyItems() { const [items, setItems] = useState([]); const [showAddForm, setShowAddForm] = useState(false); const [loading, setLoading] = useState(false); const [liveRegion, setLiveRegion] = useState(''); const [formData, setFormData] = useState({ display_name: '', strength: '', form: '', indication_plain: '', instructions_plain: '', warnings_plain: '' }); const formRef = useRef(null); const addButtonRef = useRef(null); useEffect(() => { loadItems(); }, []); useEffect(() => { if (showAddForm && formRef.current) { formRef.current.focus(); } }, [showAddForm]); const loadItems = async () => { try { const response = await fetch('/api/items'); const data = await response.json(); setItems(data); setLiveRegion(`Loaded ${data.length} medication items`); } catch (error) { console.error('Error loading items:', error); setLiveRegion('Error loading items'); } }; const handleSubmit = async (e) => { e.preventDefault(); setLoading(true); setLiveRegion('Saving medication item...'); try { const response = await fetch('/api/items', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(formData) }); if (response.ok) { const newItem = await response.json(); setLiveRegion(`Saved new item: ${newItem.display_name}`); setFormData({ display_name: '', strength: '', form: '', indication_plain: '', instructions_plain: '', warnings_plain: '' }); setShowAddForm(false); loadItems(); if (addButtonRef.current) { addButtonRef.current.focus(); } } } catch (error) { console.error('Error saving item:', error); setLiveRegion('Error saving item'); } finally { setLoading(false); } }; return (

My Medications & Products

{showAddForm && (

Add New Medication or Product

setFormData({...formData, display_name: e.target.value})} className="w-full p-3 text-lg border-2 border-gray-300 rounded-lg focus:border-blue-500" placeholder="e.g., Metformin, Aspirin, Vitamin D" aria-required="true" />
setFormData({...formData, strength: e.target.value})} className="w-full p-3 text-lg border-2 border-gray-300 rounded-lg focus:border-blue-500" placeholder="e.g., 500 mg, 10 mg" />
setFormData({...formData, indication_plain: e.target.value})} className="w-full p-3 text-lg border-2 border-gray-300 rounded-lg focus:border-blue-500" placeholder="e.g., For diabetes, For headaches" />