// Nutrition, Chat, Profile screens

function NutritionScreen({ t, coach, dark }) {
  const [tab, setTab] = React.useState('Food Log');
  const [selectedDay, setSelectedDay] = React.useState(27);
  const [openMeal, setOpenMeal] = React.useState('breakfast');

  const days = [
    { d: 'S', n: 24 }, { d: 'M', n: 25, dot: true }, { d: 'T', n: 26, dot: true },
    { d: 'W', n: 27 }, { d: 'T', n: 28 }, { d: 'F', n: 29 }, { d: 'S', n: 30 },
  ];

  return (
    <>
      <ContentHeader t={t} coach={coach}/>
      <div style={{ padding: '0 18px', display: 'flex', flexDirection: 'column', gap: 14 }}>
        {/* Logged days bar */}
        <div>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 8 }}>
            <div style={{ fontSize: 17, fontWeight: 700, color: t.text }}>Logged Days</div>
            <div style={{ fontSize: 14, color: t.primary, fontWeight: 700 }}>3/7</div>
          </div>
          <div style={{ height: 5, background: t.surface3, borderRadius: 999, overflow: 'hidden' }}>
            <div style={{ width: '42%', height: '100%', background: t.primary, borderRadius: 999 }}/>
          </div>
        </div>

        {/* Day picker */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
          <button style={btnIcon(t)}><Icon.Back size={14} color={t.textMuted}/></button>
          <div style={{ flex: 1, display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 2 }}>
            {days.map(d => {
              const active = selectedDay === d.n;
              return (
                <button key={d.n} onClick={() => setSelectedDay(d.n)} style={{
                  background: 'none', border: 'none', cursor: 'pointer', padding: 4,
                  display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
                  fontFamily: 'inherit',
                }}>
                  <div style={{ fontSize: 11, color: t.textMuted, fontWeight: 600 }}>{d.d}</div>
                  <div style={{
                    width: 32, height: 32, borderRadius: 999,
                    background: active ? t.primary : 'transparent',
                    color: active ? t.onPrimary : t.text,
                    fontSize: 14, fontWeight: 700,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                  }}>{d.n}</div>
                  {d.dot && !active && (
                    <div style={{ width: 4, height: 4, borderRadius: 2, background: t.primary, marginTop: -2 }}/>
                  )}
                </button>
              );
            })}
          </div>
          <button style={btnIcon(t)}><Icon.ChevronRight size={14} color={t.textMuted}/></button>
        </div>

        <PillToggle options={['Food Log', 'Meal Plan']} value={tab} onChange={setTab} t={t}/>

        {/* Macro card */}
        <Card t={t} style={{ display: 'flex', alignItems: 'center', gap: 18, padding: '18px 18px' }}>
          <ProgressRing value={33} t={t} size={92} stroke={7} label={
            <div style={{ textAlign: 'center', lineHeight: 1 }}>
              <div style={{ fontSize: 22, fontWeight: 700, color: t.text }}>670</div>
              <div style={{ fontSize: 10, color: t.textMuted, marginTop: 2 }}>/ 2000</div>
            </div>
          } customLabel/>
          <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 12 }}>
            <Macro t={t} name="Protein" value={40} max={150} color={t.protein}/>
            <Macro t={t} name="Carbs"   value={63} max={200} color={t.carbs}/>
            <Macro t={t} name="Fat"     value={23} max={65}  color={t.fat}/>
          </div>
        </Card>

        {/* Meals */}
        <Meal t={t} dark={dark} icon={<span style={{fontSize:22}}>🌅</span>} title="Breakfast"
          kcal="520/550" pct={95}
          tags={[{ k: 'P', v: '32g', c: t.protein }, { k: 'C', v: '48g', c: t.carbs }, { k: 'F', v: '18g', c: t.fat }]}
          open={openMeal === 'breakfast'} onToggle={() => setOpenMeal(openMeal === 'breakfast' ? null : 'breakfast')}
          items={[
            { name: 'Avocado Toast with Eggs', sub: '1 serving · 8:30 AM', kcal: 320, p: 18, c: 28, f: 14 },
            { name: 'Greek Yogurt & Berries',  sub: '1 serving · 9:00 AM', kcal: 200, p: 14, c: 20, f: 4 },
          ]}
        />
        <Meal t={t} dark={dark}
          icon={<span style={{fontSize:22}}>🍎</span>}
          title="Morning Snack" kcal="150/200" pct={75}
          tags={[{ k: 'P', v: '8g', c: t.protein }, { k: 'C', v: '15g', c: t.carbs }, { k: 'F', v: '5g', c: t.fat }]}
          open={openMeal === 'snack'} onToggle={() => setOpenMeal(openMeal === 'snack' ? null : 'snack')}
        />
        <Meal t={t} dark={dark}
          icon={<span style={{fontSize:22}}>☀️</span>}
          title="Lunch" kcal="0/650" pct={0}
          open={openMeal === 'lunch'} onToggle={() => setOpenMeal(openMeal === 'lunch' ? null : 'lunch')}
        />
        <div style={{ height: 100 }}/>
      </div>
    </>
  );
}

