import React, { useState, useEffect } from 'react';

// ESSENTIAL CARE - Complete Home Health Management System
// Production-Ready for iOS/Android Smartphones
// California Labor Law Compliant

const EssentialCareApp = () => {
  // Core State
  const [view, setView] = useState('login');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [user, setUser] = useState(null);
  const [time, setTime] = useState(new Date());
  const [loading, setLoading] = useState(false);
  const [activeTab, setActiveTab] = useState('clock');
  const [adminTab, setAdminTab] = useState('overview');

  // Clock State
  const [clockedIn, setClockedIn] = useState(false);
  const [clockInTime, setClockInTime] = useState(null);
  const [clockInLocation, setClockInLocation] = useState(null);
  const [selectedClient, setSelectedClient] = useState('');
  const [notes, setNotes] = useState('');
  const [procedures, setProcedures] = useState([]);
  const [entries, setEntries] = useState([]);

  // Break State (CA Labor Law)
  const [onBreak, setOnBreak] = useState(false);
  const [breakStart, setBreakStart] = useState(null);
  const [breaks, setBreaks] = useState([]);

  // Mileage State
  const [mileageEntries, setMileageEntries] = useState([]);
  const [tracking, setTracking] = useState(false);
  const [tripStart, setTripStart] = useState(null);
  const [tripStartLoc, setTripStartLoc] = useState(null);
  const [tripPurpose, setTripPurpose] = useState('');

  // Schedule/Shift State
  const [shifts, setShifts] = useState([
    { id: 1, date: '2025-01-02', time: '8:00 AM - 12:00 PM', client: 'Margaret Johnson', clientId: 1, caregiver: 'Sarah Williams', caregiverId: 1, available: false, requestedBy: null },
    { id: 2, date: '2025-01-02', time: '1:00 PM - 5:00 PM', client: 'Robert Chen', clientId: 2, caregiver: 'Michael Thompson', caregiverId: 2, available: true, requestedBy: null },
    { id: 3, date: '2025-01-03', time: '9:00 AM - 1:00 PM', client: 'Elena Rodriguez', clientId: 3, caregiver: 'Jennifer Davis', caregiverId: 3, available: false, requestedBy: null },
    { id: 4, date: '2025-01-03', time: '2:00 PM - 6:00 PM', client: 'Margaret Johnson', clientId: 1, caregiver: 'Sarah Williams', caregiverId: 1, available: true, requestedBy: null },
    { id: 5, date: '2025-01-04', time: '8:00 AM - 4:00 PM', client: 'Robert Chen', clientId: 2, caregiver: 'Michael Thompson', caregiverId: 2, available: false, requestedBy: null },
    { id: 6, date: '2025-01-04', time: '10:00 AM - 2:00 PM', client: 'Elena Rodriguez', clientId: 3, caregiver: 'Jennifer Davis', caregiverId: 3, available: true, requestedBy: null },
    { id: 7, date: '2025-01-05', time: '9:00 AM - 5:00 PM', client: 'William Park', clientId: 4, caregiver: 'Sarah Williams', caregiverId: 1, available: false, requestedBy: null },
  ]);
  const [tradeRequests, setTradeRequests] = useState([]);
  const [scheduleTab, setScheduleTab] = useState('myShifts');

  // Messages/Communication State
  const [messages, setMessages] = useState([
    { id: 1, from: 'Admin', fromId: 4, to: 'all', subject: 'Holiday Schedule', body: 'Please submit your holiday availability by Friday.', date: '2024-12-28T10:00:00', read: false, type: 'announcement' },
    { id: 2, from: 'Michael Thompson', fromId: 2, to: 1, subject: 'Shift Question', body: 'Can you cover my Thursday shift?', date: '2024-12-27T14:30:00', read: true, type: 'message' },
  ]);
  const [messageTab, setMessageTab] = useState('inbox');
  const [composeOpen, setComposeOpen] = useState(false);
  const [newMessage, setNewMessage] = useState({ to: '', subject: '', body: '' });

  // Incident Report State
  const [incidents, setIncidents] = useState([]);
  const [incidentOpen, setIncidentOpen] = useState(false);
  const [newIncident, setNewIncident] = useState({ client: '', type: '', description: '', severity: 'low' });

  // Supplies/Inventory State
  const [supplyRequests, setSupplyRequests] = useState([
    { id: 1, item: 'Disposable Gloves (Box)', quantity: 2, status: 'pending', requestedBy: 'Sarah Williams', date: '2024-12-27' },
    { id: 2, item: 'Hand Sanitizer', quantity: 3, status: 'approved', requestedBy: 'Jennifer Davis', date: '2024-12-26' },
  ]);
  const [newSupply, setNewSupply] = useState({ item: '', quantity: 1 });

  // Training/Certifications State
  const [trainings, setTrainings] = useState([
    { id: 1, name: 'CPR Certification', dueDate: '2025-03-15', status: 'current', completedDate: '2024-03-15' },
    { id: 2, name: 'HIPAA Compliance', dueDate: '2025-01-30', status: 'due_soon', completedDate: '2024-01-30' },
    { id: 3, name: 'Fall Prevention', dueDate: '2025-06-01', status: 'current', completedDate: '2024-06-01' },
    { id: 4, name: 'Infection Control', dueDate: '2024-12-15', status: 'overdue', completedDate: '2023-12-15' },
  ]);

  // Emergency Contacts
  const [emergencyVisible, setEmergencyVisible] = useState(false);

  // Data
  const users = [
    { id: 1, name: 'Sarah Williams', email: 'sarah@essentialcare.com', password: 'demo123', role: 'caregiver', rate: 22.50, phone: '(408) 555-0101' },
    { id: 2, name: 'Michael Thompson', email: 'michael@essentialcare.com', password: 'demo123', role: 'caregiver', rate: 24.00, phone: '(408) 555-0102' },
    { id: 3, name: 'Jennifer Davis', email: 'jennifer@essentialcare.com', password: 'demo123', role: 'caregiver', rate: 21.00, phone: '(408) 555-0103' },
    { id: 4, name: 'Admin User', email: 'admin@essentialcare.com', password: 'admin123', role: 'admin', phone: '(408) 555-0100' },
    { id: 5, name: 'Margaret Johnson', email: 'margaret.j@email.com', password: 'client123', role: 'client', clientId: 1 },
  ];

  const caregivers = users.filter(u => u.role === 'caregiver');

  const clients = [
    { id: 1, name: 'Margaret Johnson', address: '123 Oak Lane, San Jose, CA 95123', phone: '(408) 555-1001', emergency: 'John Johnson (Son) - (408) 555-1002', procedures: ['Medication reminder', 'Mobility assistance', 'Meal preparation', 'Light housekeeping'], notes: 'Allergic to penicillin. Prefers morning visits.', vitals: true },
    { id: 2, name: 'Robert Chen', address: '456 Maple Dr, Los Gatos, CA 95030', phone: '(408) 555-2001', emergency: 'Lisa Chen (Daughter) - (408) 555-2002', procedures: ['Wound care', 'Physical therapy exercises', 'Vital signs monitoring', 'Bathing assistance'], notes: 'Diabetic - check blood sugar before meals.', vitals: true },
    { id: 3, name: 'Elena Rodriguez', address: '789 Pine St, Campbell, CA 95008', phone: '(408) 555-3001', emergency: 'Maria Rodriguez (Sister) - (408) 555-3002', procedures: ['Companionship', 'Grocery shopping', 'Medication management', 'Doctor appointment transport'], notes: 'Spanish speaking preferred. Enjoys gardening.', vitals: false },
    { id: 4, name: 'William Park', address: '321 Cedar Ave, Cupertino, CA 95014', phone: '(408) 555-4001', emergency: 'Susan Park (Wife) - (408) 555-4002', procedures: ['Post-surgery care', 'Medication administration', 'Wound dressing', 'Mobility exercises'], notes: 'Recent hip replacement. Use walker assistance.', vitals: true },
  ];

  const supplyItems = ['Disposable Gloves (Box)', 'Hand Sanitizer', 'Face Masks', 'Bandages', 'Antiseptic Wipes', 'Blood Pressure Cuff', 'Thermometer Covers', 'Pulse Oximeter', 'Wound Care Kit', 'Other'];

  const incidentTypes = ['Fall', 'Medication Error', 'Skin Injury', 'Behavioral Issue', 'Equipment Malfunction', 'Missed Visit', 'Client Complaint', 'Other'];

  // Timer
  useEffect(() => {
    const timer = setInterval(() => setTime(new Date()), 1000);
    return () => clearInterval(timer);
  }, []);

  // Load saved data
  useEffect(() => {
    try {
      const saved = localStorage.getItem('ec_entries');
      if (saved) setEntries(JSON.parse(saved));
      const savedMileage = localStorage.getItem('ec_mileage');
      if (savedMileage) setMileageEntries(JSON.parse(savedMileage));
      const savedIncidents = localStorage.getItem('ec_incidents');
      if (savedIncidents) setIncidents(JSON.parse(savedIncidents));
    } catch (e) { console.log('Storage error'); }
  }, []);

  // Save helpers
  const saveEntries = (data) => { setEntries(data); try { localStorage.setItem('ec_entries', JSON.stringify(data)); } catch (e) {} };
  const saveMileage = (data) => { setMileageEntries(data); try { localStorage.setItem('ec_mileage', JSON.stringify(data)); } catch (e) {} };
  const saveIncidents = (data) => { setIncidents(data); try { localStorage.setItem('ec_incidents', JSON.stringify(data)); } catch (e) {} };

  // Geolocation
  const getLocation = () => new Promise((resolve, reject) => {
    if (!navigator.geolocation) return reject(new Error('No GPS'));
    navigator.geolocation.getCurrentPosition(
      pos => resolve({ lat: pos.coords.latitude, lng: pos.coords.longitude, accuracy: pos.coords.accuracy }),
      err => reject(err),
      { enableHighAccuracy: true, timeout: 15000 }
    );
  });

  // Utility functions
  const formatTime = d => d ? new Date(d).toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' }) : '--:--';
  const formatDate = d => d ? new Date(d).toLocaleDateString('en-US', { month: 'short', day: 'numeric' }) : '';
  const formatFullDate = d => d ? new Date(d).toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric' }) : '';

  const elapsed = () => {
    if (!clockInTime) return '00:00:00';
    const diff = time - clockInTime;
    const h = Math.floor(diff / 3600000);
    const m = Math.floor((diff % 3600000) / 60000);
    const s = Math.floor((diff % 60000) / 1000);
    return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
  };

  const calcDistance = (lat1, lng1, lat2, lng2) => {
    const R = 3959;
    const dLat = (lat2 - lat1) * Math.PI / 180;
    const dLng = (lng2 - lng1) * Math.PI / 180;
    const a = Math.sin(dLat / 2) ** 2 + Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * Math.sin(dLng / 2) ** 2;
    return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  };

  // Auth
  const handleLogin = () => {
    setError('');
    const found = users.find(u => u.email.toLowerCase() === email.toLowerCase() && u.password === password);
    if (found) {
      setUser(found);
      setView(found.role === 'admin' ? 'admin' : found.role === 'client' ? 'client' : 'dashboard');
    } else {
      setError('Invalid email or password');
    }
  };

  const handleLogout = () => {
    setUser(null);
    setView('login');
    setEmail('');
    setPassword('');
    setClockedIn(false);
    setClockInTime(null);
    setActiveTab('clock');
  };

  // Clock functions
  const handleClockIn = async () => {
    if (!selectedClient) return alert('Select a client first');
    setLoading(true);
    try {
      const loc = await getLocation();
      const client = clients.find(c => c.id === parseInt(selectedClient));
      setClockInTime(new Date());
      setClockInLocation(loc);
      setClockedIn(true);
      setBreaks([]);
      setProcedures(client.procedures.map(p => ({ name: p, done: false, time: null })));
    } catch (e) {
      alert('Could not get location. Please enable GPS and try again.');
    }
    setLoading(false);
  };

  const handleClockOut = async () => {
    if (onBreak) return alert('End your break before clocking out');
    setLoading(true);
    try {
      const loc = await getLocation();
      const now = new Date();
      const hours = ((now - clockInTime) / 3600000).toFixed(2);
      const client = clients.find(c => c.id === parseInt(selectedClient));
      
      // CA break compliance check
      const totalBreakMins = breaks.reduce((sum, b) => sum + b.duration, 0);
      let warnings = [];
      if (parseFloat(hours) >= 5 && !breaks.some(b => b.type === 'meal')) {
        warnings.push('Missing required 30-min meal break (5+ hours worked)');
      }
      if (parseFloat(hours) >= 3.5 && totalBreakMins < 10) {
        warnings.push('Rest break recommended (10 min per 4 hours)');
      }

      const entry = {
        id: Date.now(),
        odometer: 0,
        date: clockInTime.toISOString(),
        caregiver: user.name,
        odometer: 0,
        caregiverId: user.id,
        client: client.name,
        clientId: client.id,
        clockIn: clockInTime.toISOString(),
        clockInLoc: clockInLocation,
        clockOut: now.toISOString(),
        clockOutLoc: loc,
        hours,
        procedures,
        notes,
        breaks,
        breakMins: totalBreakMins,
        warnings
      };

      saveEntries([entry, ...entries]);
      setClockedIn(false);
      setClockInTime(null);
      setClockInLocation(null);
      setSelectedClient('');
      setNotes('');
      setProcedures([]);
      setBreaks([]);

      if (warnings.length > 0) {
        alert(`⚠️ Compliance Warning:\n${warnings.join('\n')}\n\nTotal: ${hours} hours`);
      } else {
        alert(`Clocked out successfully!\nTotal: ${hours} hours`);
      }
    } catch (e) {
      alert('Could not get location');
    }
    setLoading(false);
  };

  // Break functions
  const startBreak = (type) => {
    setOnBreak(true);
    setBreakStart({ time: new Date(), type });
  };

  const endBreak = () => {
    const duration = Math.round((new Date() - breakStart.time) / 60000);
    setBreaks([...breaks, { type: breakStart.type, duration, start: breakStart.time.toISOString() }]);
    setOnBreak(false);
    setBreakStart(null);
  };

  // Mileage functions
  const startTrip = async () => {
    setLoading(true);
    try {
      const loc = await getLocation();
      setTripStart(new Date());
      setTripStartLoc(loc);
      setTracking(true);
    } catch (e) {
      alert('Could not get location');
    }
    setLoading(false);
  };

  const endTrip = async () => {
    setLoading(true);
    try {
      const loc = await getLocation();
      const miles = calcDistance(tripStartLoc.lat, tripStartLoc.lng, loc.lat, loc.lng).toFixed(2);
      const entry = {
        id: Date.now(),
        odometer: 0,
        date: tripStart.toISOString(),
        caregiver: user.name,
        odometer: 0,
        caregiverId: user.id,
        miles,
        purpose: tripPurpose || 'Client visit',
        reimbursement: (miles * 0.70).toFixed(2), // 2025 IRS rate
        startLoc: tripStartLoc,
        endLoc: loc
      };
      saveMileage([entry, ...mileageEntries]);
      setTracking(false);
      setTripStart(null);
      setTripStartLoc(null);
      setTripPurpose('');
      alert(`Trip recorded: ${miles} miles\nReimbursement: $${entry.reimbursement}`);
    } catch (e) {
      alert('Could not get location');
    }
    setLoading(false);
  };

  // Shift trading functions
  const postShiftForTrade = (shiftId) => {
    setShifts(shifts.map(s => s.id === shiftId ? { ...s, available: true } : s));
  };

  const removeFromTrade = (shiftId) => {
    setShifts(shifts.map(s => s.id === shiftId ? { ...s, available: false, requestedBy: null } : s));
  };

  const requestShift = (shiftId) => {
    const shift = shifts.find(s => s.id === shiftId);
    if (shift.caregiverId === user?.id) return alert("Can't request your own shift");
    setShifts(shifts.map(s => s.id === shiftId ? { ...s, requestedBy: user?.id } : s));
    setTradeRequests([...tradeRequests, { id: Date.now(), shiftId, requesterId: user?.id, requesterName: user?.name, status: 'pending' }]);
    alert('Trade request sent!');
  };

  const approveTradeRequest = (shiftId, requesterId) => {
    const requester = caregivers.find(c => c.id === requesterId);
    setShifts(shifts.map(s => s.id === shiftId ? { ...s, caregiver: requester?.name, caregiverId: requesterId, available: false, requestedBy: null } : s));
    setTradeRequests(tradeRequests.filter(r => r.shiftId !== shiftId));
    alert('Trade approved!');
  };

  const denyTradeRequest = (shiftId) => {
    setShifts(shifts.map(s => s.id === shiftId ? { ...s, requestedBy: null } : s));
    setTradeRequests(tradeRequests.filter(r => r.shiftId !== shiftId));
  };

  // Message functions
  const sendMessage = () => {
    if (!newMessage.to || !newMessage.subject || !newMessage.body) return alert('Fill all fields');
    const msg = {
      id: Date.now(),
      from: user.name,
      fromId: user.id,
      to: parseInt(newMessage.to),
      subject: newMessage.subject,
      body: newMessage.body,
      date: new Date().toISOString(),
      read: false,
      type: 'message'
    };
    setMessages([msg, ...messages]);
    setNewMessage({ to: '', subject: '', body: '' });
    setComposeOpen(false);
    alert('Message sent!');
  };

  // Incident functions
  const submitIncident = () => {
    if (!newIncident.client || !newIncident.type || !newIncident.description) return alert('Fill all required fields');
    const incident = {
      id: Date.now(),
      ...newIncident,
      reportedBy: user.name,
      reportedById: user.id,
      date: new Date().toISOString(),
      status: 'submitted'
    };
    saveIncidents([incident, ...incidents]);
    setNewIncident({ client: '', type: '', description: '', severity: 'low' });
    setIncidentOpen(false);
    alert('Incident report submitted');
  };

  // Supply request
  const submitSupplyRequest = () => {
    if (!newSupply.item) return alert('Select an item');
    const request = {
      id: Date.now(),
      item: newSupply.item,
      quantity: newSupply.quantity,
      status: 'pending',
      requestedBy: user.name,
      requestedById: user.id,
      date: new Date().toISOString().split('T')[0]
    };
    setSupplyRequests([request, ...supplyRequests]);
    setNewSupply({ item: '', quantity: 1 });
    alert('Supply request submitted');
  };

  // Computed values
  const myShifts = shifts.filter(s => s.caregiverId === user?.id);
  const availableShifts = shifts.filter(s => s.available && s.caregiverId !== user?.id);
  const pendingRequests = tradeRequests.filter(r => shifts.find(s => s.id === r.shiftId)?.caregiverId === user?.id);
  const myMessages = messages.filter(m => m.to === user?.id || m.to === 'all');
  const unreadCount = myMessages.filter(m => !m.read).length;

  // Styles
  const colors = {
    bg: '#0f172a',
    card: '#1e293b',
    cardLight: '#334155',
    primary: '#059669',
    primaryLight: '#10b981',
    danger: '#dc2626',
    warning: '#d97706',
    info: '#0369a1',
    purple: '#7c3aed',
    text: '#f1f5f9',
    textMuted: '#94a3b8',
    textDim: '#64748b',
    border: '#475569',
  };

  const styles = {
    container: { minHeight: '100vh', background: colors.bg, fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif', color: colors.text, WebkitFontSmoothing: 'antialiased' },
    header: { background: `linear-gradient(135deg, ${colors.primary} 0%, ${colors.primaryLight} 100%)`, padding: '16px 20px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', position: 'sticky', top: 0, zIndex: 100 },
    logo: { fontSize: '18px', fontWeight: '700', display: 'flex', alignItems: 'center', gap: '8px' },
    badge: { fontSize: '11px', padding: '5px 10px', background: 'rgba(255,255,255,0.2)', borderRadius: '20px', fontWeight: '600' },
    main: { padding: '16px 20px 100px' },
    card: { background: colors.card, borderRadius: '16px', padding: '20px', marginBottom: '16px' },
    cardTitle: { fontSize: '16px', fontWeight: '600', marginBottom: '14px', display: 'flex', alignItems: 'center', gap: '8px' },
    input: { width: '100%', padding: '14px 16px', fontSize: '17px', background: colors.bg, border: `2px solid ${colors.border}`, borderRadius: '12px', color: colors.text, boxSizing: 'border-box', marginBottom: '12px', outline: 'none' },
    select: { width: '100%', padding: '14px 16px', fontSize: '17px', background: colors.bg, border: `2px solid ${colors.border}`, borderRadius: '12px', color: colors.text, boxSizing: 'border-box', marginBottom: '12px', outline: 'none', appearance: 'none' },
    textarea: { width: '100%', padding: '14px 16px', fontSize: '16px', background: colors.bg, border: `2px solid ${colors.border}`, borderRadius: '12px', color: colors.text, boxSizing: 'border-box', marginBottom: '12px', outline: 'none', minHeight: '100px', resize: 'vertical', fontFamily: 'inherit' },
    label: { display: 'block', fontSize: '12px', fontWeight: '600', color: colors.textMuted, marginBottom: '6px', textTransform: 'uppercase', letterSpacing: '0.5px' },
    btn: { width: '100%', padding: '16px', fontSize: '17px', fontWeight: '600', border: 'none', borderRadius: '12px', color: '#fff', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '8px' },
    btnPrimary: { background: `linear-gradient(135deg, ${colors.primary} 0%, ${colors.primaryLight} 100%)` },
    btnDanger: { background: colors.danger },
    btnWarning: { background: colors.warning },
    btnInfo: { background: colors.info },
    btnSecondary: { background: colors.cardLight },
    btnSmall: { padding: '10px 16px', fontSize: '14px', borderRadius: '10px' },
    nav: { position: 'fixed', bottom: 0, left: 0, right: 0, background: colors.bg, display: 'flex', justifyContent: 'space-around', padding: '10px 0 28px', borderTop: `1px solid ${colors.cardLight}`, zIndex: 100 },
    navBtn: { background: 'none', border: 'none', color: colors.textDim, fontSize: '11px', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '4px', padding: '4px 8px', position: 'relative' },
    navActive: { color: colors.primaryLight },
    navBadge: { position: 'absolute', top: '-2px', right: '0', background: colors.danger, color: '#fff', fontSize: '10px', fontWeight: '700', padding: '2px 6px', borderRadius: '10px', minWidth: '16px', textAlign: 'center' },
    tabs: { display: 'flex', gap: '8px', marginBottom: '16px', overflowX: 'auto', paddingBottom: '4px' },
    tab: { padding: '10px 16px', fontSize: '14px', fontWeight: '600', border: 'none', borderRadius: '10px', background: colors.cardLight, color: colors.textMuted, whiteSpace: 'nowrap', cursor: 'pointer' },
    tabActive: { background: colors.primary, color: '#fff' },
    listItem: { background: colors.bg, padding: '14px', borderRadius: '12px', marginBottom: '10px' },
    flexBetween: { display: 'flex', justifyContent: 'space-between', alignItems: 'center' },
    flexRow: { display: 'flex', gap: '10px' },
    statusBadge: { padding: '4px 10px', borderRadius: '20px', fontSize: '11px', fontWeight: '600' },
    clockDisplay: { textAlign: 'center', padding: '20px 0' },
    clockTime: { fontSize: '44px', fontWeight: '700', color: colors.primaryLight, letterSpacing: '1px' },
    clockDate: { fontSize: '14px', color: colors.textMuted, marginTop: '4px' },
    elapsed: { fontSize: '32px', fontWeight: '700', marginTop: '16px' },
    statGrid: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' },
    statCard: { background: colors.bg, padding: '16px', borderRadius: '12px', textAlign: 'center' },
    statValue: { fontSize: '28px', fontWeight: '700', color: colors.primaryLight },
    statLabel: { fontSize: '12px', color: colors.textDim, marginTop: '4px' },
    checkbox: { width: '24px', height: '24px', borderRadius: '8px', border: `2px solid ${colors.border}`, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, cursor: 'pointer' },
    checkboxChecked: { background: colors.primaryLight, borderColor: colors.primaryLight },
    modal: { position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, background: 'rgba(0,0,0,0.8)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '20px', zIndex: 200 },
    modalContent: { background: colors.card, borderRadius: '20px', padding: '24px', width: '100%', maxWidth: '400px', maxHeight: '80vh', overflow: 'auto' },
    emergencyBtn: { position: 'fixed', bottom: '100px', right: '20px', width: '60px', height: '60px', borderRadius: '30px', background: colors.danger, border: 'none', color: '#fff', fontSize: '24px', boxShadow: '0 4px 20px rgba(220,38,38,0.5)', zIndex: 99, cursor: 'pointer' },
  };

  // ==================== SCREENS ====================

  // LOGIN SCREEN
  if (view === 'login') {
    return (
      <div style={{ ...styles.container, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '20px' }}>
        <div style={{ width: '100%', maxWidth: '380px' }}>
          <div style={styles.card}>
            <div style={{ textAlign: 'center', marginBottom: '28px' }}>
              <div style={{ fontSize: '56px', marginBottom: '12px' }}>💚</div>
              <h1 style={{ margin: '0 0 6px', fontSize: '26px', fontWeight: '700' }}>Essential Care</h1>
              <p style={{ margin: 0, color: colors.textMuted, fontSize: '14px' }}>Home Health Management</p>
            </div>

            {error && (
              <div style={{ background: 'rgba(220,38,38,0.15)', border: '1px solid rgba(220,38,38,0.3)', padding: '12px', borderRadius: '10px', marginBottom: '16px', fontSize: '14px', color: '#fca5a5' }}>
                ⚠️ {error}
              </div>
            )}

            <label style={styles.label}>Email</label>
            <input type="email" inputMode="email" autoCapitalize="none" autoCorrect="off" autoComplete="email" style={styles.input} value={email} onChange={e => setEmail(e.target.value)} placeholder="Enter your email" />

            <label style={styles.label}>Password</label>
            <input type="password" autoComplete="current-password" style={styles.input} value={password} onChange={e => setPassword(e.target.value)} placeholder="Enter your password" />

            <button style={{ ...styles.btn, ...styles.btnPrimary, marginTop: '8px' }} onClick={handleLogin}>Sign In</button>

            <div style={{ marginTop: '24px', padding: '16px', background: colors.bg, borderRadius: '12px', fontSize: '13px' }}>
              <div style={{ fontWeight: '600', marginBottom: '10px', color: '#fff' }}>Demo Accounts:</div>
              <div style={{ marginBottom: '8px', color: colors.textMuted }}>
                <span style={{ color: colors.primaryLight }}>Caregiver:</span> sarah@essentialcare.com / demo123
              </div>
              <div style={{ marginBottom: '8px', color: colors.textMuted }}>
                <span style={{ color: colors.primaryLight }}>Admin:</span> admin@essentialcare.com / admin123
              </div>
              <div style={{ color: colors.textMuted }}>
                <span style={{ color: colors.primaryLight }}>Client:</span> margaret.j@email.com / client123
              </div>
            </div>
          </div>
          <p style={{ textAlign: 'center', marginTop: '16px', color: colors.textDim, fontSize: '12px' }}>
            🔒 Secure • HIPAA Compliant • California
          </p>
        </div>
      </div>
    );
  }

  // CAREGIVER DASHBOARD
  if (view === 'dashboard') {
    return (
      <div style={styles.container}>
        <header style={styles.header}>
          <div style={styles.logo}>💚 Essential Care</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
            <span style={{ ...styles.badge, background: clockedIn ? 'rgba(16,185,129,0.3)' : 'rgba(255,255,255,0.2)' }}>
              {clockedIn ? '● Active' : '○ Off Duty'}
            </span>
          </div>
        </header>

        <div style={{ padding: '16px 20px 0' }}>
          <div style={styles.tabs}>
            {[
              { key: 'clock', icon: '⏱️', label: 'Clock' },
              { key: 'schedule', icon: '📅', label: 'Schedule' },
              { key: 'messages', icon: '💬', label: 'Messages', badge: unreadCount },
              { key: 'more', icon: '☰', label: 'More' }
            ].map(t => (
              <button key={t.key} onClick={() => setActiveTab(t.key)} style={{ ...styles.tab, ...(activeTab === t.key ? styles.tabActive : {}), position: 'relative' }}>
                {t.icon} {t.label}
                {t.badge > 0 && <span style={{ ...styles.navBadge, position: 'relative', top: 0, right: 0, marginLeft: '6px' }}>{t.badge}</span>}
              </button>
            ))}
          </div>
        </div>

        <main style={styles.main}>
          {/* CLOCK TAB */}
          {activeTab === 'clock' && (
            <>
              <div style={{ ...styles.card, ...styles.clockDisplay }}>
                <div style={styles.clockTime}>{time.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', second: '2-digit' })}</div>
                <div style={styles.clockDate}>{time.toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric' })}</div>
                {clockedIn && <div style={styles.elapsed}>{elapsed()}</div>}
              </div>

              {!clockedIn ? (
                <div style={styles.card}>
                  <label style={styles.label}>Select Client</label>
                  <select style={styles.select} value={selectedClient} onChange={e => setSelectedClient(e.target.value)}>
                    <option value="">Choose a client...</option>
                    {clients.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
                  </select>

                  {selectedClient && (
                    <div style={{ ...styles.listItem, marginBottom: '16px' }}>
                      <div style={{ fontSize: '13px', color: colors.textMuted, marginBottom: '4px' }}>📍 {clients.find(c => c.id === parseInt(selectedClient))?.address}</div>
                      <div style={{ fontSize: '12px', color: colors.warning, marginTop: '8px' }}>⚠️ {clients.find(c => c.id === parseInt(selectedClient))?.notes}</div>
                    </div>
                  )}

                  <button style={{ ...styles.btn, ...styles.btnPrimary, opacity: loading ? 0.6 : 1 }} onClick={handleClockIn} disabled={loading}>
                    {loading ? '⏳ Getting Location...' : '📍 Clock In'}
                  </button>
                  <p style={{ textAlign: 'center', marginTop: '10px', fontSize: '12px', color: colors.textDim }}>GPS verification required</p>
                </div>
              ) : (
                <>
                  {/* Current Client */}
                  <div style={styles.card}>
                    <div style={{ fontSize: '12px', color: colors.textDim, textTransform: 'uppercase', letterSpacing: '0.5px' }}>Currently With</div>
                    <div style={{ fontSize: '20px', fontWeight: '600', marginTop: '4px' }}>{clients.find(c => c.id === parseInt(selectedClient))?.name}</div>
                    <div style={{ marginTop: '10px', padding: '10px 12px', background: 'rgba(16,185,129,0.15)', borderRadius: '10px', fontSize: '13px', color: colors.primaryLight }}>
                      ✓ Clocked in at {formatTime(clockInTime)} • GPS Verified
                    </div>
                  </div>

                  {/* Break Tracking */}
                  <div style={styles.card}>
                    <div style={styles.cardTitle}>☕ Break Tracking (CA Labor Law)</div>
                    {!onBreak ? (
                      <div style={styles.flexRow}>
                        <button style={{ ...styles.btn, ...styles.btnInfo, flex: 1 }} onClick={() => startBreak('rest')}>
                          ☕ Rest (10min)
                        </button>
                        <button style={{ ...styles.btn, background: colors.purple, flex: 1 }} onClick={() => startBreak('meal')}>
                          🍽️ Meal (30min)
                        </button>
                      </div>
                    ) : (
                      <div style={{ textAlign: 'center' }}>
                        <div style={{ color: colors.warning, marginBottom: '8px', fontSize: '16px' }}>
                          {breakStart?.type === 'meal' ? '🍽️ Meal' : '☕ Rest'} Break in Progress
                        </div>
                        <div style={{ fontSize: '32px', fontWeight: '700', marginBottom: '12px' }}>
                          {Math.round((time - breakStart?.time) / 60000)} min
                        </div>
                        <button style={{ ...styles.btn, ...styles.btnWarning }} onClick={endBreak}>End Break</button>
                      </div>
                    )}
                    {breaks.length > 0 && (
                      <div style={{ marginTop: '14px', fontSize: '13px', color: colors.textMuted }}>
                        <div style={{ fontWeight: '600', marginBottom: '6px' }}>Today's Breaks:</div>
                        {breaks.map((b, i) => <div key={i}>{b.type === 'meal' ? '🍽️' : '☕'} {b.duration} min</div>)}
                      </div>
                    )}
                  </div>

                  {/* Procedures */}
                  <div style={styles.card}>
                    <div style={styles.cardTitle}>📋 Care Tasks</div>
                    {procedures.map((p, i) => (
                      <div key={i} onClick={() => {
                        const updated = [...procedures];
                        updated[i].done = !updated[i].done;
                        updated[i].time = updated[i].done ? new Date().toISOString() : null;
                        setProcedures(updated);
                      }} style={{ ...styles.listItem, display: 'flex', alignItems: 'center', gap: '12px', cursor: 'pointer', background: p.done ? 'rgba(16,185,129,0.1)' : colors.bg }}>
                        <div style={{ ...styles.checkbox, ...(p.done ? styles.checkboxChecked : {}) }}>
                          {p.done && <span style={{ color: '#fff', fontSize: '14px' }}>✓</span>}
                        </div>
                        <div style={{ flex: 1 }}>
                          <div style={{ fontWeight: '500', textDecoration: p.done ? 'line-through' : 'none', opacity: p.done ? 0.7 : 1 }}>{p.name}</div>
                          {p.done && p.time && <div style={{ fontSize: '11px', color: colors.primaryLight, marginTop: '2px' }}>Completed {formatTime(p.time)}</div>}
                        </div>
                      </div>
                    ))}
                  </div>

                  {/* Notes */}
                  <div style={styles.card}>
                    <label style={styles.label}>Daily Notes</label>
                    <textarea style={styles.textarea} value={notes} onChange={e => setNotes(e.target.value)} placeholder="Document care activities, observations, client condition..." />
                  </div>

                  {/* Clock Out */}
                  <button style={{ ...styles.btn, ...styles.btnDanger, opacity: loading || onBreak ? 0.6 : 1 }} onClick={handleClockOut} disabled={loading || onBreak}>
                    {loading ? '⏳ Getting Location...' : '🛑 Clock Out'}
                  </button>
                  {onBreak && <p style={{ textAlign: 'center', marginTop: '8px', fontSize: '13px', color: colors.warning }}>End your break before clocking out</p>}
                </>
              )}
            </>
          )}

          {/* SCHEDULE TAB */}
          {activeTab === 'schedule' && (
            <>
              <div style={styles.tabs}>
                {['myShifts', 'available', 'requests'].map(t => (
                  <button key={t} onClick={() => setScheduleTab(t)} style={{ ...styles.tab, flex: 1, ...(scheduleTab === t ? { ...styles.tabActive, background: colors.info } : {}) }}>
                    {t === 'myShifts' ? 'My Shifts' : t === 'available' ? 'Available' : `Requests ${pendingRequests.length > 0 ? `(${pendingRequests.length})` : ''}`}
                  </button>
                ))}
              </div>

              {scheduleTab === 'myShifts' && (
                <div style={styles.card}>
                  <div style={styles.cardTitle}>📅 My Upcoming Shifts</div>
                  {myShifts.length === 0 ? (
                    <div style={{ textAlign: 'center', color: colors.textDim, padding: '20px' }}>No shifts scheduled</div>
                  ) : (
                    myShifts.map(shift => (
                      <div key={shift.id} style={styles.listItem}>
                        <div style={styles.flexBetween}>
                          <div>
                            <div style={{ fontWeight: '600' }}>{shift.client}</div>
                            <div style={{ fontSize: '13px', color: colors.textMuted }}>{shift.date}</div>
                            <div style={{ fontSize: '13px', color: colors.primaryLight }}>{shift.time}</div>
                          </div>
                          {shift.available && (
                            <span style={{ ...styles.statusBadge, background: 'rgba(217,119,6,0.2)', color: '#fbbf24' }}>Up for Trade</span>
                          )}
                        </div>
                        {shift.requestedBy && (
                          <div style={{ background: 'rgba(3,105,161,0.2)', padding: '12px', borderRadius: '10px', marginTop: '12px' }}>
                            <div style={{ fontSize: '13px', color: '#60a5fa', marginBottom: '8px' }}>
                              ⚡ {caregivers.find(c => c.id === shift.requestedBy)?.name} wants this shift
                            </div>
                            <div style={styles.flexRow}>
                              <button style={{ ...styles.btn, ...styles.btnPrimary, ...styles.btnSmall, flex: 1 }} onClick={() => approveTradeRequest(shift.id, shift.requestedBy)}>Approve</button>
                              <button style={{ ...styles.btn, ...styles.btnDanger, ...styles.btnSmall, flex: 1 }} onClick={() => denyTradeRequest(shift.id)}>Deny</button>
                            </div>
                          </div>
                        )}
                        <div style={{ marginTop: '12px' }}>
                          {!shift.available ? (
                            <button style={{ ...styles.btn, ...styles.btnSecondary, ...styles.btnSmall }} onClick={() => postShiftForTrade(shift.id)}>🔄 Post for Trade</button>
                          ) : (
                            <button style={{ ...styles.btn, background: '#7f1d1d', ...styles.btnSmall }} onClick={() => removeFromTrade(shift.id)}>✕ Remove from Trade</button>
                          )}
                        </div>
                      </div>
                    ))
                  )}
                </div>
              )}

              {scheduleTab === 'available' && (
                <div style={styles.card}>
                  <div style={styles.cardTitle}>🔄 Available for Trade</div>
                  {availableShifts.length === 0 ? (
                    <div style={{ textAlign: 'center', color: colors.textDim, padding: '20px' }}>No shifts available</div>
                  ) : (
                    availableShifts.map(shift => (
                      <div key={shift.id} style={styles.listItem}>
                        <div style={{ fontWeight: '600' }}>{shift.client}</div>
                        <div style={{ fontSize: '13px', color: colors.textMuted }}>{shift.date} • {shift.time}</div>
                        <div style={{ fontSize: '12px', color: colors.textDim, marginTop: '4px' }}>Currently: {shift.caregiver}</div>
                        <div style={{ marginTop: '12px' }}>
                          {shift.requestedBy === user?.id ? (
                            <div style={{ padding: '10px', background: 'rgba(3,105,161,0.2)', borderRadius: '8px', textAlign: 'center', fontSize: '13px', color: '#60a5fa' }}>⏳ Request Pending</div>
                          ) : (
                            <button style={{ ...styles.btn, ...styles.btnInfo, ...styles.btnSmall }} onClick={() => requestShift(shift.id)}>✋ Request This Shift</button>
                          )}
                        </div>
                      </div>
                    ))
                  )}
                </div>
              )}

              {scheduleTab === 'requests' && (
                <div style={styles.card}>
                  <div style={styles.cardTitle}>📨 Trade Requests</div>
                  {pendingRequests.length === 0 ? (
                    <div style={{ textAlign: 'center', color: colors.textDim, padding: '20px' }}>No pending requests</div>
                  ) : (
                    pendingRequests.map(req => {
                      const shift = shifts.find(s => s.id === req.shiftId);
                      return (
                        <div key={req.id} style={styles.listItem}>
                          <div style={{ fontSize: '14px', color: '#60a5fa', marginBottom: '6px' }}>{req.requesterName} wants:</div>
                          <div style={{ fontWeight: '600' }}>{shift?.client}</div>
                          <div style={{ fontSize: '13px', color: colors.textMuted }}>{shift?.date} • {shift?.time}</div>
                          <div style={{ ...styles.flexRow, marginTop: '12px' }}>
                            <button style={{ ...styles.btn, ...styles.btnPrimary, ...styles.btnSmall, flex: 1 }} onClick={() => approveTradeRequest(req.shiftId, req.requesterId)}>✓ Approve</button>
                            <button style={{ ...styles.btn, ...styles.btnDanger, ...styles.btnSmall, flex: 1 }} onClick={() => denyTradeRequest(req.shiftId)}>✕ Deny</button>
                          </div>
                        </div>
                      );
                    })
                  )}
                </div>
              )}
            </>
          )}

          {/* MESSAGES TAB */}
          {activeTab === 'messages' && (
            <>
              <div style={{ ...styles.flexBetween, marginBottom: '16px' }}>
                <div style={styles.tabs}>
                  <button onClick={() => setMessageTab('inbox')} style={{ ...styles.tab, ...(messageTab === 'inbox' ? styles.tabActive : {}) }}>Inbox</button>
                  <button onClick={() => setMessageTab('sent')} style={{ ...styles.tab, ...(messageTab === 'sent' ? styles.tabActive : {}) }}>Sent</button>
                </div>
                <button style={{ ...styles.btn, ...styles.btnPrimary, ...styles.btnSmall, width: 'auto' }} onClick={() => setComposeOpen(true)}>+ New</button>
              </div>

              <div style={styles.card}>
                {myMessages.length === 0 ? (
                  <div style={{ textAlign: 'center', color: colors.textDim, padding: '20px' }}>No messages</div>
                ) : (
                  myMessages.map(msg => (
                    <div key={msg.id} onClick={() => {
                      setMessages(messages.map(m => m.id === msg.id ? { ...m, read: true } : m));
                    }} style={{ ...styles.listItem, borderLeft: msg.read ? 'none' : `3px solid ${colors.primaryLight}`, cursor: 'pointer' }}>
                      <div style={styles.flexBetween}>
                        <div style={{ fontWeight: msg.read ? '400' : '600' }}>{msg.subject}</div>
                        <div style={{ fontSize: '11px', color: colors.textDim }}>{formatDate(msg.date)}</div>
                      </div>
                      <div style={{ fontSize: '13px', color: colors.textMuted, marginTop: '4px' }}>From: {msg.from}</div>
                      <div style={{ fontSize: '13px', color: colors.textDim, marginTop: '6px' }}>{msg.body.substring(0, 60)}...</div>
                    </div>
                  ))
                )}
              </div>

              {/* Compose Modal */}
              {composeOpen && (
                <div style={styles.modal} onClick={() => setComposeOpen(false)}>
                  <div style={styles.modalContent} onClick={e => e.stopPropagation()}>
                    <div style={{ ...styles.flexBetween, marginBottom: '20px' }}>
                      <div style={{ fontSize: '18px', fontWeight: '600' }}>New Message</div>
                      <button style={{ background: 'none', border: 'none', color: colors.textMuted, fontSize: '24px', cursor: 'pointer' }} onClick={() => setComposeOpen(false)}>×</button>
                    </div>
                    <label style={styles.label}>To</label>
                    <select style={styles.select} value={newMessage.to} onChange={e => setNewMessage({ ...newMessage, to: e.target.value })}>
                      <option value="">Select recipient...</option>
                      {users.filter(u => u.id !== user?.id).map(u => <option key={u.id} value={u.id}>{u.name}</option>)}
                    </select>
                    <label style={styles.label}>Subject</label>
                    <input style={styles.input} value={newMessage.subject} onChange={e => setNewMessage({ ...newMessage, subject: e.target.value })} placeholder="Subject" />
                    <label style={styles.label}>Message</label>
                    <textarea style={styles.textarea} value={newMessage.body} onChange={e => setNewMessage({ ...newMessage, body: e.target.value })} placeholder="Type your message..." />
                    <button style={{ ...styles.btn, ...styles.btnPrimary }} onClick={sendMessage}>Send Message</button>
                  </div>
                </div>
              )}
            </>
          )}

          {/* MORE TAB */}
          {activeTab === 'more' && (
            <>
              {/* Mileage */}
              <div style={styles.card}>
                <div style={styles.cardTitle}>🚗 Mileage Tracking</div>
                <p style={{ fontSize: '13px', color: colors.textMuted, marginBottom: '16px' }}>$0.70/mile (2025 IRS rate)</p>
                {!tracking ? (
                  <>
                    <label style={styles.label}>Trip Purpose</label>
                    <input style={styles.input} value={tripPurpose} onChange={e => setTripPurpose(e.target.value)} placeholder="e.g., Client visit - Margaret Johnson" />
                    <button style={{ ...styles.btn, ...styles.btnPrimary, opacity: loading ? 0.6 : 1 }} onClick={startTrip} disabled={loading}>
                      {loading ? '⏳...' : '📍 Start Trip'}
                    </button>
                  </>
                ) : (
                  <div style={{ textAlign: 'center' }}>
                    <div style={{ color: colors.primaryLight, marginBottom: '12px', fontSize: '16px' }}>🚗 Trip in progress</div>
                    <button style={{ ...styles.btn, ...styles.btnDanger, opacity: loading ? 0.6 : 1 }} onClick={endTrip} disabled={loading}>
                      {loading ? '⏳...' : '🏁 End Trip'}
                    </button>
                  </div>
                )}
                {mileageEntries.length > 0 && (
                  <div style={{ marginTop: '20px' }}>
                    <div style={{ fontWeight: '600', marginBottom: '12px', fontSize: '14px' }}>Recent Trips</div>
                    {mileageEntries.slice(0, 3).map(e => (
                      <div key={e.id} style={styles.listItem}>
                        <div style={styles.flexBetween}>
                          <span>{e.miles} mi</span>
                          <span style={{ color: colors.primaryLight, fontWeight: '600' }}>${e.reimbursement}</span>
                        </div>
                        <div style={{ fontSize: '12px', color: colors.textDim }}>{formatDate(e.date)} • {e.purpose}</div>
                      </div>
                    ))}
                  </div>
                )}
              </div>

              {/* Time History */}
              <div style={styles.card}>
                <div style={styles.cardTitle}>📋 Recent Time Entries</div>
                {entries.filter(e => e.caregiverId === user?.id).slice(0, 5).map(e => (
                  <div key={e.id} style={styles.listItem}>
                    <div style={styles.flexBetween}>
                      <span style={{ fontWeight: '600' }}>{e.client}</span>
                      <span style={{ color: colors.primaryLight, fontWeight: '600' }}>{e.hours} hrs</span>
                    </div>
                    <div style={{ fontSize: '12px', color: colors.textDim }}>{formatFullDate(e.clockIn)} • {formatTime(e.clockIn)} - {formatTime(e.clockOut)}</div>
                    {e.warnings?.length > 0 && <div style={{ fontSize: '11px', color: colors.warning, marginTop: '4px' }}>⚠️ {e.warnings[0]}</div>}
                  </div>
                ))}
              </div>

              {/* Supply Request */}
              <div style={styles.card}>
                <div style={styles.cardTitle}>📦 Request Supplies</div>
                <label style={styles.label}>Item</label>
                <select style={styles.select} value={newSupply.item} onChange={e => setNewSupply({ ...newSupply, item: e.target.value })}>
                  <option value="">Select item...</option>
                  {supplyItems.map(item => <option key={item} value={item}>{item}</option>)}
                </select>
                <label style={styles.label}>Quantity</label>
                <input type="number" inputMode="numeric" style={styles.input} value={newSupply.quantity} onChange={e => setNewSupply({ ...newSupply, quantity: parseInt(e.target.value) || 1 })} min="1" />
                <button style={{ ...styles.btn, ...styles.btnSecondary }} onClick={submitSupplyRequest}>Submit Request</button>
              </div>

              {/* Incident Report */}
              <div style={styles.card}>
                <div style={styles.cardTitle}>⚠️ Incident Report</div>
                <button style={{ ...styles.btn, ...styles.btnWarning }} onClick={() => setIncidentOpen(true)}>File Incident Report</button>
              </div>

              {/* Training Status */}
              <div style={styles.card}>
                <div style={styles.cardTitle}>🎓 Training & Certifications</div>
                {trainings.map(t => (
                  <div key={t.id} style={{ ...styles.listItem, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <div>
                      <div style={{ fontWeight: '500' }}>{t.name}</div>
                      <div style={{ fontSize: '12px', color: colors.textDim }}>Due: {t.dueDate}</div>
                    </div>
                    <span style={{
                      ...styles.statusBadge,
                      background: t.status === 'current' ? 'rgba(16,185,129,0.2)' : t.status === 'due_soon' ? 'rgba(217,119,6,0.2)' : 'rgba(220,38,38,0.2)',
                      color: t.status === 'current' ? colors.primaryLight : t.status === 'due_soon' ? '#fbbf24' : '#f87171'
                    }}>
                      {t.status === 'current' ? '✓ Current' : t.status === 'due_soon' ? '⏰ Due Soon' : '⚠️ Overdue'}
                    </span>
                  </div>
                ))}
              </div>

              {/* Logout */}
              <button style={{ ...styles.btn, ...styles.btnSecondary, marginTop: '8px' }} onClick={handleLogout}>🚪 Sign Out</button>
            </>
          )}
        </main>

        {/* Incident Modal */}
        {incidentOpen && (
          <div style={styles.modal} onClick={() => setIncidentOpen(false)}>
            <div style={styles.modalContent} onClick={e => e.stopPropagation()}>
              <div style={{ ...styles.flexBetween, marginBottom: '20px' }}>
                <div style={{ fontSize: '18px', fontWeight: '600' }}>⚠️ Incident Report</div>
                <button style={{ background: 'none', border: 'none', color: colors.textMuted, fontSize: '24px', cursor: 'pointer' }} onClick={() => setIncidentOpen(false)}>×</button>
              </div>
              <label style={styles.label}>Client</label>
              <select style={styles.select} value={newIncident.client} onChange={e => setNewIncident({ ...newIncident, client: e.target.value })}>
                <option value="">Select client...</option>
                {clients.map(c => <option key={c.id} value={c.name}>{c.name}</option>)}
              </select>
              <label style={styles.label}>Incident Type</label>
              <select style={styles.select} value={newIncident.type} onChange={e => setNewIncident({ ...newIncident, type: e.target.value })}>
                <option value="">Select type...</option>
                {incidentTypes.map(t => <option key={t} value={t}>{t}</option>)}
              </select>
              <label style={styles.label}>Severity</label>
              <select style={styles.select} value={newIncident.severity} onChange={e => setNewIncident({ ...newIncident, severity: e.target.value })}>
                <option value="low">Low</option>
                <option value="medium">Medium</option>
                <option value="high">High - Requires Immediate Attention</option>
              </select>
              <label style={styles.label}>Description</label>
              <textarea style={styles.textarea} value={newIncident.description} onChange={e => setNewIncident({ ...newIncident, description: e.target.value })} placeholder="Describe what happened, when, and any actions taken..." />
              <button style={{ ...styles.btn, ...styles.btnWarning }} onClick={submitIncident}>Submit Report</button>
            </div>
          </div>
        )}

        {/* Emergency Button */}
        <button style={styles.emergencyBtn} onClick={() => setEmergencyVisible(true)}>🆘</button>

        {/* Emergency Modal */}
        {emergencyVisible && (
          <div style={styles.modal} onClick={() => setEmergencyVisible(false)}>
            <div style={styles.modalContent} onClick={e => e.stopPropagation()}>
              <div style={{ textAlign: 'center', marginBottom: '20px' }}>
                <div style={{ fontSize: '48px', marginBottom: '12px' }}>🆘</div>
                <div style={{ fontSize: '20px', fontWeight: '700', color: colors.danger }}>Emergency Contacts</div>
              </div>
              <a href="tel:911" style={{ ...styles.btn, ...styles.btnDanger, marginBottom: '12px', textDecoration: 'none' }}>📞 Call 911</a>
              <a href="tel:4085550100" style={{ ...styles.btn, ...styles.btnWarning, marginBottom: '12px', textDecoration: 'none' }}>📞 Office: (408) 555-0100</a>
              {selectedClient && (
                <a href={`tel:${clients.find(c => c.id === parseInt(selectedClient))?.phone.replace(/\D/g, '')}`} style={{ ...styles.btn, ...styles.btnInfo, marginBottom: '12px', textDecoration: 'none' }}>
                  📞 Client: {clients.find(c => c.id === parseInt(selectedClient))?.phone}
                </a>
              )}
              <button style={{ ...styles.btn, ...styles.btnSecondary }} onClick={() => setEmergencyVisible(false)}>Close</button>
            </div>
          </div>
        )}

        {/* Bottom Nav */}
        <nav style={styles.nav}>
          <button style={{ ...styles.navBtn, ...(activeTab === 'clock' ? styles.navActive : {}) }} onClick={() => setActiveTab('clock')}>
            <span style={{ fontSize: '22px' }}>⏱️</span>Clock
          </button>
          <button style={{ ...styles.navBtn, ...(activeTab === 'schedule' ? styles.navActive : {}) }} onClick={() => setActiveTab('schedule')}>
            <span style={{ fontSize: '22px' }}>📅</span>Schedule
          </button>
          <button style={{ ...styles.navBtn, ...(activeTab === 'messages' ? styles.navActive : {}) }} onClick={() => setActiveTab('messages')}>
            <span style={{ fontSize: '22px' }}>💬</span>Messages
            {unreadCount > 0 && <span style={styles.navBadge}>{unreadCount}</span>}
          </button>
          <button style={{ ...styles.navBtn, ...(activeTab === 'more' ? styles.navActive : {}) }} onClick={() => setActiveTab('more')}>
            <span style={{ fontSize: '22px' }}>☰</span>More
          </button>
        </nav>
      </div>
    );
  }

  // ADMIN DASHBOARD
  if (view === 'admin') {
    const totalHours = entries.reduce((sum, e) => sum + parseFloat(e.hours || 0), 0);
    const totalMileage = mileageEntries.reduce((sum, e) => sum + parseFloat(e.miles || 0), 0);
    const complianceIssues = entries.filter(e => e.warnings?.length > 0);

    return (
      <div style={styles.container}>
        <header style={styles.header}>
          <div style={styles.logo}>💚 Essential Care</div>
          <span style={styles.badge}>Admin</span>
        </header>

        <div style={{ padding: '16px 20px 0' }}>
          <div style={styles.tabs}>
            {['overview', 'employees', 'clients', 'payroll', 'compliance', 'incidents'].map(t => (
              <button key={t} onClick={() => setAdminTab(t)} style={{ ...styles.tab, ...(adminTab === t ? styles.tabActive : {}) }}>
                {t.charAt(0).toUpperCase() + t.slice(1)}
              </button>
            ))}
          </div>
        </div>

        <main style={styles.main}>
          {adminTab === 'overview' && (
            <>
              <div style={styles.card}>
                <div style={styles.cardTitle}>📊 Dashboard</div>
                <div style={styles.statGrid}>
                  <div style={styles.statCard}><div style={styles.statValue}>{caregivers.length}</div><div style={styles.statLabel}>Caregivers</div></div>
                  <div style={styles.statCard}><div style={styles.statValue}>{clients.length}</div><div style={styles.statLabel}>Clients</div></div>
                  <div style={styles.statCard}><div style={styles.statValue}>{totalHours.toFixed(0)}</div><div style={styles.statLabel}>Hours</div></div>
                  <div style={styles.statCard}><div style={{ ...styles.statValue, color: complianceIssues.length > 0 ? colors.danger : colors.primaryLight }}>{complianceIssues.length}</div><div style={styles.statLabel}>Compliance Issues</div></div>
                </div>
              </div>
              <div style={styles.card}>
                <div style={styles.cardTitle}>Recent Activity</div>
                {entries.slice(0, 5).map(e => (
                  <div key={e.id} style={styles.listItem}>
                    <div style={styles.flexBetween}>
                      <div><div style={{ fontWeight: '600' }}>{e.caregiver}</div><div style={{ fontSize: '12px', color: colors.textDim }}>{e.client}</div></div>
                      <div style={{ textAlign: 'right' }}><div style={{ color: colors.primaryLight, fontWeight: '600' }}>{e.hours} hrs</div><div style={{ fontSize: '11px', color: colors.textDim }}>{formatDate(e.clockIn)}</div></div>
                    </div>
                  </div>
                ))}
              </div>
            </>
          )}

          {adminTab === 'employees' && (
            <div style={styles.card}>
              <div style={styles.cardTitle}>👥 Employees</div>
              {caregivers.map(emp => (
                <div key={emp.id} style={styles.listItem}>
                  <div style={{ fontWeight: '600', fontSize: '16px' }}>{emp.name}</div>
                  <div style={{ fontSize: '13px', color: colors.textMuted }}>{emp.email}</div>
                  <div style={{ fontSize: '13px', color: colors.textMuted }}>{emp.phone}</div>
                  <div style={{ marginTop: '8px', display: 'flex', gap: '8px' }}>
                    <span style={{ ...styles.statusBadge, background: colors.cardLight }}>${emp.rate}/hr</span>
                    <span style={{ ...styles.statusBadge, background: colors.cardLight }}>{entries.filter(e => e.caregiverId === emp.id).reduce((sum, e) => sum + parseFloat(e.hours), 0).toFixed(1)} hrs this period</span>
                  </div>
                </div>
              ))}
            </div>
          )}

          {adminTab === 'clients' && (
            <div style={styles.card}>
              <div style={styles.cardTitle}>🏠 Clients</div>
              {clients.map(c => (
                <div key={c.id} style={styles.listItem}>
                  <div style={{ fontWeight: '600', fontSize: '16px' }}>{c.name}</div>
                  <div style={{ fontSize: '13px', color: colors.textMuted }}>{c.address}</div>
                  <div style={{ fontSize: '13px', color: colors.textMuted }}>{c.phone}</div>
                  <div style={{ fontSize: '12px', color: colors.warning, marginTop: '6px' }}>📞 Emergency: {c.emergency}</div>
                </div>
              ))}
            </div>
          )}

          {adminTab === 'payroll' && (
            <>
              <div style={styles.card}>
                <div style={styles.cardTitle}>💰 Payroll Summary</div>
                <div style={styles.statGrid}>
                  <div style={styles.statCard}><div style={styles.statValue}>${caregivers.reduce((sum, c) => sum + entries.filter(e => e.caregiverId === c.id).reduce((s, e) => s + parseFloat(e.hours) * c.rate, 0), 0).toFixed(0)}</div><div style={styles.statLabel}>Total Wages</div></div>
                  <div style={styles.statCard}><div style={styles.statValue}>${(totalMileage * 0.70).toFixed(0)}</div><div style={styles.statLabel}>Mileage</div></div>
                </div>
              </div>
              <div style={styles.card}>
                <div style={styles.cardTitle}>By Employee</div>
                {caregivers.map(emp => {
                  const empHours = entries.filter(e => e.caregiverId === emp.id).reduce((sum, e) => sum + parseFloat(e.hours), 0);
                  const empMiles = mileageEntries.filter(m => m.caregiverId === emp.id).reduce((sum, m) => sum + parseFloat(m.miles), 0);
                  return (
                    <div key={emp.id} style={styles.listItem}>
                      <div style={styles.flexBetween}>
                        <div style={{ fontWeight: '600' }}>{emp.name}</div>
                        <div style={{ color: colors.primaryLight, fontWeight: '600' }}>${(empHours * emp.rate + empMiles * 0.70).toFixed(2)}</div>
                      </div>
                      <div style={{ fontSize: '12px', color: colors.textDim, marginTop: '4px' }}>{empHours.toFixed(1)} hrs × ${emp.rate} + {empMiles.toFixed(1)} mi</div>
                    </div>
                  );
                })}
              </div>
            </>
          )}

          {adminTab === 'compliance' && (
            <div style={styles.card}>
              <div style={styles.cardTitle}>⚖️ CA Labor Compliance</div>
              {complianceIssues.length === 0 ? (
                <div style={{ padding: '20px', background: 'rgba(16,185,129,0.1)', borderRadius: '12px', textAlign: 'center', color: colors.primaryLight }}>✅ All entries compliant</div>
              ) : (
                complianceIssues.map(e => (
                  <div key={e.id} style={{ ...styles.listItem, borderLeft: `3px solid ${colors.danger}` }}>
                    <div style={{ fontWeight: '600' }}>{e.caregiver}</div>
                    <div style={{ fontSize: '12px', color: colors.textDim }}>{formatDate(e.clockIn)} • {e.client} • {e.hours} hrs</div>
                    {e.warnings?.map((w, i) => <div key={i} style={{ fontSize: '12px', color: '#f87171', marginTop: '4px' }}>• {w}</div>)}
                  </div>
                ))
              )}
            </div>
          )}

          {adminTab === 'incidents' && (
            <div style={styles.card}>
              <div style={styles.cardTitle}>⚠️ Incident Reports</div>
              {incidents.length === 0 ? (
                <div style={{ textAlign: 'center', color: colors.textDim, padding: '20px' }}>No incidents reported</div>
              ) : (
                incidents.map(inc => (
                  <div key={inc.id} style={{ ...styles.listItem, borderLeft: `3px solid ${inc.severity === 'high' ? colors.danger : inc.severity === 'medium' ? colors.warning : colors.info}` }}>
                    <div style={styles.flexBetween}>
                      <div style={{ fontWeight: '600' }}>{inc.type}</div>
                      <span style={{ ...styles.statusBadge, background: inc.severity === 'high' ? 'rgba(220,38,38,0.2)' : inc.severity === 'medium' ? 'rgba(217,119,6,0.2)' : 'rgba(3,105,161,0.2)', color: inc.severity === 'high' ? '#f87171' : inc.severity === 'medium' ? '#fbbf24' : '#60a5fa' }}>
                        {inc.severity.toUpperCase()}
                      </span>
                    </div>
                    <div style={{ fontSize: '13px', color: colors.textMuted, marginTop: '4px' }}>{inc.client} • {formatDate(inc.date)}</div>
                    <div style={{ fontSize: '13px', color: colors.textDim, marginTop: '6px' }}>{inc.description}</div>
                    <div style={{ fontSize: '12px', color: colors.textDim, marginTop: '6px' }}>Reported by: {inc.reportedBy}</div>
                  </div>
                ))
              )}
            </div>
          )}

          <button style={{ ...styles.btn, ...styles.btnSecondary, marginTop: '16px' }} onClick={handleLogout}>🚪 Sign Out</button>
        </main>

        <nav style={styles.nav}>
          <button style={{ ...styles.navBtn, ...styles.navActive }}><span style={{ fontSize: '22px' }}>📊</span>Admin</button>
          <button style={styles.navBtn} onClick={handleLogout}><span style={{ fontSize: '22px' }}>🚪</span>Logout</button>
        </nav>
      </div>
    );
  }

  // CLIENT PORTAL
  if (view === 'client') {
    const clientData = clients.find(c => c.id === user?.clientId);
    const clientEntries = entries.filter(e => e.clientId === clientData?.id);

    return (
      <div style={styles.container}>
        <header style={styles.header}>
          <div style={styles.logo}>💚 Essential Care</div>
          <span style={styles.badge}>Client Portal</span>
        </header>

        <main style={styles.main}>
          <div style={styles.card}>
            <div style={{ fontSize: '14px', color: colors.textDim }}>Welcome back,</div>
            <div style={{ fontSize: '24px', fontWeight: '700', marginTop: '4px' }}>{clientData?.name}</div>
            <div style={{ fontSize: '14px', color: colors.textMuted, marginTop: '8px' }}>📍 {clientData?.address}</div>
          </div>

          <div style={styles.card}>
            <div style={styles.cardTitle}>📋 Care Visits</div>
            {clientEntries.length === 0 ? (
              <div style={{ textAlign: 'center', color: colors.textDim, padding: '20px' }}>No visits yet</div>
            ) : (
              clientEntries.map(e => (
                <div key={e.id} style={styles.listItem}>
                  <div style={styles.flexBetween}>
                    <div><div style={{ fontWeight: '600' }}>{e.caregiver}</div><div style={{ fontSize: '12px', color: colors.textDim }}>{formatFullDate(e.clockIn)}</div></div>
                    <div style={{ textAlign: 'right' }}><div style={{ color: colors.primaryLight, fontWeight: '600' }}>{e.hours} hrs</div><div style={{ fontSize: '11px', color: colors.textDim }}>{formatTime(e.clockIn)} - {formatTime(e.clockOut)}</div></div>
                  </div>
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: '6px', marginTop: '10px' }}>
                    {e.procedures?.filter(p => p.done).map((p, i) => (
                      <span key={i} style={{ padding: '4px 10px', background: 'rgba(16,185,129,0.15)', borderRadius: '20px', fontSize: '11px', color: colors.primaryLight }}>✓ {p.name}</span>
                    ))}
                  </div>
                  {e.notes && (
                    <div style={{ marginTop: '10px', padding: '10px', background: colors.cardLight, borderRadius: '8px', fontSize: '13px' }}>
                      <div style={{ fontSize: '11px', color: colors.textDim, marginBottom: '4px' }}>Notes:</div>
                      {e.notes}
                    </div>
                  )}
                  <div style={{ marginTop: '8px', fontSize: '11px', color: colors.textDim }}>📍 GPS Verified</div>
                </div>
              ))
            )}
          </div>

          <div style={styles.card}>
            <div style={styles.cardTitle}>📝 Your Care Plan</div>
            {clientData?.procedures?.map((p, i) => (
              <div key={i} style={styles.listItem}>• {p}</div>
            ))}
          </div>

          <div style={styles.card}>
            <div style={styles.cardTitle}>🆘 Emergency Contact</div>
            <div style={{ padding: '14px', background: 'rgba(220,38,38,0.1)', borderRadius: '10px', color: '#fca5a5' }}>
              {clientData?.emergency}
            </div>
          </div>

          <button style={{ ...styles.btn, ...styles.btnSecondary }} onClick={handleLogout}>🚪 Sign Out</button>
        </main>

        <nav style={styles.nav}>
          <button style={{ ...styles.navBtn, ...styles.navActive }}><span style={{ fontSize: '22px' }}>🏠</span>Home</button>
          <button style={styles.navBtn} onClick={handleLogout}><span style={{ fontSize: '22px' }}>🚪</span>Logout</button>
        </nav>
      </div>
    );
  }

  return null;
};

export default EssentialCareApp;
