/* HealthyKit.jsx — shared primitives for the Muna Health "Healthy" tier file.
   Reads the design system (tokens + MunaComponents). Adds only the small,
   reusable bits the kit didn't already have: the slide Stage, a scroll
   scaffold, the 4-tab bar for this tier (Home/Challenges/Care/Profile),
   a sage check-circle, progress bars, a tooth glyph, avatars, stat tiles,
   and the trust footer. Exports to window.

   These are tier-agnostic where possible — the moderate/high files reuse them. */

// ─── HStage — 220ms horizontal slide (12% travel) + crossfade ───────────
function HStage({ activeKey, direction, render }) {
  const [items, setItems] = React.useState([{ key: activeKey, phase: 'idle' }]);
  const prev = React.useRef(activeKey);
  React.useEffect(() => {
    if (activeKey === prev.current) return;
    const from = prev.current;
    prev.current = activeKey;
    setItems([{ key: from, phase: 'leaving' }, { key: activeKey, phase: 'entering' }]);
    const t = setTimeout(() => setItems([{ key: activeKey, phase: 'idle' }]), 240);
    return () => clearTimeout(t);
  }, [activeKey]);
  return (
    <div style={{ position: 'absolute', inset: 0, overflow: 'hidden' }}>
      {items.map((it) => {
        const fwd = direction >= 0;
        let animation = 'none';
        if (it.phase === 'entering') animation = `${fwd ? 'mh-enter-fwd' : 'mh-enter-back'} var(--dur-base) var(--ease-out) both`;
        if (it.phase === 'leaving') animation = `${fwd ? 'mh-leave-fwd' : 'mh-leave-back'} var(--dur-base) var(--ease-out) both`;
        return (
          <div key={it.key} style={{ position: 'absolute', inset: 0, animation, zIndex: it.phase === 'leaving' ? 1 : 2 }}>
            {render(it.key)}
          </div>
        );
      })}
    </div>
  );
}

// ─── Screen — full-bleed column; scroll area + optional pinned footer ───
//   `footer` clears the home indicator; scroll content gets bottom clearance.
function Screen({ children, footer, scrollRef, onScroll, bg = 'var(--bg)' }) {
  return (
    <div style={{ position: 'absolute', inset: 0, background: bg, display: 'flex', flexDirection: 'column' }}>
      <div ref={scrollRef} onScroll={onScroll} style={{ flex: 1, overflowY: 'auto', WebkitOverflowScrolling: 'touch', position: 'relative' }}>
        {children}
      </div>
      {footer && <div style={{ flexShrink: 0 }}>{footer}</div>}
    </div>
  );
}