function btnIcon(t) {
  return {
    width: 28, height: 28, borderRadius: 999, border: 'none',
    background: 'transparent', cursor: 'pointer',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
  };
}

function Macro({ t, name, value, max, color }) {
  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, marginBottom: 4 }}>
        <div style={{ fontWeight: 700, color: t.text }}>{name}</div>
        <div style={{ color: t.textMuted }}>{value}/{max}g</div>
      </div>
      <div style={{ height: 4, background: t.surface3, borderRadius: 4, overflow: 'hidden' }}>
        <div style={{ width: `${(value / max) * 100}%`, height: '100%', background: color, borderRadius: 4 }}/>
      </div>
    </div>
  );
}

function Meal({ t, dark, icon, title, kcal, pct, tags = [], open, onToggle, items = [] }) {
  return (
    <Card t={t} style={{ padding: 0, overflow: 'hidden' }}>
      <button onClick={onToggle} style={{
        width: '100%', background: 'none', border: 'none', cursor: 'pointer',
        padding: 14, display: 'flex', alignItems: 'center', gap: 12,
        fontFamily: 'inherit', textAlign: 'left',
      }}>
        <div style={{
          width: 36, height: 36, borderRadius: 8,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>{icon}</div>
        <div style={{ flex: 1 }}>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
            <div style={{ fontSize: 15, fontWeight: 700, color: t.text }}>{title}</div>
            <div style={{ fontSize: 12, color: t.textMuted }}>{kcal} cal</div>
          </div>
          {tags.length > 0 && (
            <div style={{ display: 'flex', gap: 6, marginTop: 6 }}>
              {tags.map((tag, i) => (
                <div key={i} style={{
                  fontSize: 10, fontWeight: 600,
                  padding: '3px 7px', borderRadius: 999,
                  background: tagBg(tag.c, dark), color: tag.c,
                }}>{tag.k} {tag.v}</div>
              ))}
            </div>
          )}
        </div>
        <div style={{
          width: 38, height: 38, borderRadius: 999,
          border: `2px solid ${t.primary}`, color: t.primary,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 11, fontWeight: 700,
        }}>{pct}%</div>
        <div style={{ marginLeft: 4 }}>
          {open ? <Icon.ChevronUp color={t.textMuted}/> : <Icon.ChevronDown color={t.textMuted}/>}
        </div>
      </button>
      {open && items.length > 0 && (
        <div style={{ borderTop: `1px solid ${t.border}`, padding: '4px 14px 14px' }}>
          {items.map((it, i) => (
            <div key={i} style={{ padding: '12px 0', borderBottom: i < items.length - 1 ? `1px solid ${t.border}` : 'none' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                <div style={{ fontSize: 14, fontWeight: 700, color: t.text, display: 'flex', alignItems: 'center', gap: 6 }}>
                  {it.name}
                  <Icon.Pencil size={12} color={t.textMuted}/>
                  <Icon.Trash size={12} color={t.textMuted}/>
                </div>
                <div style={{ fontSize: 13, color: t.primary, fontWeight: 700 }}>{it.kcal} cal</div>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 4 }}>
                <div style={{ fontSize: 11, color: t.textMuted }}>{it.sub}</div>
                <div style={{ display: 'flex', gap: 4 }}>
                  <Tag t={t} dark={dark} k="P" v={it.p+'g'} c={t.protein}/>
                  <Tag t={t} dark={dark} k="C" v={it.c+'g'} c={t.carbs}/>
                  <Tag t={t} dark={dark} k="F" v={it.f+'g'} c={t.fat}/>
                </div>
              </div>
            </div>
          ))}
          <button style={{
            marginTop: 12, width: '100%', background: 'transparent',
            border: `1.5px dashed ${t.primary}`, color: t.primary,
            padding: 12, borderRadius: 14, fontSize: 13, fontWeight: 700,
            cursor: 'pointer', fontFamily: 'inherit',
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
          }}><Icon.Plus size={14} color={t.primary}/> Add Food</button>
        </div>
      )}
    </Card>
  );
}

function Tag({ t, dark, k, v, c }) {
  return (
    <div style={{
      fontSize: 10, fontWeight: 600,
      padding: '3px 7px', borderRadius: 999,
      background: tagBg(c, dark), color: c,
    }}>{k} {v}</div>
  );
}

function tagBg(color, dark) {
  // semi-transparent based on color
  if (dark) return color + '26';
  return color + '22';
}

// ────────────────────────────── Chat ──────────────────────────────
function ChatScreen({ t, coach, dark }) {
  const [aiOn, setAiOn] = React.useState(false);
  const [text, setText] = React.useState('');

  if (aiOn) return <LiftAIChatView t={t} coach={coach} dark={dark} onToggleOff={() => setAiOn(false)}/>;

  return (
    <>
      {/* Top user header (no greeting) */}
      <div style={{
        padding: '110px 18px 14px', display: 'flex', alignItems: 'center', gap: 12,
      }}>
        <div style={{
          width: 42, height: 42, borderRadius: 999,
          background: `linear-gradient(135deg, ${t.secondarySoft}, ${t.secondary})`,
          color: '#fff', fontWeight: 700, fontSize: 14,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>OL</div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 16, fontWeight: 700, color: t.text }}>Orville Leffler</div>
          <div style={{ fontSize: 12, color: '#34C759', fontWeight: 600 }}>Online</div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <Icon.Info color={t.textMuted}/>
          <Icon.Sparkle color={t.primary}/>
          <span style={{ fontSize: 12, fontWeight: 700, color: t.text }}>LIFT AI</span>
          <Switch on={aiOn} setOn={setAiOn} t={t}/>
        </div>
      </div>
      <div style={{ height: 1, background: t.border }}/>

      {/* Messages */}
      <div style={{
        padding: '14px 18px 14px', display: 'flex', flexDirection: 'column', gap: 10,
        minHeight: 460,
      }}>
        <div style={{ alignSelf: 'center',
          background: t.surface3, color: t.textMuted,
          fontSize: 12, fontWeight: 600, padding: '5px 12px', borderRadius: 999,
          marginBottom: 4,
        }}>Today</div>

        <Bubble t={t} side="right" text="Hi, John" time="4:30 pm"/>
        <Bubble t={t} side="right" text="I did a walking activity today" time="4:30 pm"/>
        <Bubble t={t} side="left" text="Hi, Robert" time="4:30 pm"/>

        {/* voice message - left */}
        <VoiceBubble t={t} side="left" duration="0:24" time="4:31 pm"/>
        {/* voice message - right */}
        <VoiceBubble t={t} side="right" duration="0:42" time="4:31 pm"/>

        <Bubble t={t} side="right" text="Please, can you send me anything for motivation" time="4:32 pm"/>

        {/* video message */}
        <div style={{ alignSelf: 'flex-end', maxWidth: '78%' }}>
          <div style={{ position: 'relative', borderRadius: 14, overflow: 'hidden' }}>
            <ImgPlaceholder label="video preview" height={140} t={t} dark={true}/>
            <div style={{
              position: 'absolute', inset: 0,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <div style={{
                width: 44, height: 44, borderRadius: 999,
                background: 'rgba(255,255,255,0.9)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>
                <Icon.Play size={16} color="#000"/>
              </div>
            </div>
            <div style={{
              position: 'absolute', bottom: 8, right: 10,
              color: '#fff', fontSize: 11, fontWeight: 600,
              textShadow: '0 1px 2px rgba(0,0,0,0.5)',
            }}>1:12</div>
          </div>
        </div>
      </div>

      {/* Composer — scrolls with the page so it doesn't cover messages */}
      <div style={{
        margin: '8px 14px 14px',
        padding: '10px 0',
      }}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 10,
          background: t.surface3, borderRadius: 999, padding: '6px 6px 6px 4px',
        }}>
          <div style={{
            width: 32, height: 32, borderRadius: 999,
            background: t.surface, display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: t.textMuted, fontSize: 18, fontWeight: 400,
          }}>+</div>
          <input value={text} onChange={e => setText(e.target.value)}
            placeholder="Type your message..."
            style={{
              flex: 1, background: 'transparent', border: 'none', outline: 'none',
              fontSize: 14, color: t.text, fontFamily: 'inherit',
            }}/>
          <div style={{
            width: 32, height: 32, borderRadius: 999,
            background: t.surface, display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <Icon.Mic size={15} color={t.textMuted}/>
          </div>
        </div>
      </div>
    </>
  );
}

function Switch({ on, setOn, t }) {
  return (
    <button onClick={() => setOn(!on)} style={{
      width: 36, height: 22, borderRadius: 999, border: 'none', padding: 0,
      background: on ? t.primary : t.surface3, cursor: 'pointer',
      display: 'flex', alignItems: 'center', justifyContent: on ? 'flex-end' : 'flex-start',
      transition: 'background .2s',
    }}>
      <div style={{
        width: 18, height: 18, borderRadius: 999, background: '#fff',
        margin: 2, boxShadow: '0 1px 3px rgba(0,0,0,0.2)',
      }}/>
    </button>
  );
}

function Bubble({ t, side, text, time }) {
  const isRight = side === 'right';
  return (
    <div style={{
      alignSelf: isRight ? 'flex-end' : 'flex-start',
      maxWidth: '78%',
      background: isRight ? t.primary : t.surface3,
      color: isRight ? t.onPrimary : t.text,
      padding: '10px 14px', borderRadius: 18,
      borderBottomRightRadius: isRight ? 6 : 18,
      borderBottomLeftRadius: isRight ? 18 : 6,
      fontSize: 14, lineHeight: 1.35,
      position: 'relative',
    }}>
      <div>{text}</div>
      <div style={{
        fontSize: 10, opacity: 0.75, marginTop: 4, textAlign: 'right',
      }}>{time}</div>
    </div>
  );
}

function VoiceBubble({ t, side, duration, time }) {
  const isRight = side === 'right';
  const fg = isRight ? t.onPrimary : t.text;
  const bg = isRight ? t.primary : t.surface3;
  const playBg = isRight ? 'rgba(255,255,255,0.25)' : t.primary;
  const playFg = isRight ? '#fff' : t.onPrimary;
  return (
    <div style={{
      alignSelf: isRight ? 'flex-end' : 'flex-start',
      background: bg, color: fg, padding: 10, borderRadius: 18,
      display: 'flex', alignItems: 'center', gap: 10,
      maxWidth: '70%',
    }}>
      <div style={{
        width: 30, height: 30, borderRadius: 999, background: playBg,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <Icon.Play size={11} color={playFg}/>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 1.5, flex: 1 }}>
        {Array.from({ length: 26 }).map((_, i) => (
          <div key={i} style={{
            width: 2, borderRadius: 1, background: fg, opacity: 0.8,
            height: 4 + Math.abs(Math.sin(i * 1.3)) * 14,
          }}/>
        ))}
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 2 }}>
        <div style={{ fontSize: 12, fontWeight: 600 }}>{duration}</div>
        <div style={{ fontSize: 9, opacity: 0.75 }}>{time}</div>
      </div>
    </div>
  );
}

// ────────────────────────────── Profile ──────────────────────────────
function ProfileScreen({ t, coach, dark, onMenu, onCommunity }) {
  const [tab, setTab] = React.useState('Progress');
  const nav = useNav();
  return (
    <>
      <ContentHeader t={t} coach={coach} greeting={false} leftStyle="none" onCommunity={onCommunity}/>
      <div style={{ padding: '0 18px', display: 'flex', flexDirection: 'column', gap: 16 }}>
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8 }}>
          <div style={{ position: 'relative' }}>
            <div style={{
              width: 110, height: 110, borderRadius: 999,
              border: `3px solid ${t.primary}`, padding: 4,
              background: t.surface,
            }}>
              <div style={{
                width: '100%', height: '100%', borderRadius: 999, overflow: 'hidden',
                background: coach.avatar_img ? t.surface3 : `linear-gradient(135deg, ${t.secondarySoft}, ${t.secondary})`,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                color: '#fff', fontSize: 36, fontWeight: 700,
              }}>{coach.avatar_img
                ? <img src={coach.avatar_img} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }}/>
                : coach.coach.split(' ').map(n => n[0]).join('').slice(0,2)}</div>
            </div>
            <div style={{
              position: 'absolute', bottom: 4, right: 4,
              width: 28, height: 28, borderRadius: 999, background: t.primary,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              border: `2px solid ${t.surface}`,
            }}>
              <Icon.Pencil size={12} color={t.onPrimary}/>
            </div>
          </div>
          <div style={{ fontSize: 22, fontWeight: 700, color: t.text }}>{coach.coach}</div>
          <div style={{ fontSize: 13, color: t.textMuted }}>{coach.coach.toLowerCase().replace(' ', '')}@gmail.com</div>
        </div>

        <PillToggle options={['Progress', 'Health', 'Library']} value={tab} onChange={setTab} t={t}/>

        {tab === 'Health' && <ProfileHealthTab t={t} dark={dark} nav={nav}/>}
        {tab === 'Library' && <ProfileLibraryTab t={t} dark={dark} nav={nav}/>}
        {tab === 'Progress' && <>
        <SectionTitle t={t} title="Check-Ins" action="See All"/>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {['August 16, 2025', 'August 9, 2025', 'August 2, 2025'].map((d, i) => (
            <Card key={i} t={t} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: 14 }}>
              <div style={{
                width: 38, height: 38, borderRadius: 8, background: t.primarySoft,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>
                <Icon.Calendar size={20} color={t.primary}/>
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14, fontWeight: 700, color: t.text }}>{d}</div>
                <div style={{ fontSize: 11, color: t.success, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 4, marginTop: 2 }}>
                  <span style={{ width: 10, height: 10, borderRadius: 999, border: `1.5px solid ${t.success}`, display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
                    <Icon.Check size={6} color={t.success}/>
                  </span>
                  Completed
                </div>
              </div>
              <Icon.ChevronRight color={t.textDim}/>
            </Card>
          ))}
        </div>

        <button style={{
          background: 'transparent', border: `1.5px dashed ${t.primary}`,
          color: t.primary, padding: 14, borderRadius: 14,
          fontSize: 14, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit',
        }}>+ Add Check-In</button>

        <SectionTitle t={t} title="Progress Photos" action="View All"/>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          <div style={{ position: 'relative', height: 130, borderRadius: 14, overflow: 'hidden' }}>
            <img src="https://images.unsplash.com/photo-1518611012118-696072aa579a?w=600&q=70&auto=format&fit=crop"
              alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }}/>
            <div style={{
              position: 'absolute', bottom: 6, left: 8,
              fontSize: 10, fontWeight: 700, color: '#fff', letterSpacing: 1,
              background: 'rgba(0,0,0,0.45)', padding: '2px 8px', borderRadius: 999,
              backdropFilter: 'blur(4px)',
            }}>BEFORE · JUN</div>
          </div>
          <div style={{ position: 'relative', height: 130, borderRadius: 14, overflow: 'hidden' }}>
            <img src="https://images.unsplash.com/photo-1506126613408-eca07ce68773?w=600&q=70&auto=format&fit=crop"
              alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }}/>
            <div style={{
              position: 'absolute', bottom: 6, left: 8,
              fontSize: 10, fontWeight: 700, color: '#fff', letterSpacing: 1,
              background: 'rgba(0,0,0,0.45)', padding: '2px 8px', borderRadius: 999,
              backdropFilter: 'blur(4px)',
            }}>AFTER · AUG</div>
          </div>
        </div>
        </>}

        <div style={{ height: 100 }}/>
      </div>
    </>
  );
}

