// Patient mobile — visual system
// More humane, warmer than clinical app. Larger type, more breathing room.
// Coach tone in copy.

const PM = {
  // Warm palette — sand + terracotta accents over teal
  bg: '#faf7f2',           // warm cream
  card: '#ffffff',
  cardSoft: '#f5efe6',     // sand
  border: '#ebe4d6',
  borderStrong: '#d8cdb8',

  // Text
  text: '#1f1d1a',         // warm near-black
  textSoft: '#3d3a35',
  textMute: '#7a746c',
  textFaint: '#a89f93',

  // Brand — teal stays primary, but warmer accents available
  teal:    '#0d9488',
  tealSoft:'#ccfbf1',
  teal50:  '#f0fdfa',
  teal700: '#0f766e',
  teal900: '#134e4a',

  // Warm accents (per-domain or per-state)
  terracotta: '#c2410c',
  terracottaSoft: '#fed7aa',
  amber: '#d97706',
  amberSoft: '#fde68a',
  amber50: '#fffbeb',
  rose: '#be185d',
  roseSoft: '#fbcfe8',
  sage: '#65a30d',
  sageSoft: '#d9f99d',
  sky: '#0369a1',
  skySoft: '#bae6fd',
  plum: '#7c3aed',
  plumSoft: '#ddd6fe',

  // Semantic
  ok:    '#16a34a', okBg:    '#dcfce7', okBorder: '#bbf7d0',
  warn:  '#d97706', warnBg:  '#fef3c7', warnBorder: '#fde68a',
  bad:   '#dc2626', badBg:   '#fee2e2', badBorder: '#fecaca',
  info:  '#2563eb', infoBg:  '#dbeafe', infoBorder: '#bfdbfe',

  // Type
  fontUI:      "'Inter', -apple-system, system-ui, sans-serif",
  fontDisplay: "'Instrument Serif', 'Inter', serif",
  fontMono:    "'JetBrains Mono', 'SF Mono', monospace",
};

