// Loop — small UI atoms shared by all screens.
// Exports (window): Avatar, Pill, KindGlyph, Sparkline, ShimmerDot, RingHero,
//                   StackHero, NumberHero, GradientHero, TabBar, BackHeader,
//                   ScreenScroll, Hairline

const { useEffect, useRef, useState } = React;

function Avatar({ p, size = 40, dark }) {
  if (!p) return null;
  return (
    <div style={{
      width: size, height: size, borderRadius: size / 2,
      background: p.tint, color: '#3A3A3A',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontFamily: '-apple-system, system-ui', fontWeight: 600,
      fontSize: size * 0.36, letterSpacing: 0.2,
      boxShadow: dark ? 'inset 0 0 0 0.5px rgba(255,255,255,0.06)' : 'inset 0 0 0 0.5px rgba(0,0,0,0.04)',
      flexShrink: 0,
    }}>{p.init}</div>
  );
}

function Pill({ children, color, soft, dark, style }) {
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 5,
      padding: '3px 9px', borderRadius: 999,
      background: soft || (dark ? 'rgba(255,255,255,0.06)' : 'rgba(20,20,20,0.045)'),
      color: color || (dark ? 'rgba(255,255,255,0.78)' : 'rgba(27,27,31,0.7)'),
      fontFamily: '-apple-system, system-ui', fontSize: 12, fontWeight: 540,
      letterSpacing: 0.05,
      ...style,
    }}>{children}</span>
  );
}

function Hairline({ T, style }) {
  return <div style={{ height: 0.5, background: T.hairline, ...style }} />;
}

// Tiny per-kind glyph. Hand-drawn, calm, no emoji.
function KindGlyph({ kind, color, size = 14 }) {
  const s = { width: size, height: size, display: 'block' };
  switch (kind) {
    case 'reply':
      return <svg viewBox="0 0 16 16" style={s}><path d="M6 4 L2.5 7.5 L6 11 M3 7.5 H10.5 A3 3 0 0 1 13.5 10.5 V12" stroke={color} strokeWidth="1.4" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>;
    case 'thanks':
      return <svg viewBox="0 0 16 16" style={s}><path d="M8 13 L3 8.2 A2.8 2.8 0 0 1 8 4.8 A2.8 2.8 0 0 1 13 8.2 Z" stroke={color} strokeWidth="1.4" fill="none" strokeLinejoin="round"/></svg>;
    case 'schedule':
      return <svg viewBox="0 0 16 16" style={s}><rect x="2.5" y="3.5" width="11" height="10" rx="2" stroke={color} strokeWidth="1.4" fill="none"/><path d="M2.5 6.5 H13.5 M5 2.2 V4.6 M11 2.2 V4.6" stroke={color} strokeWidth="1.4" strokeLinecap="round"/></svg>;
    case 'approve':
      return <svg viewBox="0 0 16 16" style={s}><path d="M3.5 8.5 L6.5 11.5 L12.5 5" stroke={color} strokeWidth="1.6" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>;
    case 'followup':
      return <svg viewBox="0 0 16 16" style={s}><circle cx="8" cy="8" r="5.2" stroke={color} strokeWidth="1.4" fill="none"/><path d="M8 5.2 V8.2 L10 9.5" stroke={color} strokeWidth="1.4" fill="none" strokeLinecap="round"/></svg>;
    default:
      return <svg viewBox="0 0 16 16" style={s}><circle cx="8" cy="8" r="2.2" fill={color}/></svg>;
  }
}

function ShimmerDot({ T, size = 6 }) {
  return (
    <span style={{
      display: 'inline-block', width: size, height: size, borderRadius: size,
      background: `radial-gradient(circle, ${T.accent} 0%, ${T.accent}00 70%)`,
      boxShadow: `0 0 8px ${T.accent}80`,
      animation: 'loop-shimmer 2.4s ease-in-out infinite',
    }} />
  );
}