function ProfileHealthTab({ t, dark, nav }) {
  // Sub-scores drive the 2x2 grid. Activity uses primary. Sleep green. Mind/Recovery primary.
  const alpha = (c, a) => `color-mix(in oklch, ${c} ${Math.round(a*100)}%, transparent)`;
  const subScores = [
    { key: 'activity',  label: 'Activity',  sub: 'Good',     score: 65, delta: -3, color: t.primary, bg: alpha(t.primary, 0.10),
      icon: <Icon.Bolt size={18} color={t.primary}/> },
    { key: 'sleep',     label: 'Sleep',     sub: 'Optimal',  score: 81, delta: +6, color: t.success, bg: alpha(t.success, 0.10),
      icon: <Icon.Moon size={18} color={t.success}/> },
    { key: 'mind',      label: 'Mind',      sub: 'Fair',     score: 58, delta: -2, color: t.primary, bg: alpha(t.primary, 0.10),
      icon: (
        <svg width={18} height={18} viewBox="0 0 24 24" fill="none">
          <path d="M9 4a3 3 0 00-3 3v1a3 3 0 00-2 5 3 3 0 002 5v1a3 3 0 006 0V4a3 3 0 00-3 0zm6 0a3 3 0 013 3v1a3 3 0 012 5 3 3 0 01-2 5v1a3 3 0 01-6 0"
            stroke={t.primary} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
      ),
    },
    { key: 'recovery',  label: 'Recovery',  sub: 'Strong',   score: 74, delta: +2, color: t.primary, bg: alpha(t.primary, 0.10),
      icon: (
        <svg width={18} height={18} viewBox="0 0 24 24" fill="none">
          <path d="M4 17l5-5 4 4 7-7" stroke={t.primary} strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
      ),
    },
  ];

  return (
    <>
      {/* Wellbeing hero ring */}
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', padding: '12px 0 4px' }}>
        <HealthRing size={220} stroke={10} value={72} color={t.primary} t={t}>
          <Icon.Heart size={22} color={t.primary}/>
          <div style={{ fontSize: 56, fontWeight: 800, color: t.text, letterSpacing: -1.5, lineHeight: 1 }}>72</div>
          <div style={{ fontSize: 12, fontWeight: 700, color: t.textMuted, letterSpacing: 2, marginTop: 2 }}>GOOD</div>
        </HealthRing>

        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 18, alignSelf: 'stretch', justifyContent: 'center', position: 'relative' }}>
          <div style={{ fontSize: 15, fontWeight: 700, color: t.text, display: 'flex', alignItems: 'center', gap: 6 }}>
            Wellbeing
            <TrendArrow delta={+4} t={t}/>
            <span style={{ color: t.success, fontWeight: 700 }}>+4</span>
          </div>
          <button style={{
            position: 'absolute', right: 0,
            width: 28, height: 28, borderRadius: 999, background: t.surface3,
            border: 'none', cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <Icon.Info size={14} color={t.textMuted}/>
          </button>
        </div>
      </div>

      {/* 2x2 sub-score grid */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginTop: 6 }}>
        {subScores.map(s => (
          <button key={s.key}
            onClick={() => nav.push(p => <HealthFactorDetailScreen {...p} factor={s}/>)}
            style={{
              border: 'none', cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left',
              background: `radial-gradient(circle at 15% 15%, ${s.bg}, ${t.surface} 70%)`,
              padding: 14, borderRadius: 16, position: 'relative',
              boxShadow: '0 1px 3px rgba(0,0,0,0.04)',
              display: 'flex', flexDirection: 'column', gap: 10,
            }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <HealthRing size={50} stroke={4} value={s.score} color={s.color} t={t}>
                {s.icon}
              </HealthRing>
              <div style={{ flex: 1, textAlign: 'right' }}>
                <div style={{ fontSize: 22, fontWeight: 800, color: t.text, letterSpacing: -0.5, lineHeight: 1 }}>{s.score}</div>
                <div style={{
                  fontSize: 11, fontWeight: 700, marginTop: 3,
                  color: s.delta >= 0 ? t.success : '#E5573D',
                  display: 'inline-flex', alignItems: 'center', gap: 3,
                }}>
                  <TrendArrow delta={s.delta} t={t} size={10}/>
                  {s.delta >= 0 ? '+' : ''}{s.delta}
                </div>
              </div>
            </div>
            <div>
              <div style={{ fontSize: 15, fontWeight: 700, color: t.text }}>{s.label}</div>
              <div style={{ fontSize: 12, color: t.textMuted, marginTop: 2 }}>{s.sub}</div>
            </div>
            <div style={{
              position: 'absolute', right: 10, bottom: 10,
              width: 20, height: 20, borderRadius: 999,
              background: t.surface3,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <Icon.Info size={10} color={t.textMuted}/>
            </div>
          </button>
        ))}
      </div>
    </>
  );
}

// Ring used across Health views: thick open arc, glow at 15% of opacity inside,
// content in center.
function HealthRing({ size, stroke, value, color, t, children }) {
  const r = (size - stroke) / 2;
  const c = 2 * Math.PI * r;
  const dash = c * (value / 100);
  return (
    <div style={{ position: 'relative', width: size, height: size, flexShrink: 0 }}>
      {/* soft radial glow */}
      <div style={{
        position: 'absolute', inset: stroke + 2, borderRadius: '50%',
        background: `radial-gradient(circle, ${color}33 0%, transparent 70%)`,
      }}/>
      <svg width={size} height={size} style={{ position: 'relative', transform: 'rotate(-90deg)' }}>
        <circle cx={size/2} cy={size/2} r={r}
          stroke={color} strokeWidth={stroke} fill="none" strokeLinecap="round"
          strokeDasharray={`${dash} ${c}`}/>
      </svg>
      <div style={{
        position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column',
        alignItems: 'center', justifyContent: 'center',
      }}>{children}</div>
    </div>
  );
}

// Little inline trend arrow (up-right / down-right)
function TrendArrow({ delta, t, size = 12 }) {
  const up = delta >= 0;
  const color = up ? t.success : '#E5573D';
  return (
    <svg width={size} height={size} viewBox="0 0 16 16" fill="none" style={{ flexShrink: 0 }}>
      {up
        ? <path d="M3 11 L9 5 L13 5 L13 9" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
        : <path d="M3 5  L9 11 L13 11 L13 7" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>}
    </svg>
  );
}

// Drill-in for a single health factor (Activity / Sleep / Mind / Recovery)
function HealthFactorDetailScreen({ t, coach, dark, nav, factor }) {
  const f = factor || { label: 'Activity', sub: 'Good', score: 65, delta: -3, color: t.primary };
  // 7-day bar values (mock). Today = index 6 (S on Sunday).
  const days = [
    { d: 'M', v: 0 }, { d: 'T', v: 0 }, { d: 'W', v: 0 }, { d: 'T', v: 0 },
    { d: 'F', v: 0 }, { d: 'S', v: 0 }, { d: 'S', v: 100 },
  ];
  const factors = [
    { name: 'Steps',       val: '6,200', unit: 'steps', goal: 10000, pct: 62, status: 'Good',     color: t.primary },
    { name: 'Active min',  val: '28',    unit: 'min',   goal: 60,    pct: 47, status: 'Fair',     color: t.fat },
    { name: 'Calories',    val: '1,840', unit: 'kcal',  goal: 2500,  pct: 74, status: 'Good',     color: t.protein },
  ];
  return (
    <>
      <NavHeader title={f.label} t={t}/>
      <div style={{ padding: '0 18px 24px', display: 'flex', flexDirection: 'column', gap: 18 }}>
        {/* Big ring */}
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', paddingTop: 6 }}>
          <HealthRing size={200} stroke={9} value={f.score} color={f.color} t={t}>
            <div style={{ fontSize: 54, fontWeight: 800, color: t.text, letterSpacing: -1.5, lineHeight: 1 }}>{f.score}</div>
            <div style={{ fontSize: 12, fontWeight: 700, color: t.textMuted, letterSpacing: 2, marginTop: 2 }}>
              {(f.sub || 'GOOD').toUpperCase()}
            </div>
          </HealthRing>
          <div style={{
            marginTop: 14, display: 'inline-flex', alignItems: 'center', gap: 5,
            color: f.delta >= 0 ? t.success : '#E5573D', fontWeight: 700, fontSize: 13,
          }}>
            <TrendArrow delta={f.delta} t={t} size={14}/>
            {f.delta >= 0 ? '+' : ''}{f.delta} from yesterday
          </div>
        </div>

        {/* 7-day trend */}
        <div>
          <div style={{ fontSize: 12, fontWeight: 700, color: t.textMuted, letterSpacing: 1.5, marginBottom: 8 }}>
            7-DAY TREND
          </div>
          <Card t={t} style={{ padding: '14px 12px' }}>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 8, alignItems: 'end' }}>
              {days.map((d, i) => (
                <div key={i} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
                  <div style={{
                    width: '100%', aspectRatio: '1/1.15',
                    background: d.v > 0 ? f.color : t.surface3,
                    border: d.v > 0 ? 'none' : `1.5px solid ${t.border}`,
                    borderRadius: 10,
                  }}/>
                  <div style={{ fontSize: 11, color: t.textMuted, fontWeight: 600 }}>{d.d}</div>
                </div>
              ))}
            </div>
          </Card>
        </div>

        {/* Contributing factors */}
        <div>
          <div style={{ fontSize: 12, fontWeight: 700, color: t.textMuted, letterSpacing: 1.5, marginBottom: 8 }}>
            CONTRIBUTING FACTORS
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {factors.map((x, i) => (
              <Card key={i} t={t} style={{ padding: 14 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
                  <div style={{ width: 8, height: 8, borderRadius: 999, background: x.color }}/>
                  <div style={{ fontSize: 15, fontWeight: 700, color: t.text, flex: 1 }}>{x.name}</div>
                  <div style={{ fontSize: 15, fontWeight: 800, color: t.text }}>
                    {x.val} <span style={{ fontSize: 11, color: t.textMuted, fontWeight: 600 }}>{x.unit}</span>
                    <span style={{ fontSize: 11, color: t.textMuted, fontWeight: 600 }}> / {x.goal.toLocaleString()}</span>
                  </div>
                </div>
                <div style={{ height: 5, background: t.surface3, borderRadius: 999, overflow: 'hidden' }}>
                  <div style={{ width: x.pct + '%', height: '100%', background: x.color }}/>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 8 }}>
                  <div style={{ fontSize: 12, color: t.textMuted, fontWeight: 600 }}>{x.status}</div>
                  <div style={{ fontSize: 12, color: t.textMuted, fontWeight: 600 }}>
                    {Math.round((x.pct / 100) * x.goal).toLocaleString()} / {x.goal.toLocaleString()}
                  </div>
                </div>
              </Card>
            ))}
          </div>
        </div>
      </div>
    </>
  );
}

