// portal-components.jsx — Shared UI primitives
// Exports to window: TierBadge, LabBadge, ProgressBar, SectionLabel, Modal, EmptyState, VitalChart
const { useState, useEffect, useRef } = React;

function TierBadge({ tier, size = 'sm' }) {
  const C = window.C;
  const t = C.tiers[tier] || C.tiers.BRONCE;
  const isLg = size === 'lg';
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 5,
      fontSize: isLg ? 13 : 11, fontWeight: 800, letterSpacing: '.3px',
      borderRadius: 9999, padding: isLg ? '5px 13px' : '3px 10px',
      border: `1.5px solid ${t.border}`,
      background: t.bg, color: t.text,
    }}>
      <span style={{ width: isLg ? 8 : 6, height: isLg ? 8 : 6, borderRadius: '50%', background: t.border, flexShrink: 0 }} />
      {tier}
    </span>
  );
}

function LabBadge({ labId }) {
  const lab = (window.LABS || []).find(l => l.id === labId);
  if (!lab) return null;
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 4,
      fontSize: 10, fontWeight: 700, letterSpacing: '.3px',
      borderRadius: 9999, padding: '2px 9px',
      background: lab.colorLight, color: lab.color,
      border: `1.5px solid ${lab.color}30`,
    }}>
      {lab.name}
    </span>
  );
}

function ProgressBar({ value, max, color, height = 6 }) {
  const pct = Math.min(Math.max((value / Math.max(max, 1)) * 100, 2), 100);
  return (
    <div style={{ height, background: window.C.border, borderRadius: 9999, overflow: 'hidden' }}>
      <div style={{ height: '100%', width: `${pct}%`, background: color, borderRadius: 9999, transition: 'width .4s ease' }} />
    </div>
  );
}

function SectionLabel({ children, style }) {
  return (
    <div style={{ fontSize: 11, fontWeight: 700, color: window.C.text3, letterSpacing: 1, textTransform: 'uppercase', marginBottom: 10, ...style }}>
      {children}
    </div>
  );
}

function EmptyState({ icon, title, sub }) {
  const C = window.C;
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', padding: '40px 20px', gap: 8, textAlign: 'center' }}>
      <span style={{ fontSize: 36 }}>{icon}</span>
      <div style={{ fontSize: 15, fontWeight: 700, color: C.text1 }}>{title}</div>
      {sub && <div style={{ fontSize: 13, color: C.text3, lineHeight: 1.5 }}>{sub}</div>}
    </div>
  );
}

function Modal({ visible, onClose, title, children, height = '90%' }) {
  const C = window.C;
  useEffect(() => {
    document.body.style.overflow = visible ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [visible]);
  if (!visible) return null;
  return (
    <div style={{ position: 'fixed', inset: 0, background: 'rgba(8,54,47,.5)', zIndex: 1000, display: 'flex', alignItems: 'flex-end' }} onClick={onClose}>
      <div style={{ width: '100%', maxWidth: 430, margin: '0 auto', background: C.surface, borderRadius: '20px 20px 0 0', maxHeight: height, overflowY: 'auto', padding: '20px 20px 40px' }} onClick={e => e.stopPropagation()}>
        <div style={{ width: 40, height: 4, borderRadius: 2, background: C.border, margin: '0 auto 16px', flexShrink: 0 }} />
        {title && <div style={{ fontSize: 17, fontWeight: 800, color: C.text1, marginBottom: 16 }}>{title}</div>}
        {children}
      </div>
    </div>
  );
}

// ── VitalChart — SVG sparkline ────────────────────────────────────────────────
function VitalChart({ data, color, unit, targetMin, targetMax, height = 80 }) {
  if (!data || data.length < 2) return <div style={{ height, display: 'flex', alignItems: 'center', justifyContent: 'center', color: window.C.text3, fontSize: 12 }}>Sin suficientes datos</div>;
  const W = 280, H = height;
  const vals = data.map(d => d.value || d.sys || 0);
  const minV = Math.min(...vals) * 0.93;
  const maxV = Math.max(...vals) * 1.07;
  const x = (i) => (i / (data.length - 1)) * (W - 20) + 10;
  const y = (v) => H - 8 - ((v - minV) / (maxV - minV)) * (H - 16);
  const points = vals.map((v, i) => `${x(i)},${y(v)}`).join(' ');
  const area = `M ${x(0)},${H} ` + vals.map((v, i) => `L ${x(i)},${y(v)}`).join(' ') + ` L ${x(vals.length-1)},${H} Z`;
  const last = vals[vals.length - 1];
  const inTarget = targetMin && targetMax ? (last >= targetMin && last <= targetMax) : true;
  return (
    <svg width="100%" viewBox={`0 0 ${W} ${H}`} style={{ overflow: 'visible' }}>
      {targetMin && targetMax && (
        <rect x={10} y={y(targetMax)} width={W-20} height={y(targetMin)-y(targetMax)} fill={color+'14'} rx={3} />
      )}
      <path d={area} fill={color+'18'} />
      <polyline points={points} fill="none" stroke={color} strokeWidth={2} strokeLinejoin="round" strokeLinecap="round" />
      {vals.map((v, i) => (
        <circle key={i} cx={x(i)} cy={y(v)} r={i === vals.length - 1 ? 5 : 3}
          fill={i === vals.length - 1 ? color : window.C.surface}
          stroke={color} strokeWidth={2} />
      ))}
    </svg>
  );
}

Object.assign(window, { TierBadge, LabBadge, ProgressBar, SectionLabel, EmptyState, Modal, VitalChart });
