// portal-app.jsx — Main app: Login, navigation, Home, Perfil, Operator mode
const { useState, useMemo } = React;

// ── Lookup helpers ─────────────────────────────────────────────────────────────
function findPatient(query) {
  const q = query.trim().toLowerCase();
  return (window.PATIENTS || []).find(p =>
    p.dni.replace(/-/g,'').includes(q.replace(/-/g,'')) ||
    p.whatsapp.replace(/[^0-9]/g,'').includes(q.replace(/[^0-9]/g,'')) ||
    p.nombre.toLowerCase().includes(q)
  );
}

// ── LoginScreen ───────────────────────────────────────────────────────────────
function LoginScreen({ onLogin, onOperatorMode }) {
  const C = window.C;
  const [query, setQuery]     = useState('');
  const [error, setError]     = useState('');
  const [loading, setLoading] = useState(false);

  const handleSearch = () => {
    if (!query.trim()) return;
    setLoading(true); setError('');
    setTimeout(() => {
      const patient = findPatient(query);
      setLoading(false);
      if (patient) { onLogin(patient); }
      else { setError('No encontramos ningún socio con ese DNI o número. ¿Estás inscrito en Club Santos?'); }
    }, 600);
  };

  return (
    <div style={{ minHeight: '100vh', background: C.bg, display: 'flex', flexDirection: 'column' }}>
      {/* Header */}
      <div style={{ background: C.primary, padding: '48px 28px 56px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 0, marginBottom: 6 }}>
          <span style={{ fontSize: 32, fontWeight: 900, color: '#fff', letterSpacing: -1 }}>S</span>
          <span style={{ width: 26, height: 26, borderRadius: '50%', background: C.secondary, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: 16, fontWeight: 900, color: '#fff', margin: '0 1px' }}>o</span>
          <span style={{ fontSize: 32, fontWeight: 900, color: '#fff', letterSpacing: -1 }}>s</span>
        </div>
        <div style={{ fontSize: 11, fontWeight: 700, color: 'rgba(255,255,255,.45)', letterSpacing: 3, textTransform: 'uppercase', marginBottom: 20 }}>Club Santos</div>
        <div style={{ fontSize: 26, fontWeight: 800, color: '#fff', lineHeight: 1.2, marginBottom: 8 }}>Tu salud,<br />en tus manos</div>
        <div style={{ fontSize: 13, color: 'rgba(255,255,255,.65)', lineHeight: 1.6 }}>Monitorea tus vitales, sigue tus programas de canje y lleva el control de tus medicamentos.</div>
      </div>

      {/* Card */}
      <div style={{ flex: 1, background: C.surface, borderRadius: '24px 24px 0 0', marginTop: -20, padding: '32px 24px 40px' }}>
        <div style={{ fontSize: 15, fontWeight: 800, color: C.text1, marginBottom: 4 }}>Buscar mi cuenta</div>
        <div style={{ fontSize: 13, color: C.text3, marginBottom: 20 }}>Ingresa tu DNI, WhatsApp o número de tarjeta Club Santos</div>

        <div style={{ display: 'flex', gap: 8, marginBottom: 12 }}>
          <input
            value={query} onChange={e => { setQuery(e.target.value); setError(''); }}
            onKeyDown={e => e.key === 'Enter' && handleSearch()}
            placeholder="0801-XXXX-XXXXX o +504 XXXX XXXX"
            style={{ flex: 1, padding: '12px 16px', borderRadius: 12, border: `1.5px solid ${error ? C.danger : C.border}`, fontFamily: 'inherit', fontSize: 14, color: C.text1, background: C.bg, outline: 'none' }}
          />
          <button onClick={handleSearch} disabled={loading} style={{ padding: '12px 18px', borderRadius: 12, border: 'none', background: C.primary, color: '#fff', fontWeight: 700, fontSize: 14, cursor: 'pointer', flexShrink: 0 }}>
            {loading ? '...' : '→'}
          </button>
        </div>

        {error && <div style={{ fontSize: 12, color: C.danger, marginBottom: 16, lineHeight: 1.5 }}>{error}</div>}

        <div style={{ fontSize: 12, color: C.text3, marginBottom: 24 }}>
          Cuentas demo: <strong style={{ color: C.primary, cursor: 'pointer' }} onClick={() => { setQuery('0801-1972-04521'); }}>María García</strong> · <strong style={{ color: C.primary, cursor: 'pointer' }} onClick={() => setQuery('0801-1979-07765')}>Carlos Ortiz</strong> · <strong style={{ color: C.primary, cursor: 'pointer' }} onClick={() => setQuery('0804-1963-08834')}>Juan Hernández</strong>
        </div>

        <div style={{ borderTop: `1px solid ${C.border}`, paddingTop: 20, display: 'flex', gap: 10 }}>
          <button onClick={() => window.open('https://wa.me/50488252386', '_blank')} style={{ flex: 1, padding: '11px', borderRadius: 12, border: `1.5px solid ${C.border}`, background: C.surface, color: C.text2, fontWeight: 700, fontSize: 12, cursor: 'pointer' }}>
            ✆ Inscribirme
          </button>
          <button onClick={onOperatorMode} style={{ flex: 1, padding: '11px', borderRadius: 12, border: `1.5px solid ${C.primaryLight}`, background: C.primarySurface, color: C.primary, fontWeight: 700, fontSize: 12, cursor: 'pointer' }}>
            * Modo operador
          </button>
        </div>
      </div>
    </div>
  );
}

// ── HomeTab ───────────────────────────────────────────────────────────────────
function HomeTab({ patient, enrollments, onTabChange }) {
  const C = window.C;
  const myEnr     = enrollments.filter(e => e.customerId === patient.id);
  const readyCanjes = myEnr.filter(e => e.rewardsPending > 0);
  const inProgress  = myEnr.filter(e => e.rewardsPending === 0 && (e.purchasesLogged + e.purchasesPending) > 0);
  const tierGoals = { BRONCE: 5000, PLATA: 15000, ORO: 40000, JADE: 99999, PLATINO: 99999 };
  const goal = tierGoals[patient.tier] || 15000;
  const tierCol = C.tiers[patient.tier];

  return (
    <div style={{ padding: '16px 16px 100px' }}>
      {/* Welcome card */}
      <div style={{ background: C.primary, borderRadius: 20, padding: '20px 20px', marginBottom: 16, position: 'relative', overflow: 'hidden' }}>
        <div style={{ position: 'absolute', top: -30, right: -30, width: 120, height: 120, borderRadius: '50%', background: 'rgba(255,255,255,.05)' }} />
        <div style={{ fontSize: 12, color: 'rgba(255,255,255,.6)', marginBottom: 4 }}>Bienvenida de nuevo</div>
        <div style={{ fontSize: 20, fontWeight: 800, color: '#fff', marginBottom: 8 }}>{patient.nombre.split(' ')[0]} {patient.nombre.split(' ')[1]}</div>
        <window.TierBadge tier={patient.tier} size="sm" />
        <div style={{ marginTop: 14, borderTop: '1px solid rgba(255,255,255,.15)', paddingTop: 14, display: 'flex', gap: 20 }}>
          <div>
            <div style={{ fontSize: 22, fontWeight: 900, color: '#fff' }}>{patient.puntos.toLocaleString()}</div>
            <div style={{ fontSize: 10, color: 'rgba(255,255,255,.55)' }}>puntos</div>
          </div>
          <div>
            <div style={{ fontSize: 22, fontWeight: 900, color: '#fff' }}>L. {patient.gastoAnual.toLocaleString()}</div>
            <div style={{ fontSize: 10, color: 'rgba(255,255,255,.55)' }}>gasto anual</div>
          </div>
          <div>
            <div style={{ fontSize: 22, fontWeight: 900, color: '#fff' }}>{patient.transacciones}</div>
            <div style={{ fontSize: 10, color: 'rgba(255,255,255,.55)' }}>compras</div>
          </div>
        </div>
      </div>

      {/* Tier progress */}
      <div style={{ background: C.surface, border: `1px solid ${C.border}`, borderRadius: 16, padding: 16, marginBottom: 12 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
          <div style={{ fontSize: 12, fontWeight: 700, color: C.text2 }}>Progreso de nivel</div>
          <div style={{ fontSize: 11, color: C.text3 }}>L. {Math.max(goal - patient.gastoAnual, 0).toLocaleString()} para el siguiente</div>
        </div>
        <window.ProgressBar value={patient.gastoAnual} max={goal} color={tierCol?.border || C.secondary} height={8} />
      </div>

      {/* Canje summary */}
      {readyCanjes.length > 0 && (
        <button onClick={() => onTabChange('canjes')} style={{ width: '100%', background: C.success, border: 'none', borderRadius: 16, padding: '16px 18px', marginBottom: 12, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 12, textAlign: 'left' }}>
          <span style={{ fontSize: 28 }}>✦</span>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 15, fontWeight: 800, color: '#fff' }}>{readyCanjes.length === 1 ? '¡1 canje listo!' : `¡${readyCanjes.length} canjes listos!`}</div>
            <div style={{ fontSize: 12, color: 'rgba(255,255,255,.8)' }}>Toca para ver y recoger en farmacia</div>
          </div>
          <span style={{ fontSize: 22, color: '#fff', opacity: .7 }}>›</span>
        </button>
      )}

      {inProgress.length > 0 && (
        <button onClick={() => onTabChange('canjes')} style={{ width: '100%', background: C.primarySurface, border: `1px solid ${C.primaryLight}`, borderRadius: 16, padding: '14px 16px', marginBottom: 12, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 12, textAlign: 'left' }}>
          <span style={{ fontSize: 24 }}>Rx</span>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 14, fontWeight: 700, color: C.primary }}>{inProgress.length} programa{inProgress.length > 1 ? 's' : ''} en progreso</div>
            <div style={{ fontSize: 12, color: C.primaryMid }}>Registra tus próximas compras</div>
          </div>
          <span style={{ fontSize: 22, color: C.primaryLight }}>›</span>
        </button>
      )}

      {/* Quick links */}
      <window.SectionLabel>ACCESOS RÁPIDOS</window.SectionLabel>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
        {[
          { icon: 'Rx', label: 'Mis canjes', sub: `${myEnr.length} programas`, tab: 'canjes', color: C.primary },
          { icon: '▦', label: 'Mis vitales', sub: 'Glucose, presión…', tab: 'vitales', color: '#E8743A' },
          { icon: '●', label: 'Mi perfil', sub: 'Datos y medicación', tab: 'perfil', color: C.info },
          { icon: '✆', label: 'WhatsApp', sub: 'Farmacia Santos', tab: 'wa', color: '#25D366' },
        ].map(item => (
          <button key={item.tab} onClick={() => item.tab === 'wa' ? window.open('https://wa.me/50488252386','_blank') : onTabChange(item.tab)}
            style={{ background: C.surface, border: `1.5px solid ${C.border}`, borderRadius: 16, padding: 16, cursor: 'pointer', textAlign: 'left', display: 'flex', flexDirection: 'column', gap: 6 }}>
            <span style={{ fontSize: 24 }}>{item.icon}</span>
            <div style={{ fontSize: 13, fontWeight: 700, color: item.color }}>{item.label}</div>
            <div style={{ fontSize: 11, color: C.text3 }}>{item.sub}</div>
          </button>
        ))}
      </div>

      {/* Contact */}
      <div style={{ marginTop: 20, background: C.surfaceWarm, border: `1px solid ${C.border}`, borderRadius: 14, padding: '12px 14px', display: 'flex', alignItems: 'center', gap: 10 }}>
        <span style={{ fontSize: 16 }}>◆</span>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 12, fontWeight: 700, color: C.text1 }}>Farmacia Santos, Copán Ruinas</div>
          <div style={{ fontSize: 11, color: C.text3 }}>Calle La Independencia · 8am–8pm diario</div>
        </div>
        <a href="tel:+50488252386" style={{ fontSize: 11, fontWeight: 700, color: C.primary, textDecoration: 'none' }}>Llamar</a>
      </div>
    </div>
  );
}

