// portal-vitales.jsx — Health vitals tracker
const { useState } = React;

const VITAL_CONFIGS = {
  glucose: {
    label: 'Glucosa', unit: 'mg/dL', icon: '●',
    targetMin: 70, targetMax: 130,
    targetLabel: 'Meta: 70–130 mg/dL',
    color: '#E8743A',
    getValue: d => d.value,
    getDisplay: d => `${d.value}`,
  },
  bloodPressure: {
    label: 'Presión arterial', unit: 'mmHg', icon: '♥',
    targetMin: 110, targetMax: 130,
    targetLabel: 'Meta sistólica: <130 mmHg',
    color: '#DC2626',
    getValue: d => d.sys,
    getDisplay: d => `${d.sys}/${d.dia}`,
  },
  uricAcid: {
    label: 'Ácido úrico', unit: 'mg/dL', icon: '●',
    targetMin: 2.5, targetMax: 6.0,
    targetLabel: 'Meta: <6.0 mg/dL',
    color: '#7C3AED',
    getValue: d => d.value,
    getDisplay: d => `${d.value}`,
  },
  weight: {
    label: 'Peso corporal', unit: 'kg', icon: '●',
    targetMin: null, targetMax: null,
    targetLabel: null,
    color: '#059669',
    getValue: d => d.value,
    getDisplay: d => `${d.value}`,
  },
};

function LogModal({ vitalKey, config, onSave, onClose }) {
  const C = window.C;
  const [val, setVal] = useState('');
  const [val2, setVal2] = useState('');
  const [date, setDate] = useState(new Date().toISOString().split('T')[0]);
  const isBP = vitalKey === 'bloodPressure';

  const handleSave = () => {
    if (!val) return;
    const entry = { date };
    if (isBP) { entry.sys = parseFloat(val); entry.dia = parseFloat(val2 || 0); }
    else       { entry.value = parseFloat(val); }
    onSave(vitalKey, entry);
    onClose();
  };

  return (
    <window.Modal visible={true} onClose={onClose} title={`Registrar ${config.label}`}>
      <div style={{ marginBottom: 14 }}>
        <div style={{ fontSize: 12, fontWeight: 600, color: C.text2, marginBottom: 6 }}>Fecha</div>
        <input type="date" value={date} onChange={e => setDate(e.target.value)} style={{ width: '100%', padding: '10px 14px', borderRadius: 10, border: `1.5px solid ${C.border}`, fontFamily: 'inherit', fontSize: 14, color: C.text1, background: C.bg }} />
      </div>
      {isBP ? (
        <div style={{ display: 'flex', gap: 10, marginBottom: 14 }}>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 12, fontWeight: 600, color: C.text2, marginBottom: 6 }}>Sistólica (mmHg)</div>
            <input type="number" value={val} onChange={e => setVal(e.target.value)} placeholder="120" style={{ width: '100%', padding: '10px 14px', borderRadius: 10, border: `1.5px solid ${C.border}`, fontFamily: 'inherit', fontSize: 16, color: C.text1, background: C.bg }} />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 12, fontWeight: 600, color: C.text2, marginBottom: 6 }}>Diastólica (mmHg)</div>
            <input type="number" value={val2} onChange={e => setVal2(e.target.value)} placeholder="80" style={{ width: '100%', padding: '10px 14px', borderRadius: 10, border: `1.5px solid ${C.border}`, fontFamily: 'inherit', fontSize: 16, color: C.text1, background: C.bg }} />
          </div>
        </div>
      ) : (
        <div style={{ marginBottom: 14 }}>
          <div style={{ fontSize: 12, fontWeight: 600, color: C.text2, marginBottom: 6 }}>{config.label} ({config.unit})</div>
          <input type="number" value={val} onChange={e => setVal(e.target.value)} placeholder="0.0" step="0.1" style={{ width: '100%', padding: '10px 14px', borderRadius: 10, border: `1.5px solid ${C.border}`, fontFamily: 'inherit', fontSize: 20, fontWeight: 700, color: C.text1, background: C.bg }} />
        </div>
      )}
      {config.targetLabel && (
        <div style={{ fontSize: 11, color: C.info, background: C.infoLight, borderRadius: 8, padding: '6px 10px', marginBottom: 14 }}>{config.targetLabel}</div>
      )}
      <div style={{ display: 'flex', gap: 8 }}>
        <button onClick={onClose} style={{ flex: 1, padding: 11, borderRadius: 12, border: `1.5px solid ${C.border}`, background: C.surface, color: C.text2, fontWeight: 700, fontSize: 13, cursor: 'pointer' }}>Cancelar</button>
        <button onClick={handleSave} disabled={!val} style={{ flex: 2, padding: 11, borderRadius: 12, border: 'none', background: val ? C.primary : C.border, color: '#fff', fontWeight: 700, fontSize: 13, cursor: val ? 'pointer' : 'default' }}>✓ Guardar lectura</button>
      </div>
    </window.Modal>
  );
}