// Hero — ring (Activity-inspired)
function RingHero({ T, cleared, total, minutes }) {
  const pct = total === 0 ? 1 : cleared / total;
  const r = 78;
  const c = 2 * Math.PI * r;
  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '8px 0' }}>
      <svg width="200" height="200" viewBox="0 0 200 200">
        <defs>
          <linearGradient id="ringGrad" x1="0" y1="0" x2="1" y2="1">
            <stop offset="0%" stopColor={T.accent} stopOpacity="0.9"/>
            <stop offset="100%" stopColor={T.accent} stopOpacity="0.55"/>
          </linearGradient>
        </defs>
        <circle cx="100" cy="100" r={r} stroke={T.hairline} strokeWidth="14" fill="none"/>
        <circle cx="100" cy="100" r={r}
          stroke="url(#ringGrad)" strokeWidth="14" fill="none"
          strokeLinecap="round"
          strokeDasharray={`${c * pct} ${c}`}
          transform="rotate(-90 100 100)"
          style={{ transition: 'stroke-dasharray 700ms cubic-bezier(.2,.8,.2,1)' }}
        />
        <text x="100" y="96" textAnchor="middle"
          style={{ fontFamily: T.fontSerif, fontSize: 48, fontWeight: 400, fill: T.text, letterSpacing: -1 }}>
          {total - cleared}
        </text>
        <text x="100" y="118" textAnchor="middle"
          style={{ fontFamily: T.fontSans, fontSize: 12, fontWeight: 540, fill: T.textSub, letterSpacing: 0.6, textTransform: 'uppercase' }}>
          loops left
        </text>
        <text x="100" y="138" textAnchor="middle"
          style={{ fontFamily: T.fontSans, fontSize: 12, fontWeight: 500, fill: T.textMuted }}>
          ~{minutes} min
        </text>
      </svg>
    </div>
  );
}

function NumberHero({ T, cleared, total, minutes }) {
  return (
    <div style={{ padding: '24px 6px 18px' }}>
      <div style={{ fontFamily: T.fontSerif, fontSize: 88, lineHeight: '88px', color: T.text, letterSpacing: -2.5, fontWeight: 400 }}>
        {total - cleared}
      </div>
      <div style={{ fontFamily: T.fontSans, fontSize: 17, color: T.textSub, marginTop: 6, lineHeight: 1.4 }}>
        small loops to clear · about {minutes} minutes
      </div>
    </div>
  );
}

function GradientHero({ T, cleared, total, minutes }) {
  return (
    <div style={{
      borderRadius: 28, padding: '28px 22px 24px', marginTop: 4,
      background: T.dark
        ? `radial-gradient(120% 100% at 0% 0%, ${T.accent}40 0%, transparent 55%), linear-gradient(160deg, ${T.bgElev} 0%, #0F1115 100%)`
        : `radial-gradient(120% 100% at 0% 0%, ${T.accentSoft} 0%, transparent 60%), linear-gradient(160deg, #FFFFFF 0%, #F2EFE6 100%)`,
      boxShadow: T.cardShadow,
      border: `0.5px solid ${T.cardEdge}`,
      position: 'relative', overflow: 'hidden',
    }}>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 10 }}>
        <div style={{ fontFamily: T.fontSerif, fontSize: 64, lineHeight: '64px', color: T.text, letterSpacing: -1.6 }}>
          {total - cleared}
        </div>
        <div style={{ fontFamily: T.fontSans, fontSize: 15, color: T.textSub }}>
          loops · ~{minutes} min
        </div>
      </div>
      <div style={{ fontFamily: T.fontSerif, fontSize: 22, lineHeight: 1.3, color: T.text, marginTop: 14, fontWeight: 400, maxWidth: 280 }}>
        Most are under two minutes. Start anywhere.
      </div>
    </div>
  );
}

function StackHero({ T, cleared, total, minutes, peek }) {
  const cards = peek.slice(0, 3);
  return (
    <div style={{ padding: '4px 0 0' }}>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
        <div style={{ fontFamily: T.fontSerif, fontSize: 56, lineHeight: '56px', color: T.text, letterSpacing: -1.4 }}>
          {total - cleared}
        </div>
        <div style={{ fontFamily: T.fontSans, fontSize: 14, color: T.textSub }}>· {minutes} min</div>
      </div>
      <div style={{ fontFamily: T.fontSans, fontSize: 14, color: T.textMuted, marginTop: 4, marginBottom: 14 }}>
        next up
      </div>
      <div style={{ position: 'relative', height: 84 }}>
        {cards.map((c, i) => (
          <div key={c.id} style={{
            position: 'absolute', left: i * 8, right: i * 8, top: i * 8,
            background: T.card, borderRadius: 16,
            border: `0.5px solid ${T.cardEdge}`,
            boxShadow: T.cardShadow,
            padding: '12px 14px',
            opacity: 1 - i * 0.22,
            transform: `scale(${1 - i * 0.02})`,
          }}>
            {i === 0 && (
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <KindGlyph kind={c.kind} color={T.accent} size={13}/>
                <span style={{ fontFamily: T.fontSans, fontSize: 13, fontWeight: 560, color: T.text }}>{c.kindLabel}</span>
                <span style={{ fontFamily: T.fontSans, fontSize: 12, color: T.textMuted, marginLeft: 'auto' }}>{c.minutes} min</span>
              </div>
            )}
          </div>
        ))}
      </div>
    </div>
  );
}