// ── PerfilTab ─────────────────────────────────────────────────────────────────
function PerfilTab({ patient, onLogout }) {
  const C = window.C;
  return (
    <div style={{ padding: '16px 16px 100px' }}>
      {/* Profile header */}
      <div style={{ display: 'flex', gap: 14, alignItems: 'center', marginBottom: 20 }}>
        <div style={{ width: 60, height: 60, borderRadius: '50%', background: C.primaryLight, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 20, fontWeight: 900, color: C.primary }}>
          {patient.iniciales}
        </div>
        <div>
          <div style={{ fontSize: 18, fontWeight: 800, color: C.text1, marginBottom: 4 }}>{patient.nombre}</div>
          <window.TierBadge tier={patient.tier} size="sm" />
        </div>
      </div>

      <window.SectionLabel>DATOS PERSONALES</window.SectionLabel>
      <div style={{ background: C.surface, border: `1px solid ${C.border}`, borderRadius: 16, overflow: 'hidden', marginBottom: 16 }}>
        {[
          { label: 'DNI / Cédula', value: patient.dni },
          { label: 'WhatsApp', value: patient.whatsapp },
          { label: 'Email', value: patient.email },
          { label: 'Edad', value: `${patient.edad} años` },
          { label: 'Dirección', value: patient.direccion },
          { label: 'Sucursal preferida', value: patient.sucursal.split('—')[0].trim() },
        ].map((f, i, arr) => (
          <div key={f.label} style={{ display: 'flex', justifyContent: 'space-between', padding: '13px 16px', borderBottom: i < arr.length - 1 ? `1px solid ${C.border}` : 'none', gap: 12 }}>
            <div style={{ fontSize: 12, fontWeight: 600, color: C.text3 }}>{f.label}</div>
            <div style={{ fontSize: 13, fontWeight: 500, color: C.text1, textAlign: 'right' }}>{f.value}</div>
          </div>
        ))}
      </div>

      {(patient.condiciones?.length > 0 || patient.alergias?.length > 0) && (
        <>
          <window.SectionLabel>HISTORIAL CLÍNICO</window.SectionLabel>
          <div style={{ background: C.surface, border: `1px solid ${C.border}`, borderRadius: 16, padding: 16, marginBottom: 16 }}>
            {patient.condiciones?.length > 0 && (
              <div style={{ marginBottom: 12 }}>
                <div style={{ fontSize: 12, fontWeight: 700, color: C.text3, marginBottom: 8 }}>CONDICIONES CRÓNICAS</div>
                <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                  {patient.condiciones.map((c, i) => (
                    <span key={i} style={{ fontSize: 11, fontWeight: 600, background: C.primarySurface, color: C.primary, border: `1px solid ${C.primaryLight}`, borderRadius: 9999, padding: '3px 10px' }}>{c}</span>
                  ))}
                </div>
              </div>
            )}
            {patient.alergias?.length > 0 && (
              <div>
                <div style={{ fontSize: 12, fontWeight: 700, color: C.text3, marginBottom: 8 }}>! ALERGIAS</div>
                <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                  {patient.alergias.map((a, i) => (
                    <span key={i} style={{ fontSize: 11, fontWeight: 600, background: C.dangerLight, color: C.danger, border: `1px solid ${C.danger}30`, borderRadius: 9999, padding: '3px 10px' }}>{a}</span>
                  ))}
                </div>
              </div>
            )}
            {patient.doctor && <div style={{ fontSize: 12, color: C.text3, marginTop: 12 }}>Médico tratante: <strong style={{ color: C.text1 }}>{patient.doctor}</strong></div>}
            {patient.seguro && <div style={{ fontSize: 12, color: C.text3, marginTop: 4 }}>Seguro médico: <strong style={{ color: C.text1 }}>{patient.seguro}</strong></div>}
          </div>
        </>
      )}

      <button onClick={onLogout} style={{ width: '100%', padding: 13, borderRadius: 14, border: `1.5px solid ${C.border}`, background: C.surface, color: C.text2, fontWeight: 700, fontSize: 13, cursor: 'pointer' }}>
        Cerrar sesión
      </button>
    </div>
  );
}