// ─────────────────────────────────────────────────────────────
// Shell — warm background + scroll area + top status spacer
// ─────────────────────────────────────────────────────────────
function PMShell({ children, bg, padTop = true, padBottom = true }) {
  return (
    <div style={{
      width: '100%', height: '100%', background: bg || PM.bg,
      display: 'flex', flexDirection: 'column', overflow: 'hidden',
      fontFamily: PM.fontUI, color: PM.text,
    }}>
      {padTop ? <div style={{ height: 62, flexShrink: 0 }}/> : null}
      <div className="lpr-scroll" style={{ flex: 1, overflow: 'auto', paddingBottom: padBottom ? 100 : 24 }}>
        {children}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Header — back chevron, title, optional action
// ─────────────────────────────────────────────────────────────
function PMHeader({ title, subtitle, onBack = true, action, big, eyebrow }) {
  return (
    <div style={{ padding: '12px 20px 4px' }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', minHeight: 32 }}>
        {onBack ? (
          <button style={{
            width: 36, height: 36, borderRadius: 18, border: 'none',
            background: PM.card, display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            boxShadow: '0 1px 3px rgba(0,0,0,0.06)', cursor: 'pointer',
          }}>
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke={PM.textSoft} strokeWidth="2.2" strokeLinecap="round">
              <path d="M9 2L4 7l5 5"/>
            </svg>
          </button>
        ) : <div style={{ width: 36 }}/>}
        {action ? action : <div style={{ width: 36 }}/>}
      </div>
      {eyebrow ? (
        <div style={{ fontSize: 12, color: PM.textMute, marginTop: 8, fontWeight: 500, letterSpacing: 0.3, textTransform: 'uppercase' }}>{eyebrow}</div>
      ) : null}
      {title ? (
        <div style={{
          fontFamily: big ? PM.fontDisplay : PM.fontUI,
          fontSize: big ? 32 : 26, fontWeight: 700, color: PM.text,
          letterSpacing: -0.6, lineHeight: 1.15, marginTop: eyebrow ? 4 : 12,
        }}>{title}</div>
      ) : null}
      {subtitle ? (
        <div style={{ fontSize: 14.5, color: PM.textMute, marginTop: 6, lineHeight: 1.5 }}>{subtitle}</div>
      ) : null}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Card — warm-bordered surface
// ─────────────────────────────────────────────────────────────
function PMCard({ children, style, padding = 16, radius = 18, bg, border, onClick }) {
  return (
    <div onClick={onClick} style={{
      background: bg || PM.card,
      border: border === false ? 'none' : `1px solid ${border || PM.border}`,
      borderRadius: radius, padding, cursor: onClick ? 'pointer' : 'default',
      ...style,
    }}>{children}</div>
  );
}

// ─────────────────────────────────────────────────────────────
// Section title (above a card group)
// ─────────────────────────────────────────────────────────────
function PMSection({ title, action, children, style }) {
  return (
    <div style={{ padding: '20px 20px 8px', ...style }}>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 10 }}>
        <span style={{ fontSize: 13, fontWeight: 600, color: PM.textMute, letterSpacing: 0.3, textTransform: 'uppercase' }}>{title}</span>
        {action}
      </div>
      {children}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Pill — small label
// ─────────────────────────────────────────────────────────────
function PMPill({ children, tone = 'neutral', icon, style }) {
  const map = {
    neutral: { fg: PM.textSoft, bg: PM.cardSoft, br: PM.border },
    teal:    { fg: PM.teal700,  bg: PM.teal50,   br: PM.tealSoft },
    ok:      { fg: PM.ok,       bg: PM.okBg,     br: PM.okBorder },
    warn:    { fg: PM.warn,     bg: PM.warnBg,   br: PM.warnBorder },
    bad:     { fg: PM.bad,      bg: PM.badBg,    br: PM.badBorder },
    info:    { fg: PM.info,     bg: PM.infoBg,   br: PM.infoBorder },
    rose:    { fg: PM.rose,     bg: '#fce7f3',   br: PM.roseSoft },
    plum:    { fg: PM.plum,     bg: '#f3e8ff',   br: PM.plumSoft },
    sky:     { fg: PM.sky,      bg: '#e0f2fe',   br: PM.skySoft },
    sage:    { fg: '#3f6212',   bg: '#ecfccb',   br: PM.sageSoft },
  };
  const c = map[tone] || map.neutral;
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 5,
      padding: '4px 10px', borderRadius: 999,
      fontSize: 12, fontWeight: 500, color: c.fg,
      background: c.bg, border: `1px solid ${c.br}`,
      whiteSpace: 'nowrap', ...style,
    }}>{icon ? <span style={{ display: 'inline-flex' }}>{icon}</span> : null}{children}</span>
  );
}

// ─────────────────────────────────────────────────────────────
// Button — big, friendly
// ─────────────────────────────────────────────────────────────
function PMButton({ children, kind = 'primary', size = 'md', icon, iconRight, full, onClick, style, disabled }) {
  const sizes = {
    sm: { fs: 13, py: 9, px: 14, ic: 14 },
    md: { fs: 15, py: 13, px: 18, ic: 16 },
    lg: { fs: 16, py: 16, px: 22, ic: 18 },
  };
  const sz = sizes[size];
  const styles = {
    primary:   { bg: PM.teal700, fg: '#fff', br: PM.teal700 },
    secondary: { bg: PM.card,    fg: PM.text,br: PM.borderStrong },
    soft:      { bg: PM.teal50,  fg: PM.teal700, br: PM.tealSoft },
    ghost:     { bg: 'transparent', fg: PM.text, br: 'transparent' },
    warm:      { bg: PM.terracotta, fg: '#fff', br: PM.terracotta },
    danger:    { bg: PM.bad, fg: '#fff', br: PM.bad },
  };
  const k = styles[kind] || styles.primary;
  return (
    <button onClick={onClick} disabled={disabled} style={{
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
      fontFamily: PM.fontUI, fontSize: sz.fs, fontWeight: 600,
      padding: `${sz.py}px ${sz.px}px`, borderRadius: 14,
      background: k.bg, color: k.fg, border: `1px solid ${k.br}`,
      cursor: disabled ? 'not-allowed' : 'pointer', opacity: disabled ? 0.5 : 1,
      width: full ? '100%' : 'auto', ...style,
    }}>
      {icon ? <span style={{ display: 'inline-flex' }}>{React.cloneElement(icon, { size: sz.ic })}</span> : null}
      {children}
      {iconRight ? <span style={{ display: 'inline-flex' }}>{React.cloneElement(iconRight, { size: sz.ic })}</span> : null}
    </button>
  );
}

// ─────────────────────────────────────────────────────────────
// Bottom navigation
// ─────────────────────────────────────────────────────────────
function PMBottomNav({ active = 'home' }) {
  const items = [
    { id: 'home',  label: 'Hoje',     icon: Icons.Home },
    { id: 'score', label: 'Score',    icon: Icons.Activity },
    { id: 'plan',  label: 'Plano',    icon: Icons.Target },
    { id: 'chat',  label: 'Equipe',   icon: Icons.Mail },
    { id: 'me',    label: 'Eu',       icon: Icons.User },
  ];
  return (
    <div style={{
      position: 'absolute', left: 0, right: 0, bottom: 0,
      paddingBottom: 28, paddingTop: 8,
      background: 'rgba(255,253,249,0.94)',
      backdropFilter: 'blur(20px)', WebkitBackdropFilter: 'blur(20px)',
      borderTop: `1px solid ${PM.border}`,
      display: 'flex', justifyContent: 'space-around', alignItems: 'center',
    }}>
      {items.map((it) => {
        const Ic = it.icon;
        const on = active === it.id;
        return (
          <button key={it.id} style={{
            flex: 1, padding: '6px 4px', border: 'none', background: 'transparent',
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
            cursor: 'pointer', color: on ? PM.teal700 : PM.textMute,
          }}>
            <Ic size={22} color={on ? PM.teal700 : PM.textMute}/>
            <span style={{ fontSize: 10.5, fontWeight: on ? 600 : 500 }}>{it.label}</span>
          </button>
        );
      })}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// MetricBig — large hero number
// ─────────────────────────────────────────────────────────────
function PMBigMetric({ value, unit, label, trend, color }) {
  return (
    <div>
      <div style={{ fontSize: 12, color: PM.textMute, fontWeight: 500, letterSpacing: 0.3, textTransform: 'uppercase' }}>{label}</div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginTop: 6 }}>
        <span style={{
          fontFamily: PM.fontDisplay, fontSize: 56, fontWeight: 700,
          color: color || PM.text, letterSpacing: -1.5, lineHeight: 1,
          fontVariantNumeric: 'tabular-nums',
        }}>{value}</span>
        {unit ? <span style={{ fontSize: 16, color: PM.textMute, fontWeight: 500 }}>{unit}</span> : null}
      </div>
      {trend ? <div style={{ marginTop: 8, fontSize: 13, color: trend.color || PM.textSoft }}>{trend.text}</div> : null}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Sparkline — shaped for warm app (rounded cap, soft fill)
// ─────────────────────────────────────────────────────────────
function PMSpark({ values = [], width = 100, height = 32, color, fill }) {
  if (!values.length) return null;
  const min = Math.min(...values), max = Math.max(...values);
  const range = max - min || 1;
  const dx = width / (values.length - 1 || 1);
  const pts = values.map((v, i) => [i * dx, height - 3 - ((v - min) / range) * (height - 6)]);
  const d = pts.map((p, i) => `${i === 0 ? 'M' : 'L'}${p[0].toFixed(1)},${p[1].toFixed(1)}`).join(' ');
  const area = `${d} L${width},${height} L0,${height} Z`;
  return (
    <svg width={width} height={height}>
      {fill ? <path d={area} fill={fill} stroke="none"/> : null}
      <path d={d} fill="none" stroke={color || PM.teal700} strokeWidth={2} strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
}

// ─────────────────────────────────────────────────────────────
// Avatar — Mariana
// ─────────────────────────────────────────────────────────────
function PMAvatar({ size = 36, name = 'Mariana Corrêa' }) {
  const init = name.split(' ').filter(Boolean).slice(0, 2).map((s) => s[0]).join('').toUpperCase();
  return (
    <span style={{
      width: size, height: size, borderRadius: '50%',
      background: 'linear-gradient(135deg, #fed7aa 0%, #fdba74 100%)',
      color: '#9a3412', display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      fontSize: Math.round(size * 0.4), fontWeight: 700, flexShrink: 0,
    }}>{init}</span>
  );
}

// ─────────────────────────────────────────────────────────────
// Streak chip — fire emoji-free, terracotta dot
// ─────────────────────────────────────────────────────────────
function PMStreak({ days = 4, label = 'dias seguidos' }) {
  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center', gap: 8,
      padding: '6px 12px', borderRadius: 999,
      background: PM.amber50, border: `1px solid ${PM.amberSoft}`,
    }}>
      <Icons.Flame size={14} color={PM.terracotta}/>
      <span style={{ fontSize: 13, fontWeight: 700, color: PM.terracotta, fontVariantNumeric: 'tabular-nums' }}>{days}</span>
      <span style={{ fontSize: 12, color: PM.textSoft }}>{label}</span>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Coach line — quoted message from clinical team
// ─────────────────────────────────────────────────────────────
function PMCoachLine({ author = 'Dr. Helena Marques', role = 'Sua médica', children, when }) {
  return (
    <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
      <span style={{
        width: 36, height: 36, borderRadius: '50%',
        background: 'linear-gradient(135deg, #ccfbf1 0%, #5eead4 100%)',
        color: PM.teal900, display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 14, fontWeight: 700, flexShrink: 0,
      }}>HM</span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, flexWrap: 'wrap' }}>
          <span style={{ fontSize: 13.5, fontWeight: 600, color: PM.text }}>{author}</span>
          <span style={{ fontSize: 11, color: PM.textMute }}>{role}</span>
          {when ? <span style={{ fontSize: 11, color: PM.textMute }}>· {when}</span> : null}
        </div>
        <div style={{ fontSize: 14, color: PM.textSoft, lineHeight: 1.5, marginTop: 4 }}>{children}</div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Domain chip — small icon + label, status colored
// ─────────────────────────────────────────────────────────────
function PMDomainChip({ id, label, icon, score, status = 'green' }) {
  const map = {
    green:  { fg: PM.ok,   bg: PM.okBg,   br: PM.okBorder },
    yellow: { fg: PM.warn, bg: PM.warnBg, br: PM.warnBorder },
    red:    { fg: PM.bad,  bg: PM.badBg,  br: PM.badBorder },
    gray:   { fg: PM.textMute, bg: PM.cardSoft, br: PM.border },
  };
  const c = map[status] || map.gray;
  const Ic = typeof icon === 'string' ? Icons[icon] : icon;
  return (
    <div style={{
      padding: 12, borderRadius: 14,
      background: PM.card, border: `1px solid ${PM.border}`,
      display: 'flex', flexDirection: 'column', gap: 6,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <span style={{
          width: 28, height: 28, borderRadius: 8, background: c.bg,
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        }}>{Ic ? <Ic size={14} color={c.fg}/> : null}</span>
        <span style={{ flex: 1, fontSize: 13, fontWeight: 600, color: PM.text }}>{label}</span>
      </div>
      {score != null ? (
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 4 }}>
          <span style={{ fontFamily: PM.fontDisplay, fontSize: 24, fontWeight: 700, color: c.fg, letterSpacing: -0.5, lineHeight: 1, fontVariantNumeric: 'tabular-nums' }}>{score}</span>
          <span style={{ fontSize: 11, color: PM.textMute }}>/100</span>
        </div>
      ) : null}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Progress ring — for score visuals
// ─────────────────────────────────────────────────────────────
function PMRing({ value, max = 100, size = 120, stroke = 10, color, label }) {
  const r = (size - stroke) / 2;
  const c = 2 * Math.PI * r;
  const off = c - (value / max) * c;
  return (
    <div style={{ position: 'relative', width: size, height: size }}>
      <svg width={size} height={size}>
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke={PM.cardSoft} strokeWidth={stroke}/>
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke={color || PM.teal700} strokeWidth={stroke}
          strokeLinecap="round" strokeDasharray={c} strokeDashoffset={off}
          transform={`rotate(-90 ${size/2} ${size/2})`}/>
      </svg>
      <div style={{
        position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column',
        alignItems: 'center', justifyContent: 'center',
      }}>
        <span style={{
          fontFamily: PM.fontDisplay, fontSize: size * 0.32, fontWeight: 700,
          color: PM.text, letterSpacing: -0.5, lineHeight: 1,
          fontVariantNumeric: 'tabular-nums',
        }}>{value}</span>
        {label ? <span style={{ fontSize: 11, color: PM.textMute, marginTop: 2 }}>{label}</span> : null}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Mood / scale buttons (1-5 with labels)
// ─────────────────────────────────────────────────────────────
function PMMoodScale({ value, onChange, labels = ['😞','😕','😐','🙂','😊'] }) {
  return (
    <div style={{ display: 'flex', gap: 8 }}>
      {labels.map((l, i) => {
        const on = value === i + 1;
        return (
          <button key={i} onClick={() => onChange && onChange(i + 1)} style={{
            flex: 1, height: 56, borderRadius: 12, fontSize: 26, cursor: 'pointer',
            border: `1.5px solid ${on ? PM.teal700 : PM.border}`,
            background: on ? PM.teal50 : PM.card,
            boxShadow: on ? `0 0 0 3px ${PM.tealSoft}` : 'none',
          }}>{l}</button>
        );
      })}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Soft progress bar (rounded, gradient)
// ─────────────────────────────────────────────────────────────
function PMBar({ value, max = 100, color, height = 8, bg }) {
  const pct = Math.max(0, Math.min(100, (value / max) * 100));
  return (
    <div style={{ width: '100%', height, background: bg || PM.cardSoft, borderRadius: 999, overflow: 'hidden' }}>
      <div style={{ width: `${pct}%`, height: '100%', background: color || PM.teal700, borderRadius: 999 }}/>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Wearable badge — Apple Watch / Oura / Whoop / Garmin / CGM
// ─────────────────────────────────────────────────────────────
function PMWearable({ kind = 'watch', synced = true }) {
  const data = {
    watch:  { label: 'Apple Watch', dot: '#000' },
    oura:   { label: 'Oura',        dot: '#1c1917' },
    whoop:  { label: 'Whoop',       dot: '#0a0a0a' },
    garmin: { label: 'Garmin',      dot: '#0369a1' },
    cgm:    { label: 'Libre 3',     dot: '#fbbf24' },
  };
  const w = data[kind] || data.watch;
  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center', gap: 6,
      padding: '4px 10px', borderRadius: 999,
      background: PM.cardSoft, border: `1px solid ${PM.border}`,
      fontSize: 11, color: PM.textSoft, fontWeight: 500,
    }}>
      <span style={{ width: 6, height: 6, borderRadius: '50%', background: w.dot }}/>
      {w.label}
      {synced ? <Icons.Check size={11} color={PM.ok} style={{ marginLeft: 2 }}/> : null}
    </div>
  );
}

// Make all of the above globally available to screens
Object.assign(window, {
  PM, PMShell, PMHeader, PMCard, PMSection, PMPill, PMButton, PMBottomNav,
  PMBigMetric, PMSpark, PMAvatar, PMStreak, PMCoachLine, PMDomainChip, PMRing,
  PMMoodScale, PMBar, PMWearable,
});