function ProfileLibraryTab({ t, dark, nav }) {
  const collections = [
    {
      name: 'Nutrition Facts', count: 4,
      desc: 'Essential nutrition guides covering macros, micronutrients, meal timing, and how to eat for your goals.',
      img: 'https://images.unsplash.com/photo-1546069901-ba9599a7e63c?w=900&q=75&auto=format&fit=crop',
    },
    {
      name: 'Power Course', count: 4,
      desc: 'A comprehensive strength training video series designed to build raw power and technique.',
      img: 'https://images.unsplash.com/photo-1534438327276-14e5300c3a48?w=900&q=75&auto=format&fit=crop',
    },
    {
      name: 'Mindset Coaching', count: 6,
      desc: 'Daily practices and audio sessions to stay motivated, focused, and confident through your journey.',
      img: 'https://images.unsplash.com/photo-1506126613408-eca07ce68773?w=900&q=75&auto=format&fit=crop',
    },
    {
      name: 'Recovery & Mobility', count: 8,
      desc: 'Stretching, foam rolling, and recovery protocols to keep you moving well and injury-free.',
      img: 'https://images.unsplash.com/photo-1518611012118-696072aa579a?w=900&q=75&auto=format&fit=crop',
    },
  ];
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14, marginTop: 4 }}>
      {collections.map((c, i) => (
        <button key={i} onClick={() => nav.push(p => <CollectionDetailScreen {...p} collection={c}/>)}
          style={{
            border: 'none', cursor: 'pointer', padding: 0,
            borderRadius: 16, overflow: 'hidden', position: 'relative',
            height: 190, width: '100%', fontFamily: 'inherit', textAlign: 'left',
            background: t.surface3,
          }}>
          <img src={c.img} alt="" style={{
            position: 'absolute', inset: 0, width: '100%', height: '100%',
            objectFit: 'cover',
          }}/>
          <div style={{
            position: 'absolute', inset: 0,
            background: 'linear-gradient(180deg, transparent 35%, rgba(0,0,0,0.75) 100%)',
          }}/>
          <div style={{
            position: 'absolute', left: 16, right: 16, bottom: 14, color: '#fff',
          }}>
            <div style={{ fontSize: 20, fontWeight: 800, letterSpacing: -0.3 }}>{c.name}</div>
            <div style={{
              fontSize: 12, color: 'rgba(255,255,255,0.88)', marginTop: 4,
              lineHeight: 1.4, overflow: 'hidden',
              display: '-webkit-box', WebkitLineClamp: 1, WebkitBoxOrient: 'vertical',
            }}>{c.desc}</div>
            <div style={{ fontSize: 12, color: 'rgba(255,255,255,0.7)', marginTop: 6 }}>
              {c.count} items
            </div>
          </div>
        </button>
      ))}
    </div>
  );
}

Object.assign(window, { NutritionScreen, ChatScreen, ProfileScreen, Bubble, VoiceBubble, Switch, Macro, Meal, Tag, ProfileHealthTab, ProfileLibraryTab });