// ── OperatorLogin ─────────────────────────────────────────────────────────────
function OperatorLogin({ onAccess, onBack }) {
  const C = window.C;
  const [pin, setPin] = useState('');
  const [err, setErr] = useState(false);
  const check = () => { if (pin === '1234' || pin === 'santos') { onAccess(); } else { setErr(true); setTimeout(() => setErr(false), 1400); } };
  return (
    <div style={{ minHeight: '100vh', background: C.bg, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: 24 }}>
      <div style={{ width: '100%', maxWidth: 360 }}>
        <div style={{ textAlign: 'center', marginBottom: 32 }}>
          <div style={{ fontSize: 36, marginBottom: 8 }}>*</div>
          <div style={{ fontSize: 20, fontWeight: 800, color: C.text1 }}>Modo Operador</div>
          <div style={{ fontSize: 13, color: C.text3, marginTop: 6 }}>Ingresa la contraseña de farmacia</div>
        </div>
        <input type="password" value={pin} onChange={e => setPin(e.target.value)} onKeyDown={e => e.key === 'Enter' && check()}
          placeholder="Contraseña" style={{ width: '100%', padding: '14px 18px', borderRadius: 14, border: `2px solid ${err ? C.danger : C.border}`, fontFamily: 'inherit', fontSize: 18, textAlign: 'center', letterSpacing: 4, marginBottom: 12, background: C.surface, color: C.text1, outline: 'none', transition: 'border-color .2s' }} />
        {err && <div style={{ fontSize: 12, color: C.danger, textAlign: 'center', marginBottom: 10 }}>Contraseña incorrecta. Usa: 1234</div>}
        <button onClick={check} style={{ width: '100%', padding: 14, borderRadius: 14, border: 'none', background: C.primary, color: '#fff', fontWeight: 700, fontSize: 15, cursor: 'pointer', marginBottom: 12 }}>Entrar</button>
        <button onClick={onBack} style={{ width: '100%', padding: 14, borderRadius: 14, border: `1.5px solid ${C.border}`, background: C.surface, color: C.text2, fontWeight: 700, fontSize: 14, cursor: 'pointer' }}>← Volver</button>
        <div style={{ fontSize: 12, color: C.text3, textAlign: 'center', marginTop: 12 }}>Demo PIN: 1234</div>
      </div>
    </div>
  );
}