function VitalCard({ vitalKey, config, data, onLog }) {
  const C = window.C;
  const sorted = [...(data || [])].sort((a, b) => a.date > b.date ? 1 : -1);
  const latest = sorted[sorted.length - 1];
  const latestVal = latest ? config.getValue(latest) : null;
  const inTarget = latestVal && config.targetMin && config.targetMax ? (latestVal >= config.targetMin && latestVal <= config.targetMax) : null;
  const statusColor = inTarget === null ? C.text3 : inTarget ? C.success : C.danger;
  const chartData   = sorted.map(d => ({ ...d, value: config.getValue(d) }));

  return (
    <div style={{ background: C.surface, border: `1px solid ${C.border}`, borderRadius: 16, padding: 16, marginBottom: 12, boxShadow: '0 1px 6px rgba(8,54,47,.05)' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 12 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{ fontSize: 20 }}>{config.icon}</span>
          <div>
            <div style={{ fontSize: 13, fontWeight: 700, color: C.text1 }}>{config.label}</div>
            {config.targetLabel && <div style={{ fontSize: 10, color: C.text3 }}>{config.targetLabel}</div>}
          </div>
        </div>
        <div style={{ textAlign: 'right' }}>
          {latestVal ? (
            <>
              <div style={{ fontSize: 22, fontWeight: 900, color: statusColor, lineHeight: 1 }}>
                {config.getDisplay(latest)}
              </div>
              <div style={{ fontSize: 10, color: C.text3 }}>{config.unit}</div>
            </>
          ) : (
            <div style={{ fontSize: 12, color: C.text3 }}>Sin datos</div>
          )}
        </div>
      </div>

      {/* Status pill */}
      {inTarget !== null && (
        <div style={{ marginBottom: 10 }}>
          <span style={{ fontSize: 10, fontWeight: 800, borderRadius: 9999, padding: '3px 10px', background: inTarget ? C.successLight : C.dangerLight, color: inTarget ? C.success : C.danger, border: `1px solid ${inTarget ? C.success : C.danger}` }}>
            {inTarget ? '✓ En rango objetivo' : '! Fuera de rango objetivo'}
          </span>
        </div>
      )}

      {/* Chart */}
      {sorted.length >= 2 && (
        <div style={{ marginBottom: 12 }}>
          <window.VitalChart data={chartData} color={config.color} unit={config.unit} targetMin={config.targetMin} targetMax={config.targetMax} height={70} />
          <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 4 }}>
            <span style={{ fontSize: 10, color: C.text3 }}>{new Date(sorted[0].date).toLocaleDateString('es-HN', { month: 'short', day: 'numeric' })}</span>
            <span style={{ fontSize: 10, color: C.text3 }}>{new Date(sorted[sorted.length-1].date).toLocaleDateString('es-HN', { month: 'short', day: 'numeric' })}</span>
          </div>
        </div>
      )}

      {/* History */}
      {sorted.length > 0 && (
        <div style={{ borderTop: `1px solid ${C.border}`, paddingTop: 10, marginBottom: 10, maxHeight: 100, overflowY: 'auto' }}>
          {[...sorted].reverse().slice(0, 5).map((d, i) => (
            <div key={i} style={{ display: 'flex', justifyContent: 'space-between', padding: '4px 0', borderBottom: i < Math.min(sorted.length, 5) - 1 ? `1px solid ${C.border}` : 'none' }}>
              <span style={{ fontSize: 11, color: C.text3 }}>{new Date(d.date).toLocaleDateString('es-HN', { day: 'numeric', month: 'short', year: '2-digit' })}</span>
              <span style={{ fontSize: 12, fontWeight: 700, color: C.text1 }}>{config.getDisplay(d)} {config.unit}</span>
            </div>
          ))}
        </div>
      )}

      <button onClick={() => onLog(vitalKey)} style={{ width: '100%', padding: '9px', borderRadius: 10, border: 'none', background: C.primarySurface, color: C.primary, fontSize: 12, fontWeight: 700, cursor: 'pointer' }}>
        + Registrar nueva lectura
      </button>
    </div>
  );
}

function VitalesTab({ patient, vitals, onLogVital }) {
  const C = window.C;
  const [logging, setLogging] = useState(null);
  const myVitals = vitals[patient.id] || {};

  // Which vitals are relevant to their conditions
  const conditions = patient.condiciones || [];
  const hasDiabetes = conditions.some(c => c.toLowerCase().includes('diabet'));
  const hasGout     = conditions.some(c => c.toLowerCase().includes('gota') || c.toLowerCase().includes('uricemi'));
  const showUric    = hasGout || (myVitals.uricAcid || []).length > 0;

  const keys = ['glucose', 'bloodPressure', ...(showUric ? ['uricAcid'] : []), 'weight'];

  return (
    <div style={{ padding: '16px 16px 100px' }}>
      {conditions.length > 0 && (
        <div style={{ background: C.primarySurface, border: `1px solid ${C.primaryLight}`, borderRadius: 12, padding: '10px 14px', marginBottom: 16, display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{ fontSize: 16 }}>✚</span>
          <div style={{ fontSize: 12, color: C.primaryDark, lineHeight: 1.5 }}>
            <strong>Condiciones crónicas:</strong> {conditions.join(' · ')}
          </div>
        </div>
      )}

      {keys.map(key => (
        <VitalCard key={key} vitalKey={key} config={VITAL_CONFIGS[key]} data={myVitals[key]} onLog={(k) => setLogging(k)} />
      ))}

      {logging && (
        <LogModal vitalKey={logging} config={VITAL_CONFIGS[logging]}
          onSave={(key, entry) => { onLogVital(patient.id, key, entry); }}
          onClose={() => setLogging(null)} />
      )}
    </div>
  );
}

Object.assign(window, { VitalesTab });