// Bottom tab bar — glass, 5 tabs
function TabBar({ T, tab, setTab }) {
  const tabs = [
    { id: 'home',     label: 'Momentum',  icon: 'home' },
    { id: 'queue',    label: 'Queue',     icon: 'queue' },
    { id: 'summary',  label: 'Today',     icon: 'sum' },
    { id: 'people',   label: 'People',    icon: 'ppl' },
    { id: 'activity', label: 'Activity',  icon: 'act' },
  ];
  const icon = (k, on) => {
    const c = on ? T.accent : T.textMuted;
    if (k === 'home')  return <svg viewBox="0 0 24 24" width="22" height="22"><circle cx="12" cy="12" r="8.5" stroke={c} strokeWidth="1.6" fill="none"/><circle cx="12" cy="12" r="3.2" fill={c}/></svg>;
    if (k === 'queue') return <svg viewBox="0 0 24 24" width="22" height="22"><rect x="4" y="6" width="16" height="3" rx="1.2" fill={c}/><rect x="4" y="11" width="16" height="3" rx="1.2" fill={c} opacity="0.7"/><rect x="4" y="16" width="16" height="3" rx="1.2" fill={c} opacity="0.4"/></svg>;
    if (k === 'sum')   return <svg viewBox="0 0 24 24" width="22" height="22"><path d="M4 17 L9 11 L13 14 L20 6" stroke={c} strokeWidth="1.8" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>;
    if (k === 'ppl')   return <svg viewBox="0 0 24 24" width="22" height="22"><circle cx="9" cy="9" r="3.2" stroke={c} strokeWidth="1.6" fill="none"/><circle cx="16" cy="11" r="2.4" stroke={c} strokeWidth="1.6" fill="none"/><path d="M3 19 C4 16 7 14.5 9 14.5 C11 14.5 14 16 15 19" stroke={c} strokeWidth="1.6" fill="none" strokeLinecap="round"/></svg>;
    if (k === 'act')   return <svg viewBox="0 0 24 24" width="22" height="22"><path d="M3 12 H7 L9 7 L13 17 L15 12 H21" stroke={c} strokeWidth="1.6" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>;
  };
  return (
    <div style={{
      position: 'absolute', left: 12, right: 12, bottom: 12, zIndex: 30,
      borderRadius: 28, padding: '8px 6px 10px',
      background: T.dark ? 'rgba(20,22,28,0.78)' : 'rgba(255,255,255,0.78)',
      backdropFilter: 'blur(22px) saturate(180%)',
      WebkitBackdropFilter: 'blur(22px) saturate(180%)',
      border: `0.5px solid ${T.cardEdge}`,
      boxShadow: T.dark
        ? '0 10px 30px rgba(0,0,0,0.4)'
        : '0 10px 30px rgba(20,20,20,0.08)',
      display: 'flex', justifyContent: 'space-around', alignItems: 'center',
    }}>
      {tabs.map(t => (
        <button key={t.id} onClick={() => setTab(t.id)} style={{
          all: 'unset', cursor: 'pointer', display: 'flex', flexDirection: 'column',
          alignItems: 'center', gap: 2, padding: '6px 10px', borderRadius: 14, minWidth: 50,
        }}>
          {icon(t.icon, tab === t.id)}
          <span style={{
            fontFamily: T.fontSans, fontSize: 10, fontWeight: 580, letterSpacing: 0.15,
            color: tab === t.id ? T.accent : T.textMuted,
          }}>{t.label}</span>
        </button>
      ))}
    </div>
  );
}

function BackHeader({ T, title, onBack, trailing, topInset = 52 }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      padding: `${topInset + 6}px 16px 8px`,
    }}>
      <button onClick={onBack} style={{
        all: 'unset', cursor: 'pointer', color: T.accent,
        fontFamily: T.fontSans, fontSize: 17, fontWeight: 500,
        display: 'flex', alignItems: 'center', gap: 2,
      }}>
        <svg width="12" height="20" viewBox="0 0 12 20"><path d="M9 3 L3 10 L9 17" stroke={T.accent} strokeWidth="2.2" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
        <span style={{ marginLeft: 2 }}>{title || 'Back'}</span>
      </button>
      {trailing}
    </div>
  );
}

function ScreenScroll({ T, children, padBottom = 110, padTop = 52 }) {
  return (
    <div style={{
      position: 'absolute', inset: 0, overflow: 'auto',
      paddingTop: padTop,
      paddingBottom: padBottom,
      background: T.bg,
      WebkitOverflowScrolling: 'touch',
    }}>{children}</div>
  );
}

Object.assign(window, {
  Avatar, Pill, KindGlyph, ShimmerDot,
  RingHero, NumberHero, GradientHero, StackHero,
  TabBar, BackHeader, ScreenScroll, Hairline,
});