// ── App ────────────────────────────────────────────────────────────────────────
function App() {
  const C = window.C;
  const { CanjesTab, OperatorQueue, VitalesTab } = window;
  const [patient,     setPatient]     = useState(null);
  const [tab,         setTab]         = useState('home');
  const [enrollments, setEnrollments] = useState(window.INITIAL_ENROLLMENTS || []);
  const [submissions, setSubmissions] = useState(window.INITIAL_SUBMISSIONS || []);
  const [vitals,      setVitals]      = useState(window.VITALS_DATA || {});
  const [mode,        setMode]        = useState('patient'); // 'patient' | 'operator-login' | 'operator'

  // ── Canje actions ───────────────────────────────────────────────────────────
  const handleAddEnrollment = (customerId, prog) => {
    const newEnr = { id: `e-${Date.now()}`, customerId, programId: prog.id, purchasesLogged: 0, purchasesPending: 0, rewardsEarned: 0, rewardsPending: 0, sinceDate: new Date().toISOString().split('T')[0] };
    setEnrollments(prev => [...prev, newEnr]);
  };

  const handleRegisterPurchase = (enrollmentId, date) => {
    const enr = enrollments.find(e => e.id === enrollmentId);
    if (!enr) return;
    const prog = (window.LAB_PROGRAMS || []).find(p => p.id === enr.programId);
    const newSub = { id: `s-${Date.now()}`, enrollmentId, customerId: enr.customerId, programId: enr.programId, labId: prog?.labId || '', date, submittedToPortal: false };
    setSubmissions(prev => [...prev, newSub]);
    setEnrollments(prev => prev.map(e => e.id === enrollmentId ? { ...e, purchasesPending: e.purchasesPending + 1 } : e));
  };

  const handleMarkSubmitted = (subId) => {
    const sub = submissions.find(s => s.id === subId);
    if (!sub) return;
    const prog = (window.LAB_PROGRAMS || []).find(p => p.id === sub.programId);
    setSubmissions(prev => prev.map(s => s.id === subId ? { ...s, submittedToPortal: true } : s));
    setEnrollments(prev => prev.map(e => {
      if (e.id !== sub.enrollmentId) return e;
      const newLogged  = e.purchasesLogged + 1;
      const newPending = Math.max(e.purchasesPending - 1, 0);
      const thresholdHit = prog && newLogged >= prog.buyQty;
      return {
        ...e,
        purchasesLogged: thresholdHit ? 0 : newLogged,
        purchasesPending: newPending,
        rewardsEarned:  e.rewardsEarned + (thresholdHit ? 1 : 0),
        rewardsPending: e.rewardsPending + (thresholdHit ? 1 : 0),
      };
    }));
  };

  const handleLogVital = (patientId, key, entry) => {
    setVitals(prev => ({
      ...prev,
      [patientId]: { ...prev[patientId], [key]: [...(prev[patientId]?.[key] || []), entry] },
    }));
  };

  const pendingCount = submissions.filter(s => !s.submittedToPortal).length;

  // ── Operator mode ───────────────────────────────────────────────────────────
  if (mode === 'operator-login') {
    return <OperatorLogin onAccess={() => setMode('operator')} onBack={() => setMode('patient')} />;
  }

  if (mode === 'operator') {
    return (
      <div style={{ minHeight: '100vh', background: C.bg, maxWidth: 430, margin: '0 auto', display: 'flex', flexDirection: 'column' }}>
        {/* Operator header */}
        <div style={{ background: C.primaryDark, padding: '16px 18px 20px' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <div>
              <div style={{ fontSize: 10, fontWeight: 700, color: 'rgba(255,255,255,.5)', letterSpacing: 2, textTransform: 'uppercase', marginBottom: 2 }}>Modo Operador</div>
              <div style={{ fontSize: 18, fontWeight: 800, color: '#fff' }}>Lista de Registro — Portales</div>
            </div>
            <button onClick={() => setMode('patient')} style={{ background: 'rgba(255,255,255,.1)', border: 'none', color: '#fff', borderRadius: 10, padding: '7px 12px', fontSize: 12, fontWeight: 700, cursor: 'pointer' }}>Salir</button>
          </div>
          <div style={{ fontSize: 12, color: 'rgba(255,255,255,.55)', marginTop: 6 }}>
            {pendingCount} envío{pendingCount !== 1 ? 's' : ''} pendiente{pendingCount !== 1 ? 's' : ''} — Copán Ruinas · {new Date().toLocaleDateString('es-HN', { weekday: 'long', day: 'numeric', month: 'long' })}
          </div>
        </div>
        <div style={{ flex: 1, overflowY: 'auto' }}>
          <OperatorQueue submissions={submissions} enrollments={enrollments} onMarkSubmitted={handleMarkSubmitted} />
        </div>
      </div>
    );
  }

  // ── Patient not logged in ───────────────────────────────────────────────────
  if (!patient) {
    return <LoginScreen onLogin={(p) => { setPatient(p); setTab('home'); }} onOperatorMode={() => setMode('operator-login')} />;
  }

  // ── Patient portal ──────────────────────────────────────────────────────────
  const NAV = [
    { id: 'home',    icon: '⌂', label: 'Inicio' },
    { id: 'canjes',  icon: '✦', label: 'Canjes' },
    { id: 'vitales', icon: '▦', label: 'Vitales' },
    { id: 'perfil',  icon: '●', label: 'Perfil' },
  ];

  const myEnr       = enrollments.filter(e => e.customerId === patient.id);
  const readyCount  = myEnr.filter(e => e.rewardsPending > 0).length;

  return (
    <div style={{ minHeight: '100vh', background: C.bg, maxWidth: 430, margin: '0 auto', display: 'flex', flexDirection: 'column', position: 'relative' }}>
      {/* Brand header */}
      <div style={{ background: C.primary, padding: '14px 18px 22px', display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{ flex: 1 }}>
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <span style={{ fontSize: 18, fontWeight: 900, color: '#fff', letterSpacing: -0.5 }}>S</span>
            <span style={{ width: 16, height: 16, borderRadius: '50%', background: C.secondary, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: 10, fontWeight: 900, color: '#fff', margin: '0 1px' }}>o</span>
            <span style={{ fontSize: 18, fontWeight: 900, color: '#fff', letterSpacing: -0.5 }}>s</span>
          </div>
          <div style={{ fontSize: 8, fontWeight: 700, color: 'rgba(255,255,255,.4)', letterSpacing: 2.5, textTransform: 'uppercase' }}>Club Santos</div>
        </div>
        <div style={{ textAlign: 'right' }}>
          <div style={{ fontSize: 13, fontWeight: 700, color: '#fff' }}>{patient.nombre.split(' ')[0]}</div>
          <div style={{ fontSize: 10, color: 'rgba(255,255,255,.55)' }}>{patient.sucursal.split('—')[0].trim()}</div>
        </div>
        <div style={{ width: 36, height: 36, borderRadius: '50%', background: C.secondary, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12, fontWeight: 900, color: '#fff' }}>
          {patient.iniciales}
        </div>
      </div>

      {/* Content */}
      <div style={{ flex: 1, overflowY: 'auto', borderRadius: '20px 20px 0 0', background: C.bg, marginTop: -8 }}>
        {tab === 'home'    && <HomeTab    patient={patient} enrollments={enrollments} onTabChange={setTab} />}
        {tab === 'canjes'  && <CanjesTab  patient={patient} enrollments={enrollments} onAddEnrollment={handleAddEnrollment} onRegisterPurchase={handleRegisterPurchase} />}
        {tab === 'vitales' && <VitalesTab patient={patient} vitals={vitals} onLogVital={handleLogVital} />}
        {tab === 'perfil'  && <PerfilTab  patient={patient} onLogout={() => { setPatient(null); setTab('home'); }} />}
      </div>

      {/* Bottom nav */}
      <div style={{ position: 'sticky', bottom: 0, background: C.surface, borderTop: `1px solid ${C.border}`, display: 'flex', padding: '8px 0 20px', boxShadow: '0 -4px 16px rgba(8,54,47,.07)' }}>
        {NAV.map(n => {
          const active = tab === n.id;
          const badge  = n.id === 'canjes' && readyCount > 0;
          return (
            <button key={n.id} onClick={() => setTab(n.id)} style={{ flex: 1, border: 'none', background: 'none', cursor: 'pointer', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3, padding: '6px 0', position: 'relative' }}>
              <span style={{ fontSize: 22 }}>{n.icon}</span>
              {badge && (
                <span style={{ position: 'absolute', top: 2, right: '50%', transform: 'translateX(8px)', width: 14, height: 14, background: C.danger, borderRadius: '50%', fontSize: 8, fontWeight: 900, color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', border: `2px solid ${C.surface}` }}>
                  {readyCount}
                </span>
              )}
              <span style={{ fontSize: 10, fontWeight: active ? 700 : 500, color: active ? C.primary : C.text3 }}>{n.label}</span>
              {active && <span style={{ position: 'absolute', bottom: 0, width: 24, height: 3, background: C.primary, borderRadius: 9999 }} />}
            </button>
          );
        })}
      </div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