// ─── Top nav (back chevron + centered title), clears the status bar ─────
function HNav({ title, onBack, right, light = false }) {
  const fg = light ? '#fff' : 'var(--fg-1)';
  return (
    <div style={{
      height: 44, paddingTop: 52, flexShrink: 0,
      display: 'grid', gridTemplateColumns: '44px 1fr 44px', alignItems: 'center',
      paddingLeft: 8, paddingRight: 8,
    }}>
      <div>{onBack && (
        <button onClick={onBack} aria-label="Back" style={{ background: 'transparent', border: 0, color: fg, width: 44, height: 44, display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer' }}>
          <Icon name="chevron-left" size={26}/>
        </button>
      )}</div>
      <div style={{ font: 'var(--type-h2)', textAlign: 'center', color: fg }}>{title}</div>
      <div style={{ display: 'flex', justifyContent: 'flex-end' }}>{right}</div>
    </div>
  );
}

// ─── Bottom tab bar — config-driven for tier-specific tab variation ─────
//   SYSTEM RULE: Home / Care / Profile are tier-SHARED (always present, same
//   icons). The 2nd slot is tier-CONDITIONAL. Each tier passes its own `tabs`
//   list as (id, label, icon) tuples via TIER_TABS or a custom array, so the
//   icon-missing class of bug can't recur — there is one render path.
const TAB_HOME    = { id: 'home',    label: 'Home',    icon: 'home' };
const TAB_CARE    = { id: 'care',    label: 'Care',    icon: 'heart' };
const TAB_PROFILE = { id: 'profile', label: 'Profile', icon: 'user' };
// Tier-conditional 2nd-slot presets:
const TAB_SLOT2 = {
  healthy:  { id: 'challenges', label: 'Challenges', icon: 'award' },     // trophy/laurel
  moderate: { id: 'learn',      label: 'Learn',      icon: 'book-open' }, // short-form education
  // high: TBD — add the high-risk variant here when File 5 lands.
};
// Convenience: assemble the 4-tab list for a given tier.
function tierTabs(tier) {
  return [TAB_HOME, TAB_SLOT2[tier], TAB_CARE, TAB_PROFILE].filter(Boolean);
}

function TierTabBar({ tabs, active = 'home', onChange = () => {} }) {
  return (
    <div style={{ padding: '8px 12px 30px', background: 'linear-gradient(180deg, rgba(250,248,245,0) 0%, var(--bg) 30%)' }}>
      <div style={{
        background: 'rgba(250, 248, 245, 0.9)',
        backdropFilter: 'blur(14px) saturate(160%)', WebkitBackdropFilter: 'blur(14px) saturate(160%)',
        borderRadius: 22, border: '1px solid var(--border-subtle)',
        padding: '9px 6px', display: 'flex', justifyContent: 'space-around',
        boxShadow: 'var(--shadow-s)',
      }}>
        {tabs.map(t => (
          <button key={t.id} onClick={() => onChange(t.id)} style={{
            background: 'transparent', border: 0, cursor: 'pointer',
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3, padding: '4px 12px',
            color: active === t.id ? 'var(--amber-600)' : 'var(--fg-3)',
          }}>
            <Icon name={t.icon} size={24} strokeWidth={active === t.id ? 2 : 1.75}/>
            <div style={{ font: 'var(--type-caption)', fontWeight: active === t.id ? 600 : 500 }}>{t.label}</div>
          </button>
        ))}
      </div>
    </div>
  );
}

// Thin tier wrapper — Healthy (Home / Challenges / Care / Profile)
function HealthyTabBar({ active = 'home', onChange = () => {} }) {
  return <TierTabBar tabs={tierTabs('healthy')} active={active} onChange={onChange}/>;
}

// ─── CheckCircle — sage (earned/pass) or stone (locked) ─────────────────
function CheckCircle({ size = 28, tone = 'sage' }) {
  const map = {
    sage: { bg: 'var(--sage-50)', fg: 'var(--sage-600)' },
    amber: { bg: 'var(--amber-50)', fg: 'var(--amber-600)' },
    stone: { bg: 'var(--stone-100)', fg: 'var(--stone-400)' },
  };
  const c = map[tone];
  return (
    <div style={{ width: size, height: size, borderRadius: '50%', background: c.bg, color: c.fg, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
      {tone === 'stone' ? <Icon name="lock" size={size * 0.5} strokeWidth={2}/> : <Icon name="check" size={size * 0.58} strokeWidth={2.6}/>}
    </div>
  );
}

// ─── ProgressBar ────────────────────────────────────────────────────────
function ProgressBar({ value, max = 100, color = 'var(--amber-500)', track = 'var(--stone-200)', height = 8 }) {
  const pct = Math.max(0, Math.min(1, max ? value / max : 0)) * 100;
  return (
    <div style={{ height, borderRadius: height / 2, background: track, overflow: 'hidden', width: '100%' }}>
      <div style={{ width: pct + '%', height: '100%', background: color, borderRadius: height / 2, transition: 'width var(--dur-slow) var(--ease-out)' }}/>
    </div>
  );
}

// ─── ToothIcon — kit has no tooth; minimal line glyph ───────────────────
function ToothIcon({ size = 20, color = 'currentColor' }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" style={{ display: 'block' }}>
      <path d="M7 3.5C5 3.5 3.5 5 3.5 7.5c0 2 .8 3 1.2 5 .3 1.6.4 4 .8 5.6.2 1 .6 1.9 1.3 1.9.9 0 1.1-1 1.4-2.4.3-1.6.5-3.1 1.8-3.1s1.5 1.5 1.8 3.1c.3 1.4.5 2.4 1.4 2.4.7 0 1.1-.9 1.3-1.9.4-1.6.5-4 .8-5.6.4-2 1.2-3 1.2-5C19.5 5 18 3.5 16 3.5c-1.6 0-2.4.9-4 .9s-2.4-.9-4-.9z"/>
    </svg>
  );
}

// ─── Avatar — initials in a tinted circle ───────────────────────────────
function Avatar({ initials, size = 44, bg = 'var(--amber-500)', fg = '#fff' }) {
  return (
    <div style={{ width: size, height: size, borderRadius: '50%', background: bg, color: fg, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', font: `600 ${Math.round(size * 0.4)}px/1 var(--font-sans)` }}>
      {initials}
    </div>
  );
}

// ─── StatTile — number (serif) + label, for stat grids ──────────────────
function StatTile({ value, label, accent = 'var(--fg-1)', serif = true }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
      <div style={{ font: serif ? '600 26px/1 var(--font-serif)' : '700 24px/1 var(--font-sans)', color: accent, letterSpacing: 'var(--tracking-tight)' }}>{value}</div>
      <div style={{ font: 'var(--type-body-s)', color: 'var(--fg-3)' }}>{label}</div>
    </div>
  );
}

// ─── Overline + section heading helpers ─────────────────────────────────
function SectionHeading({ children, style = {} }) {
  return <div style={{ font: 'var(--type-h3)', color: 'var(--fg-1)', marginBottom: 12, ...style }}>{children}</div>;
}

// ─── TrustFooter ────────────────────────────────────────────────────────
function TrustFooter({ style = {} }) {
  return (
    <div style={{ textAlign: 'center', padding: '8px 0', ...style }}>
      <div className="overline" style={{ color: 'var(--fg-3)' }}>HIPAA compliant · Secure results · Trusted partners</div>
    </div>
  );
}

// ─── XP / streak pill ───────────────────────────────────────────────────
function StatPill({ icon, children, bg = 'var(--amber-50)', fg = 'var(--amber-700)' }) {
  return (
    <div style={{ display: 'inline-flex', alignItems: 'center', gap: 5, padding: '4px 10px', borderRadius: 'var(--radius-pill)', background: bg, color: fg, font: '600 12px/1.2 var(--font-sans)', whiteSpace: 'nowrap' }}>
      {icon && <Icon name={icon} size={13} strokeWidth={2}/>}
      {children}
    </div>
  );
}

Object.assign(window, { HStage, Screen, HNav, TierTabBar, tierTabs, HealthyTabBar, CheckCircle, ProgressBar, ToothIcon, Avatar, StatTile, SectionHeading, TrustFooter, StatPill });
