// screens.jsx — Today (home), Setup, Complete, Journal, Atlas (body heat-map)

function relDay(iso) {
  const d = new Date(iso), now = new Date();
  const days = Math.round((now.setHours(0,0,0,0) - new Date(iso).setHours(0,0,0,0)) / 864e5);
  if (days === 0) return 'Today';
  if (days === 1) return 'Yesterday';
  if (days < 7) return d.toLocaleDateString(undefined, { weekday: 'long' });
  return d.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
}

// aggregate markers across sessions into a per-region heat object
function buildHeat(sessions) {
  const acc = {};
  sessions.forEach(s => (s.markers || []).forEach(m => {
    if (!acc[m.region]) acc[m.region] = { total: 0, sens: {} };
    const w = (m.intensity || 0) + 1;
    acc[m.region].total += w;
    acc[m.region].sens[m.sensationId] = (acc[m.region].sens[m.sensationId] || 0) + w;
  }));
  let max = 1;
  Object.values(acc).forEach(a => { max = Math.max(max, a.total); });
  const heat = {};
  Object.entries(acc).forEach(([rid, a]) => {
    const top = Object.entries(a.sens).sort((x, y) => y[1] - x[1])[0][0];
    heat[rid] = { hue: (MT_SENS_MAP[top] || {}).hue || '#36E8D2', weight: a.total / max, total: a.total, topSens: top };
  });
  return heat;
}

// ── Today ─────────────────────────────────────────────────────────
// last-30-days continuity grid + time-of-day rhythm
const MT_DAYPARTS = [
  { id: 'early', label: 'Early morning', range: [4, 8], icon: '☀' },
  { id: 'morning', label: 'Morning', range: [8, 12], icon: '☀' },
  { id: 'midday', label: 'Midday', range: [12, 17], icon: '☀' },
  { id: 'evening', label: 'Evening', range: [17, 21], icon: '☾' },
  { id: 'night', label: 'Night', range: [21, 28], icon: '☾' }, // 21–24 + 0–4 (wraps)
];
function dayPartOf(hr) {
  if (hr >= 4 && hr < 8) return 'early';
  if (hr >= 8 && hr < 12) return 'morning';
  if (hr >= 12 && hr < 17) return 'midday';
  if (hr >= 17 && hr < 21) return 'evening';
  return 'night';
}

function Last30({ sessions, streak }) {
  const C = MT_COLORS;
  // map day-string → { count, minutes }
  const byDay = React.useMemo(() => {
    const m = {};
    sessions.forEach(s => {
      const k = new Date(s.date).toDateString();
      if (!m[k]) m[k] = { count: 0, minutes: 0 };
      m[k].count++; m[k].minutes += s.duration || 0;
    });
    return m;
  }, [sessions]);
  const days = React.useMemo(() => Array.from({ length: 30 }, (_, i) => {
    const d = new Date(); d.setHours(0, 0, 0, 0); d.setDate(d.getDate() - (29 - i));
    const info = byDay[d.toDateString()];
    return { d, lit: !!info, minutes: info ? info.minutes : 0,
      label: d.toLocaleDateString(undefined, { month: 'short', day: 'numeric' }) };
  }), [byDay]);
  const satCount = days.filter(d => d.lit).length;

  // time-of-day distribution
  const parts = React.useMemo(() => {
    const counts = { early: 0, morning: 0, midday: 0, evening: 0, night: 0 };
    sessions.forEach(s => { counts[dayPartOf(new Date(s.date).getHours())]++; });
    return counts;
  }, [sessions]);
  const maxPart = Math.max(1, ...Object.values(parts));
  const topPart = Object.entries(parts).sort((a, b) => b[1] - a[1])[0];
  const topLabel = topPart[1] > 0 ? (MT_DAYPARTS.find(p => p.id === topPart[0]) || {}).label : null;
  const stats = React.useMemo(() => buildStats(sessions), [sessions]);
  const fmtH = (h) => h >= 10 ? Math.round(h) + 'h' : h.toFixed(1) + 'h';

  const dotColor = (m) => {
    if (!m) return 'transparent';
    const t = Math.min(1, m / 40); // 40min = full
    return `radial-gradient(circle, ${hexA(C.teal, 0.55 + t * 0.45)}, #1a8d80)`;
  };

  return (
    <MTPanel style={{ padding: '16px 18px', marginBottom: 16 }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <MTIcon name="today" size={17} color={C.teal} />
          <span style={{ fontSize: 14, color: C.inkDim }}>Last 30 days</span>
          {streak > 0 && (
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, marginLeft: 4, padding: '2px 9px', borderRadius: 999, background: hexA('#FF9E6B', 0.12), border: `1px solid ${hexA('#FF9E6B', 0.3)}` }}>
              <MTIcon name="flame" size={12} color="#FF9E6B" />
              <span style={{ fontSize: 11.5, color: '#FF9E6B', fontFamily: 'var(--mono)' }}>{streak}d</span>
            </span>
          )}
        </div>
        <span style={{ fontFamily: 'var(--mono)', fontSize: 13, color: C.teal }}>{satCount}<span style={{ color: C.inkFaint }}> / 30 sat</span></span>
      </div>

      {/* 30-day dot grid */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(15, 1fr)', gap: 7 }}>
        {days.map((d, i) => (
          <div key={i} title={`${d.label}${d.lit ? ' · ' + d.minutes + ' min' : ' · no sit'}`}
            style={{ aspectRatio: '1', borderRadius: 999, background: dotColor(d.minutes),
              border: `1px solid ${d.lit ? 'transparent' : C.inkGhost}`,
              boxShadow: d.lit ? `0 0 8px ${hexA(C.teal, 0.45)}` : 'none' }} />
        ))}
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 8, fontSize: 10, color: C.inkFaint, fontFamily: 'var(--mono)' }}>
        <span>30 days ago</span><span>today</span>
      </div>

      {/* lifetime stats row */}
      <div style={{ display: 'flex', gap: 8, marginTop: 16 }}>
        {[
          [stats.count, 'sittings', C.teal],
          [fmtH(stats.totalHours), 'total', C.teal],
          [stats.avgMin + 'm', 'avg sit', C.teal],
          [stats.bestStreak + 'd', 'best streak', '#FF9E6B'],
        ].map(([v, l, hue], i) => (
          <div key={i} style={{ flex: 1, textAlign: 'center', padding: '11px 4px', borderRadius: 13, background: 'rgba(255,255,255,0.025)', border: `1px solid ${C.inkGhost}` }}>
            <div style={{ fontFamily: 'var(--mono)', fontSize: 18, color: hue, lineHeight: 1 }}>{v}</div>
            <div style={{ fontSize: 10, color: C.inkFaint, marginTop: 5 }}>{l}</div>
          </div>
        ))}
      </div>

      {/* when you sit */}
      {topLabel && (
        <div style={{ marginTop: 18, paddingTop: 16, borderTop: `1px solid ${C.stroke}` }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <MTIcon name="timer" size={16} color={C.inkDim} />
              <span style={{ fontSize: 13.5, color: C.inkDim }}>When you sit</span>
            </div>
            <span style={{ fontSize: 12.5, color: C.teal }}>mostly {topLabel.toLowerCase()}</span>
          </div>
          <div style={{ display: 'flex', gap: 7, alignItems: 'flex-end', height: 50 }}>
            {MT_DAYPARTS.map(p => {
              const v = parts[p.id]; const on = p.id === topPart[0] && v > 0;
              return (
                <div key={p.id} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
                  <div style={{ width: '100%', display: 'flex', alignItems: 'flex-end', justifyContent: 'center', height: 32 }}>
                    <div style={{ width: '78%', maxWidth: 30, height: `${Math.max(8, (v / maxPart) * 100)}%`, borderRadius: 6,
                      background: v ? (on ? `linear-gradient(180deg, ${C.teal}, ${hexA(C.teal, 0.4)})` : hexA(C.teal, 0.28)) : 'rgba(255,255,255,0.05)',
                      boxShadow: on ? `0 0 10px ${hexA(C.teal, 0.5)}` : 'none' }} />
                  </div>
                  <span style={{ fontSize: 9, color: on ? C.teal : C.inkFaint, fontFamily: 'var(--mono)', textAlign: 'center', lineHeight: 1.2 }}>{p.label.split(' ')[0]}</span>
                </div>
              );
            })}
          </div>
          <div style={{ marginTop: 12, fontSize: 11.5, color: C.inkFaint, lineHeight: 1.5, textWrap: 'pretty', textAlign: 'center' }}>
            Sitting at the <span style={{ color: hexA(C.teal, 0.9) }}>same time and same place</span> each day builds the habit fastest — especially early in the practice.
          </div>
        </div>
      )}
    </MTPanel>
  );
}

// quick-start practice cycle — tap the pill to change what Quick start launches
const MT_QS_OPTIONS = [
  ['anapana_vipassana', 'Sweep'],
  ['anapana', 'Ānāpāna'],
  ['anapana_vipassana_metta', 'Full arc'],
  ['open', 'Open'],
  ['walking', 'Walking'],
  ['bhakti', 'Naam'],
  ['hybrid', 'Naam-scan'],
];
const MT_QS_KEY = 'mt_quickpractice_v1';

function TodayScreen({ sessions, onBegin, onQuickStart, onWitness, onOpenLife, onTeachings, streak, life, vp }) {
  const C = MT_COLORS;
  const [qp, setQp] = React.useState(() => {
    try { const v = localStorage.getItem(MT_QS_KEY); if (MT_QS_OPTIONS.some(o => o[0] === v)) return v; } catch (e) {}
    return 'anapana_vipassana';
  });
  const pickQp = (v) => { setQp(v); try { localStorage.setItem(MT_QS_KEY, v); } catch (e2) {} };
  const qpLabel = (MT_QS_OPTIONS.find(o => o[0] === qp) || MT_QS_OPTIONS[0])[1];
  const hr = new Date().getHours();
  const greet = hr < 5 ? 'Late stillness' : hr < 12 ? 'Good morning' : hr < 18 ? 'Good afternoon' : 'Good evening';

  return (
    <div style={{ padding: '8px 20px 120px' }}>
      <div style={{ marginTop: 8, marginBottom: 4 }}>
        <MTEyebrow>{new Date().toLocaleDateString(undefined, { weekday: 'long', month: 'long', day: 'numeric' })}</MTEyebrow>
      </div>
      <h1 style={{ font: '300 32px/1.1 var(--serif)', color: C.ink, margin: '4px 0 14px', letterSpacing: 0.2 }}>{greet}.</h1>

      {/* Goenka's vow of continuity — glowing rotating border */}
      <div style={{ position: 'relative', borderRadius: 16, padding: 1.5, marginBottom: 18, overflow: 'hidden' }}>
        <div style={{ position: 'absolute', top: '-60%', left: '-30%', width: '160%', height: '220%',
          background: `conic-gradient(from 0deg, transparent 0deg, ${hexA(MT_TRAD.vipassana.hue, 0.0)} 40deg, ${MT_TRAD.vipassana.hue} 90deg, ${hexA(MT_TRAD.vipassana.hue, 0.0)} 150deg, transparent 360deg)`,
          animation: 'mtSpin 5.5s linear infinite', pointerEvents: 'none' }} />
        <div style={{ position: 'relative', display: 'flex', alignItems: 'flex-start', gap: 10, padding: '12px 15px', borderRadius: 14.5,
          background: 'linear-gradient(160deg, rgba(10,26,32,0.96), rgba(7,16,24,0.97))' }}>
          <span style={{ color: MT_TRAD.vipassana.hue, fontSize: 20, lineHeight: 1, marginTop: 1 }}>“</span>
          <div>
            <div style={{ font: 'italic 300 15.5px/1.45 var(--serif)', color: C.ink, textWrap: 'pretty' }}>The continuity of practice is the secret of success.</div>
            <div style={{ fontSize: 11, color: C.inkFaint, fontFamily: 'var(--mono)', letterSpacing: 1, marginTop: 5 }}>S. N. GOENKA</div>
          </div>
        </div>
      </div>

      {/* sense of urgency — time remaining */}
      <LifeCard cfg={life} sessions={sessions} onOpen={onOpenLife} />

      {/* hero begin card */}
      <div onClick={onBegin} style={{ position: 'relative', borderRadius: 26, overflow: 'hidden', cursor: 'pointer',
        border: `1px solid ${C.tealLine}`, background: 'radial-gradient(120% 100% at 50% 0%, #0c2433 0%, #061521 70%)',
        padding: '22px 20px 20px', marginBottom: 16, minHeight: 220 }}>
        <ParticleField count={26} />
        <div style={{ position: 'absolute', right: -30, top: -10, width: 200, height: 240, opacity: 0.5, pointerEvents: 'none' }}>
          <BodyFigure interactive={false} breathing markers={[]} />
        </div>
        <div style={{ position: 'relative', zIndex: 2 }}>
          <MTEyebrow color={C.teal}>Today's sitting</MTEyebrow>
          <div style={{ font: '300 26px/1.2 var(--serif)', color: C.ink, margin: '10px 0 6px', maxWidth: 210 }}>
            Scan the body. Note what arises.
          </div>
          <div style={{ fontSize: 14, color: C.inkFaint, maxWidth: 200, lineHeight: 1.5, marginBottom: 64 }}>
            A slow sweep of attention, crown to feet — observing with equanimity.
          </div>
          <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
            <MTButton size="md" onClick={(e) => { e.stopPropagation(); onBegin(); }}>
              <MTIcon name="play" size={18} color="#022019" /> Begin practice
            </MTButton>
            {/* split button: quick-start action + practice selector, one pill */}
            <div onClick={(e) => e.stopPropagation()} style={{ display: 'inline-flex', alignItems: 'stretch', borderRadius: 999,
              border: `1px solid ${hexA(C.teal, 0.45)}`, overflow: 'hidden', background: 'rgba(54,232,210,0.07)' }}>
              <button onClick={() => onQuickStart(qp)} style={{ appearance: 'none', border: 'none', cursor: 'pointer', background: 'transparent',
                color: C.ink, display: 'inline-flex', alignItems: 'center', gap: 8, padding: '13px 14px 13px 18px', font: 'inherit', fontSize: 15, fontWeight: 500 }}>
                <MTIcon name="flame" size={17} color={C.teal} /> Quick start · {qpLabel}
              </button>
              <div style={{ position: 'relative', display: 'flex', alignItems: 'center', borderLeft: `1px solid ${hexA(C.teal, 0.3)}` }}>
                <select value={qp} onChange={(e) => pickQp(e.target.value)} title="Choose the Quick start practice"
                  style={{ appearance: 'none', WebkitAppearance: 'none', background: 'transparent', border: 'none', cursor: 'pointer',
                    color: 'transparent', width: 36, height: '100%', outline: 'none' }}>
                  {MT_QS_OPTIONS.map(([v, l]) => <option key={v} value={v} style={{ color: '#000' }}>{l}</option>)}
                </select>
                <span style={{ position: 'absolute', left: '50%', transform: 'translateX(-50%)', pointerEvents: 'none', color: C.teal, fontSize: 10 }}>▾</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* witness / teaching mode */}
      <div onClick={onWitness} style={{ position: 'relative', borderRadius: 22, overflow: 'hidden', cursor: 'pointer',
        border: `1px solid ${hexA('#B49CFF', 0.32)}`, background: 'linear-gradient(110deg, rgba(28,22,46,0.7), rgba(10,18,28,0.6))',
        padding: '16px 18px', marginBottom: 16, display: 'flex', alignItems: 'center', gap: 14 }}>
        <div style={{ width: 46, height: 70, flexShrink: 0, position: 'relative' }}>
          <BodyFigure interactive={false} dim markers={[{ region: 'chest', sensationId: 'tension', intensity: 1, i: 0 }, { region: 'head', sensationId: 'tingling', intensity: 1, i: 0 }]} />
          <span style={{ position: 'absolute', top: -2, left: '50%', transform: 'translateX(-50%)', width: 7, height: 7, borderRadius: 7, background: '#B49CFF', boxShadow: '0 0 8px #B49CFF' }} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <MTEyebrow color="#B49CFF">Learn meditation</MTEyebrow>
          <div style={{ font: '300 19px/1.2 var(--serif)', color: C.ink, margin: '6px 0 4px' }}>Learn from the masters</div>
          <div style={{ fontSize: 13, color: C.inkFaint, lineHeight: 1.45 }}>Read the method, then watch Dipa Ma &amp; Goenka meet what arises — and note it pass.</div>
        </div>
        <MTIcon name="chevR" size={20} color={C.inkFaint} />
      </div>

      {/* last 30 days continuity + when you sit */}
      <Last30 sessions={sessions} streak={streak} />

      <div style={{ marginTop: 28, padding: '0 6px' }}>
        <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 14 }}>
          <MTEyebrow>A teaching for today · tap for another</MTEyebrow>
        </div>
        <QuoteBlock shuffle align="center" size={17} />
        <div style={{ display: 'flex', justifyContent: 'center', marginTop: 18 }}>
          <button onClick={onTeachings} style={{ appearance: 'none', cursor: 'pointer', background: 'rgba(255,255,255,0.03)', border: `1px solid ${C.inkGhost}`, borderRadius: 999, padding: '9px 16px', color: C.inkDim, fontSize: 13, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 7, fontFamily: 'var(--sans)' }}>
            <MTIcon name="quotes" size={15} color={C.teal} /> Browse all teachings
          </button>
        </div>
      </div>
    </div>
  );
}

// reusable session summary card
function SessionCard({ s, compact, onClick }) {
  const C = MT_COLORS;
  const heat = buildHeat([s]);
  const emoHue = '#7CF0DC';
  return (
    <MTPanel onClick={onClick} style={{ padding: 14, display: 'flex', gap: 14, alignItems: 'stretch' }}>
      <div style={{ width: 58, flexShrink: 0, height: compact ? 110 : 128, display: 'grid', placeItems: 'center' }}>
        <BodyFigure interactive={false} heat={heat} markers={s.markers} dim />
      </div>
      <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
          <span style={{ fontFamily: 'var(--mono)', fontSize: 13, color: C.teal }}>{s.duration} min</span>
          <span style={{ width: 3, height: 3, borderRadius: 3, background: C.inkGhost }} />
          <span style={{ fontSize: 13, color: C.inkFaint }}>{s.markers.length} noted</span>
          {s.emotion && <span style={{ marginLeft: 'auto', fontSize: 11, color: C.inkDim, border: `1px solid ${C.inkGhost}`, padding: '3px 9px', borderRadius: 999 }}>{s.emotion}</span>}
        </div>
        <div style={{ font: 'italic 300 15px/1.45 var(--serif)', color: C.inkDim, textWrap: 'pretty',
          display: '-webkit-box', WebkitLineClamp: compact ? 2 : 4, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>
          {s.reflection || 'No reflection noted.'}
        </div>
        <div style={{ display: 'flex', gap: 5, marginTop: 'auto', paddingTop: 10, flexWrap: 'wrap' }}>
          {[...new Set(s.markers.map(m => m.sensationId))].slice(0, 4).map(id => (
            <span key={id} style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 11, color: C.inkDim }}>
              <span style={{ width: 7, height: 7, borderRadius: 7, background: (MT_SENS_MAP[id] || {}).hue }} />
              {(MT_SENS_MAP[id] || {}).label}
            </span>
          ))}
        </div>
      </div>
    </MTPanel>
  );
}

// small "share this exact practice" control on the Setup screen —
// copies a deep link like https://meditate.ajinkya.ai/#/sit/metta/20
function ShareSitLink({ dur, path, practice }) {
  const C = MT_COLORS;
  const [copied, setCopied] = React.useState(false);
  const token = path === 'bhakti' ? 'naam' : path === 'hybrid' ? 'naamscan'
    : ({ anapana: 'anapana', anapana_vipassana: 'sweep', anapana_vipassana_metta: 'metta', open: 'open', walking: 'walking' }[practice] || 'sweep');
  const url = `${window.location.origin}/#/sit/${token}/${dur}`;
  const copy = () => {
    try {
      navigator.clipboard.writeText(url).then(() => { setCopied(true); setTimeout(() => setCopied(false), 2200); }).catch(() => {});
    } catch (e) {}
  };
  return (
    <button onClick={copy} style={{ appearance: 'none', background: 'none', border: 'none', cursor: 'pointer',
      display: 'flex', alignItems: 'center', gap: 8, margin: '18px auto 0', padding: '4px 8px',
      color: copied ? C.teal : C.inkFaint, fontSize: 13, fontFamily: 'var(--mono)', letterSpacing: 0.4 }}>
      <MTIcon name="chevR" size={14} color={copied ? C.teal : C.inkFaint} />
      {copied ? 'Link copied — send it to someone' : 'Copy a link to this practice'}
    </button>
  );
}

// ── Setup ─────────────────────────────────────────────────────────
function SetupScreen({ onStart, onBack, pose, setPose, preset, onRelax }) {
  const C = MT_COLORS;
  const [dur, setDur] = React.useState((preset && preset.duration) || 20);
  const [practice, setPractice] = React.useState((preset && preset.practice) || 'anapana_vipassana');
  const [path, setPath] = React.useState((preset && preset.path) || 'insight');
  const [deity, setDeity] = React.useState('vitthala');
  const [whyOpen, setWhyOpen] = React.useState(false);
  const [speed, setSpeed] = React.useState(95);
  const [direction, setDirection] = React.useState('down');
  const [ambient, setAmbient] = React.useState(true);
  const [voice, setVoice] = React.useState(true);
  const [ambientVol, setAmbientVol] = React.useState(55);
  const [voiceVol, setVoiceVol] = React.useState(100);
  const [cueEvery, setCueEvery] = React.useState(5);   // spoken-cue repeat after instructions; 0 = off
  React.useEffect(() => {
    const onKey = (e) => {
      const tag = e.target && e.target.tagName;
      if (e.key === 'Escape' && tag !== 'INPUT' && tag !== 'TEXTAREA' && tag !== 'SELECT') onBack();
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
    // eslint-disable-next-line
  }, [onBack]);
  const [intervalBell, setIntervalBell] = React.useState(0);
  const [reminderType, setReminderType] = React.useState('gong');
  const [parked, setParked] = React.useState(() => mtLoadParked());
  const durs = React.useMemo(() => {
    const base = [10, 15, 20, 30, 45, 60];
    return base.includes(dur) ? base : [...base, dur].sort((a, b) => a - b);
  }, [dur]);
  const hasSweep = path === 'hybrid' || ((path === 'insight') && (practice === 'anapana_vipassana' || practice === 'anapana_vipassana_metta' || practice === 'vipassana'));
  const dirs = [
    { id: 'down', g: '↓', t: 'Top → bottom' },
    { id: 'up', g: '↑', t: 'Bottom → top' },
    { id: 'right', g: '→', t: 'Left → right' },
    { id: 'left', g: '←', t: 'Right → left' },
    { id: 'mix', g: '↕', t: 'Mix · both ways' },
    { id: 'random', g: '✦', t: 'Random' },
  ];
  const speeds = [{ s: 150, t: 'Slow' }, { s: 95, t: 'Medium' }, { s: 60, t: 'Brisk' }, { s: 30, t: 'Quick' }];
  return (
    <div style={{ padding: '8px 20px 40px', minHeight: '100%', display: 'flex', flexDirection: 'column' }}>
      <button onClick={onBack} style={{ appearance: 'none', background: 'none', border: 'none', color: C.inkDim, display: 'flex', alignItems: 'center', gap: 4, cursor: 'pointer', marginBottom: 18, padding: 0, fontSize: 15 }}>
        <MTIcon name="chevL" size={20} /> Today
      </button>
      <h1 style={{ font: '300 30px/1.1 var(--serif)', color: C.ink, margin: '0 0 14px' }}>Prepare to sit</h1>

      <div style={{ display: 'flex', gap: 11, alignItems: 'flex-start', padding: '13px 15px', marginBottom: 18, borderRadius: 14,
        background: hexA(C.teal, 0.06), border: `1px solid ${hexA(C.teal, 0.22)}` }}>
        <div style={{ width: 30, height: 30, borderRadius: 9, flexShrink: 0, display: 'grid', placeItems: 'center', background: hexA(C.teal, 0.12), color: C.teal }}>
          <MTIcon name="atlas" size={17} />
        </div>
        <div style={{ fontSize: 13, color: C.inkDim, lineHeight: 1.5, textWrap: 'pretty' }}>
          The body keeps the score — stress is stored in it as sensation. It releases only when you observe those sensations and emotions objectively, untying the knots held deep in the body and the subconscious mind.
        </div>
      </div>

      <div style={{ marginBottom: 24, paddingBottom: 4 }}>
        <QuoteBlock quote={React.useMemo(() => mtQuotePhase('start'), [])} shuffle align="left" size={15.5} />
      </div>

      {path !== 'relax' && (<React.Fragment>
      <MTEyebrow>Duration</MTEyebrow>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 9, margin: '12px 0 26px' }}>
        {durs.map(d => (
          <button key={d} onClick={() => { setDur(d); setIntervalBell(b => (b > 0 && b >= d) ? 0 : b); }} style={{
            appearance: 'none', cursor: 'pointer', font: 'inherit', width: 'calc(33.33% - 6px)',
            padding: '16px 0', borderRadius: 16, border: `1px solid ${dur === d ? C.teal : C.inkGhost}`,
            background: dur === d ? 'rgba(54,232,210,0.1)' : 'rgba(255,255,255,0.02)', color: dur === d ? C.ink : C.inkDim,
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2,
          }}>
            <span style={{ fontFamily: 'var(--mono)', fontSize: 22, fontWeight: 500 }}>{d}</span>
            <span style={{ fontSize: 11, color: C.inkFaint }}>min</span>
          </button>
        ))}
      </div>

      <MTEyebrow>The figure</MTEyebrow>
      <div style={{ display: 'flex', gap: 10, margin: '12px 0 26px' }}>
        {[
          { id: 'standing', t: 'Energy body', d: 'Upright wireframe', icon: 'person' },
          { id: 'seated', t: 'Seated posture', d: 'Cross-legged, lotus', icon: 'lotus' },
        ].map(o => {
          const on = pose === o.id;
          return (
            <button key={o.id} onClick={() => setPose(o.id)} style={{
              flex: 1, appearance: 'none', cursor: 'pointer', font: 'inherit', textAlign: 'left',
              padding: '14px 14px', borderRadius: 16, border: `1px solid ${on ? C.teal : C.inkGhost}`,
              background: on ? 'rgba(54,232,210,0.08)' : 'rgba(255,255,255,0.02)',
              display: 'flex', flexDirection: 'column', gap: 10,
            }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <div style={{ width: 38, height: 38, borderRadius: 11, display: 'grid', placeItems: 'center', background: on ? 'rgba(54,232,210,0.14)' : 'rgba(255,255,255,0.03)', color: on ? C.teal : C.inkDim }}>
                  <MTIcon name={o.icon} size={20} />
                </div>
                <span style={{ width: 17, height: 17, borderRadius: 999, border: `1px solid ${on ? C.teal : C.inkGhost}`, display: 'grid', placeItems: 'center' }}>
                  {on && <span style={{ width: 9, height: 9, borderRadius: 9, background: C.teal }} />}
                </span>
              </div>
              <div>
                <div style={{ fontSize: 15, fontWeight: 600, color: C.ink }}>{o.t}</div>
                <div style={{ fontSize: 12, color: C.inkFaint, marginTop: 2 }}>{o.d}</div>
              </div>
            </button>
          );
        })}
      </div>

      </React.Fragment>)}

      <MTEyebrow>Path</MTEyebrow>
      <div style={{ display: 'flex', gap: 6, padding: 4, borderRadius: 16, background: 'rgba(255,255,255,0.03)', border: `1px solid ${C.inkGhost}`, margin: '12px 0 12px' }}>
        {['insight', 'bhakti', 'hybrid', 'relax'].map(id => {
          const P = MT_PATHS[id]; const on = path === id;
          return (
            <button key={id} onClick={() => setPath(id)} style={{
              flex: 1, appearance: 'none', cursor: 'pointer', font: 'inherit', padding: '10px 4px', borderRadius: 12, border: 'none',
              background: on ? hexA(P.hue, 0.16) : 'transparent', color: on ? C.ink : C.inkDim,
              display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3,
            }}>
              <span style={{ fontSize: 14.5, fontWeight: 700 }}>{P.label}</span>
              <span style={{ fontSize: 9.5, color: on ? P.hue : C.inkFaint, fontFamily: 'var(--mono)', letterSpacing: 0.3, textAlign: 'center', lineHeight: 1.2 }}>{P.sub}</span>
            </button>
          );
        })}
      </div>
      <div style={{ fontSize: 13, color: C.inkDim, lineHeight: 1.5, marginBottom: 8, textWrap: 'pretty' }}>{MT_PATHS[path].blurb}</div>
      <button onClick={() => setWhyOpen(o => !o)} style={{ appearance: 'none', background: 'none', border: 'none', cursor: 'pointer', color: MT_PATHS[path].hue, fontSize: 12.5, fontWeight: 600, padding: 0, fontFamily: 'var(--sans)', marginBottom: whyOpen ? 12 : 22 }}>
        {whyOpen ? '− Hide' : '+ How insight & devotion both liberate'}
      </button>
      {whyOpen && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 22 }}>
          <div style={{ padding: '13px 15px', borderRadius: 14, background: hexA(MT_TRAD.vipassana.hue, 0.06), border: `1px solid ${hexA(MT_TRAD.vipassana.hue, 0.25)}` }}>
            <div style={{ fontSize: 13, fontWeight: 700, color: MT_TRAD.vipassana.hue, marginBottom: 5 }}>Insight — purify by observing</div>
            <div style={{ fontSize: 12.5, color: C.inkDim, lineHeight: 1.5, textWrap: 'pretty' }}>You watch each sensation objectively, without reacting. Old impurities surface, are seen, and dissolve. The ego thins through clear seeing — nothing is added.</div>
          </div>
          <div style={{ padding: '13px 15px', borderRadius: 14, background: hexA(MT_TRAD.bhakti.hue, 0.06), border: `1px solid ${hexA(MT_TRAD.bhakti.hue, 0.25)}` }}>
            <div style={{ fontSize: 13, fontWeight: 700, color: MT_TRAD.bhakti.hue, marginBottom: 5 }}>Bhakti — fill, and the ego is pushed out</div>
            <div style={{ fontSize: 12.5, color: C.inkDim, lineHeight: 1.5, textWrap: 'pretty' }}>You fill the mind completely with the divine Name. There is no room left for ego or craving — they are crowded out by love and surrender. Nothing is observed; the heart is simply filled.</div>
          </div>
          <div style={{ fontSize: 12, color: C.inkFaint, lineHeight: 1.55, textWrap: 'pretty', padding: '0 2px' }}>
            Two doors to the same room: one empties the mind by seeing through impurity, the other fills it so impurity has nowhere to live. Both quiet the ego — and both lead to the freedom of mind.
          </div>
        </div>
      )}

      {path === 'insight' && (<React.Fragment>
      <MTEyebrow>Practice</MTEyebrow>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10, margin: '12px 0 0' }}>
        {[
          { id: 'anapana', t: 'Ānāpāna', d: 'Breath only — attention rests at the nostrils. The foundation.', tag: 'breath', hue: MT_TRAD.anapana.hue },
          { id: 'anapana_vipassana', t: 'Ānāpāna → Vipassanā', d: 'Settle on the breath, then sweep sensation through the body.', tag: 'Goenka', hue: MT_TRAD.vipassana.hue },
          { id: 'anapana_vipassana_metta', t: 'Ānāpāna → Vipassanā → Mettā', d: 'The full arc: breath, body sweep, then lovingkindness to close.', tag: 'full sit', hue: MT_TRAD.metta.hue },
          { id: 'open', t: 'Open awareness', d: 'No sweep. Rest in open noting — Dipa Ma\u2019s householder way.', tag: 'noting', hue: MT_TRAD.noting.hue },
          { id: 'walking', t: 'Walking', d: 'Mindful steps — attention in the soles of the feet. Phone in pocket.', tag: 'movement', hue: '#8FD0A8' },
        ].map(o => {
          const on = practice === o.id;
          return (
            <div key={o.id} onClick={() => setPractice(o.id)} style={{
              display: 'flex', gap: 14, alignItems: 'center', padding: '15px 16px', borderRadius: 18, cursor: 'pointer',
              border: `1px solid ${on ? o.hue : C.inkGhost}`, background: on ? hexA(o.hue, 0.08) : 'rgba(255,255,255,0.02)',
            }}>
              <div style={{ width: 10, height: 10, borderRadius: 10, flexShrink: 0, background: o.hue, boxShadow: on ? `0 0 10px ${o.hue}` : 'none' }} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 15.5, fontWeight: 600, color: C.ink }}>{o.t}</div>
                <div style={{ fontSize: 12.5, color: C.inkFaint, lineHeight: 1.45, marginTop: 2 }}>{o.d}</div>
              </div>
              <span style={{ fontSize: 10, color: on ? o.hue : C.inkFaint, fontFamily: 'var(--mono)', letterSpacing: 0.5, flexShrink: 0 }}>{o.tag}</span>
            </div>
          );
        })}
      </div>
      </React.Fragment>)}

      {(path === 'bhakti' || path === 'hybrid') && (<React.Fragment>
        <MTEyebrow>The Name to chant</MTEyebrow>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 9, margin: '12px 0 12px' }}>
          {Object.keys(MT_DEITIES).map(id => {
            const dd = MT_DEITIES[id]; const on = deity === id;
            return (
              <button key={id} onClick={() => setDeity(id)} style={{
                width: 'calc(50% - 5px)', appearance: 'none', cursor: 'pointer', font: 'inherit', textAlign: 'left', padding: '13px 15px', borderRadius: 14,
                border: `1px solid ${on ? dd.hue : C.inkGhost}`, background: on ? hexA(dd.hue, 0.1) : 'rgba(255,255,255,0.02)',
                display: 'flex', alignItems: 'center', gap: 11,
              }}>
                <span style={{ width: 10, height: 10, borderRadius: 10, flexShrink: 0, background: dd.hue, boxShadow: on ? `0 0 10px ${dd.hue}` : 'none' }} />
                <div>
                  <div style={{ fontSize: 15.5, fontWeight: 600, color: C.ink, fontFamily: 'var(--serif)' }}>{dd.label}</div>
                  <div style={{ fontSize: 11, color: C.inkFaint, marginTop: 1 }}>{dd.tradition}</div>
                </div>
              </button>
            );
          })}
        </div>
        <div style={{ fontSize: 12.5, color: C.inkDim, lineHeight: 1.5, marginBottom: 4, textWrap: 'pretty' }}>
          {path === 'bhakti'
            ? `Sit and repeat “${MT_DEITIES[deity].chant}”. When a sensation or feeling arises, note it, offer it to ${MT_DEITIES[deity].label}, and return to the Name.`
            : `Sweep through the body, placing the Name “${MT_DEITIES[deity].chant}” on each part — filling every cell with naama in place of craving.`}
        </div>
      </React.Fragment>)}

      {/* scan controls — only meaningful when the practice includes the Vipassanā sweep */}
      {hasSweep && (
        <div style={{ marginTop: 26 }}>
          <MTEyebrow>Scan direction</MTEyebrow>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 9, margin: '12px 0 22px' }}>
            {dirs.map(o => {
              const on = direction === o.id;
              return (
                <button key={o.id} onClick={() => setDirection(o.id)} style={{
                  appearance: 'none', cursor: 'pointer', font: 'inherit', padding: '12px 6px', borderRadius: 14,
                  border: `1px solid ${on ? C.teal : C.inkGhost}`, background: on ? 'rgba(54,232,210,0.1)' : 'rgba(255,255,255,0.02)',
                  color: on ? C.ink : C.inkDim, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
                }}>
                  <span style={{ fontSize: 20, lineHeight: 1, color: on ? C.teal : C.inkDim }}>{o.g}</span>
                  <span style={{ fontSize: 11.5, fontWeight: on ? 600 : 500, textAlign: 'center' }}>{o.t}</span>
                </button>
              );
            })}
          </div>

          <MTEyebrow>Scan speed</MTEyebrow>
          <div style={{ display: 'flex', gap: 8, margin: '12px 0 0' }}>
            {speeds.map(o => {
              const on = speed === o.s;
              return (
                <button key={o.s} onClick={() => setSpeed(o.s)} style={{
                  flex: 1, appearance: 'none', cursor: 'pointer', font: 'inherit', padding: '11px 0', borderRadius: 12,
                  border: `1px solid ${on ? C.teal : C.inkGhost}`, background: on ? 'rgba(54,232,210,0.1)' : 'rgba(255,255,255,0.02)',
                  color: on ? C.ink : C.inkDim, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2,
                }}>
                  <span style={{ fontSize: 14, fontWeight: 600 }}>{o.t}</span>
                  <span style={{ fontSize: 10.5, color: C.inkFaint, fontFamily: 'var(--mono)' }}>{Math.round(o.s)}s</span>
                </button>
              );
            })}
          </div>
        </div>
      )}

      <div style={{ flex: 1, minHeight: 20 }} />

      {path !== 'relax' && <div style={{ marginTop: 26 }}>
        <MTEyebrow>Sound</MTEyebrow>
        {/* ambient music toggle */}
        <div onClick={() => setAmbient(a => !a)} style={{ display: 'flex', alignItems: 'center', gap: 13, padding: '14px 16px', borderRadius: 16, cursor: 'pointer', margin: '12px 0 10px',
          border: `1px solid ${ambient ? C.teal : C.inkGhost}`, background: ambient ? 'rgba(54,232,210,0.07)' : 'rgba(255,255,255,0.02)' }}>
          <div style={{ width: 40, height: 40, borderRadius: 11, display: 'grid', placeItems: 'center', background: ambient ? 'rgba(54,232,210,0.14)' : 'rgba(255,255,255,0.03)', color: ambient ? C.teal : C.inkDim, flexShrink: 0 }}>
            <MTIcon name={ambient ? 'sound' : 'mute'} size={20} />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 15.5, fontWeight: 600, color: C.ink }}>Ambient drone</div>
            <div style={{ fontSize: 12.5, color: C.inkFaint, marginTop: 1 }}>A soft, breathing background tone</div>
          </div>
          <span style={{ width: 44, height: 26, borderRadius: 999, flexShrink: 0, position: 'relative', transition: 'background .2s',
            background: ambient ? C.teal : 'rgba(255,255,255,0.12)' }}>
            <span style={{ position: 'absolute', top: 3, left: ambient ? 21 : 3, width: 20, height: 20, borderRadius: 999, background: '#fff', transition: 'left .2s', boxShadow: '0 1px 3px rgba(0,0,0,0.4)' }} />
          </span>
        </div>

        {/* voice guidance toggle */}
        <div onClick={() => setVoice(v => !v)} style={{ display: 'flex', alignItems: 'center', gap: 13, padding: '14px 16px', borderRadius: 16, cursor: 'pointer', margin: '0 0 10px',
          border: `1px solid ${voice ? C.teal : C.inkGhost}`, background: voice ? 'rgba(54,232,210,0.07)' : 'rgba(255,255,255,0.02)' }}>
          <div style={{ width: 40, height: 40, borderRadius: 11, display: 'grid', placeItems: 'center', background: voice ? 'rgba(54,232,210,0.14)' : 'rgba(255,255,255,0.03)', color: voice ? C.teal : C.inkDim, flexShrink: 0 }}>
            <MTIcon name="quotes" size={20} />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 15.5, fontWeight: 600, color: C.ink }}>Voice guidance</div>
            <div style={{ fontSize: 12.5, color: C.inkFaint, marginTop: 1 }}>A spoken voice leads the sweep aloud</div>
          </div>
          <span style={{ width: 44, height: 26, borderRadius: 999, flexShrink: 0, position: 'relative', transition: 'background .2s',
            background: voice ? C.teal : 'rgba(255,255,255,0.12)' }}>
            <span style={{ position: 'absolute', top: 3, left: voice ? 21 : 3, width: 20, height: 20, borderRadius: 999, background: '#fff', transition: 'left .2s', boxShadow: '0 1px 3px rgba(0,0,0,0.4)' }} />
          </span>
        </div>

        {/* interval reminder */}
        <div style={{ padding: '14px 16px', borderRadius: 16, border: `1px solid ${C.inkGhost}`, background: 'rgba(255,255,255,0.02)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 13, marginBottom: 13 }}>
            <div style={{ width: 40, height: 40, borderRadius: 11, display: 'grid', placeItems: 'center', background: intervalBell ? 'rgba(54,232,210,0.14)' : 'rgba(255,255,255,0.03)', color: intervalBell ? C.teal : C.inkDim, flexShrink: 0 }}>
              <MTIcon name="timer" size={20} />
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 15.5, fontWeight: 600, color: C.ink }}>Attention reminder</div>
              <div style={{ fontSize: 12.5, color: C.inkFaint, marginTop: 1 }}>A cue to bring attention back, as you sit</div>
            </div>
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            {[[0, 'Off'], [3, '3m'], [5, '5m'], [10, '10m'], [15, '15m']].map(([v, lab]) => {
              const on = intervalBell === v;
              const disabled = v > 0 && v >= dur;
              return (
                <button key={v} disabled={disabled} onClick={() => setIntervalBell(v)} style={{
                  flex: 1, appearance: 'none', cursor: disabled ? 'not-allowed' : 'pointer', font: 'inherit', padding: '11px 0', borderRadius: 12,
                  border: `1px solid ${on ? C.teal : C.inkGhost}`, background: on ? 'rgba(54,232,210,0.1)' : 'transparent',
                  color: on ? C.ink : C.inkDim, opacity: disabled ? 0.35 : 1, fontSize: 13.5, fontWeight: 600,
                }}>{lab}</button>
              );
            })}
          </div>
          {/* gong vs gentle voice */}
          {intervalBell > 0 && (
            <div style={{ display: 'flex', gap: 8, marginTop: 10 }}>
              {[['gong', 'Gong'], ['voice', 'Gentle voice']].map(([id, lab]) => {
                const on = reminderType === id;
                return (
                  <button key={id} onClick={() => setReminderType(id)} style={{
                    flex: 1, appearance: 'none', cursor: 'pointer', font: 'inherit', padding: '10px 0', borderRadius: 12,
                    border: `1px solid ${on ? C.teal : C.inkGhost}`, background: on ? 'rgba(54,232,210,0.1)' : 'transparent',
                    color: on ? C.ink : C.inkDim, fontSize: 13, fontWeight: 600, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7,
                  }}>
                    <MTIcon name={id === 'gong' ? 'timer' : 'quotes'} size={14} color={on ? C.teal : C.inkFaint} /> {lab}
                  </button>
                );
              })}
            </div>
          )}
        </div>
      </div>}

      <div style={{ marginTop: 20 }}>
        <ParkingBox items={parked} setItems={setParked} />
      </div>

      {/* sound levels */}
      {path !== 'relax' && (ambient || voice) && (
        <div style={{ margin: '14px 0 0', padding: '14px 16px', borderRadius: 16, border: `1px solid ${C.inkGhost}`, background: 'rgba(255,255,255,0.02)' }}>
          {ambient && (
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: voice ? 12 : 0 }}>
              <span style={{ fontSize: 12.5, color: C.inkFaint, width: 64, fontFamily: 'var(--mono)' }}>ambient</span>
              <input type="range" min="10" max="100" value={ambientVol} onChange={(e) => setAmbientVol(+e.target.value)} style={{ flex: 1, accentColor: C.teal }} />
            </div>
          )}
          {voice && (
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <span style={{ fontSize: 12.5, color: C.inkFaint, width: 64, fontFamily: 'var(--mono)' }}>voice</span>
              <input type="range" min="20" max="100" value={voiceVol} onChange={(e) => setVoiceVol(+e.target.value)} style={{ flex: 1, accentColor: C.teal }} />
            </div>
          )}
          {voice && (
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 12 }}>
              <span style={{ fontSize: 12.5, color: C.inkFaint, width: 64, fontFamily: 'var(--mono)' }} title="The opening instructions always play; this sets how often a cue repeats afterwards">repeat</span>
              <div style={{ display: 'flex', gap: 8, flex: 1 }}>
                {[[0, 'off'], [3, '3m'], [5, '5m'], [10, '10m']].map(([v, lab]) => (
                  <button key={v} onClick={() => setCueEvery(v)} style={{
                    appearance: 'none', cursor: 'pointer', flex: 1, padding: '7px 0', borderRadius: 999,
                    border: `1px solid ${cueEvery === v ? C.teal : C.inkGhost}`,
                    background: cueEvery === v ? 'rgba(54,232,210,0.1)' : 'rgba(255,255,255,0.02)',
                    color: cueEvery === v ? C.ink : C.inkDim, fontSize: 12.5, fontFamily: 'var(--mono)' }}>{lab}</button>
                ))}
              </div>
            </div>
          )}
        </div>
      )}

      {path !== 'relax' && <ShareSitLink dur={dur} path={path} practice={practice} />}
      {path === 'relax' ? (
      <MTButton full size="lg" onClick={() => onRelax(parked)} style={{ marginTop: 22, background: 'linear-gradient(180deg, #7CC4FF, #3E86C8)' }}>
        <MTIcon name="play" size={20} color="#04121f" /> Begin 61-point relaxation
      </MTButton>
      ) : (
      <MTButton full size="lg" onClick={() => onStart({ duration: dur, path, deity, practice: path === 'insight' ? practice : (path === 'hybrid' ? 'hybrid' : 'bhakti'), mode: (path === 'insight' && practice === 'open') ? 'silent' : 'guided', pose, speed, direction, parked, ambient, voice, ambientVol, voiceVol, cueEvery, reminderType, intervalBell: intervalBell >= dur ? 0 : intervalBell })} style={{ marginTop: 22 }}>
        <MTIcon name="play" size={20} color="#022019" /> Begin {dur}-minute sitting
      </MTButton>
      )}
    </div>
  );
}

// ── Parking box: "set down your mind" before sitting ─────────────
function ParkingBox({ items, setItems }) {
  const C = MT_COLORS;
  const [val, setVal] = React.useState('');
  const add = () => {
    const t = val.trim();
    if (!t) return;
    const next = [...items, { id: 'p' + Date.now() + Math.random().toString(36).slice(2, 6), text: t }];
    setItems(next); mtSaveParked(next); setVal('');
  };
  const remove = (id) => { const next = items.filter(i => i.id !== id); setItems(next); mtSaveParked(next); };
  return (
    <div style={{ position: 'relative', borderRadius: 20, border: `1px solid ${hexA('#FFC78A', 0.3)}`,
      background: 'linear-gradient(160deg, rgba(38,28,16,0.5), rgba(10,18,28,0.5))', padding: '16px 16px 18px' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
        <div style={{ width: 34, height: 34, borderRadius: 10, display: 'grid', placeItems: 'center', background: 'rgba(255,199,138,0.12)', color: '#FFC78A', flexShrink: 0 }}>
          <MTIcon name="tray" size={19} color="#FFC78A" />
        </div>
        <div>
          <div style={{ fontSize: 15.5, fontWeight: 600, color: C.ink }}>Set down your mind</div>
          <div style={{ fontSize: 12, color: C.inkFaint }}>I'll hold these and hand them back after the sit.</div>
        </div>
      </div>

      <div style={{ display: 'flex', gap: 8, marginTop: 12 }}>
        <input value={val} onChange={e => setVal(e.target.value)}
          onKeyDown={e => { if (e.key === 'Enter') { e.preventDefault(); add(); } }}
          placeholder="A to-do, a reminder, a worry…"
          style={{ flex: 1, minWidth: 0, boxSizing: 'border-box', background: 'rgba(255,255,255,0.04)', border: `1px solid ${C.inkGhost}`,
            borderRadius: 12, padding: '12px 14px', color: C.ink, fontSize: 14.5, fontFamily: 'var(--sans)', outline: 'none' }} />
        <button onClick={add} style={{ appearance: 'none', cursor: 'pointer', flexShrink: 0, width: 46, borderRadius: 12, border: 'none',
          background: val.trim() ? 'linear-gradient(180deg, #FFC78A, #E0A45C)' : 'rgba(255,255,255,0.05)', color: val.trim() ? '#241608' : C.inkFaint,
          display: 'grid', placeItems: 'center', transition: 'all .15s' }}>
          <MTIcon name="plus" size={20} color={val.trim() ? '#241608' : C.inkFaint} />
        </button>
      </div>

      {items.length > 0 && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 7, marginTop: 12 }}>
          {items.map(it => (
            <div key={it.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px', borderRadius: 11,
              background: 'rgba(255,255,255,0.03)', border: `1px solid ${C.inkGhost}` }}>
              <span style={{ width: 6, height: 6, borderRadius: 6, background: '#FFC78A', flexShrink: 0 }} />
              <span style={{ flex: 1, minWidth: 0, fontSize: 14, color: C.inkDim, wordBreak: 'break-word' }}>{it.text}</span>
              <button onClick={() => remove(it.id)} style={{ appearance: 'none', background: 'none', border: 'none', cursor: 'pointer', color: C.inkFaint, display: 'grid', placeItems: 'center', flexShrink: 0, padding: 2 }}>
                <MTIcon name="close" size={16} />
              </button>
            </div>
          ))}
          <div style={{ fontSize: 11.5, color: C.inkFaint, fontFamily: 'var(--mono)', letterSpacing: 0.5, marginTop: 4, textAlign: 'center' }}>
            {items.length} held · released from mind for now
          </div>
        </div>
      )}
    </div>
  );
}

// ── Complete ──────────────────────────────────────────────────────
function CompleteScreen({ result, onSave, onDiscard }) {
  const C = MT_COLORS;
  const [reflection, setReflection] = React.useState('');
  const [emotion, setEmotion] = React.useState(null);
  const [markers, setMarkers] = React.useState(result.markers || []);
  const [sheet, setSheet] = React.useState(null);
  const [parked, setParked] = React.useState(() => {
    const a = (result && result.parked) ? result.parked : [];
    const b = mtLoadParked();
    const seen = new Set(); const merged = [];
    [...a, ...b].forEach(it => { if (it && !seen.has(it.id)) { seen.add(it.id); merged.push(it); } });
    return merged;
  });
  const heat = buildHeat([{ markers }]);
  const regionsTouched = new Set(markers.map(m => m.region)).size;
  const dismiss = (id) => setParked(p => p.filter(i => i.id !== id));
  const finishSave = (payload) => { mtClearParked(); onSave(payload); };
  const finishDiscard = () => { mtClearParked(); onDiscard(); };
  const addMark = (m) => { setMarkers(prev => { const i = prev.filter(p => p.region === m.region).length; return [...prev, { ...m, i }]; }); setSheet(null); };
  return (
    <div style={{ padding: '12px 20px 40px', minHeight: '100%', display: 'flex', flexDirection: 'column' }}>
      <div style={{ textAlign: 'center', marginTop: 6, marginBottom: 14 }}>
        <MTEyebrow color={C.teal}>Sitting complete</MTEyebrow>
        <h1 style={{ font: '300 28px/1.2 var(--serif)', color: C.ink, margin: '8px 0 4px' }}>Where did the body hold?</h1>
        <p style={{ fontSize: 13.5, color: C.inkFaint, lineHeight: 1.5, margin: '6px auto 0', maxWidth: 330, textWrap: 'pretty' }}>
          Eyes open now. Tap anywhere the body carried tension, heat, or ease during the sit.
        </p>
      </div>

      <div style={{ display: 'flex', gap: 11, alignItems: 'flex-start', padding: '13px 15px', marginBottom: 18, borderRadius: 14,
        background: hexA(C.teal, 0.06), border: `1px solid ${hexA(C.teal, 0.22)}` }}>
        <div style={{ width: 30, height: 30, borderRadius: 9, flexShrink: 0, display: 'grid', placeItems: 'center', background: hexA(C.teal, 0.12), color: C.teal }}>
          <MTIcon name="atlas" size={17} />
        </div>
        <div style={{ fontSize: 13, color: C.inkDim, lineHeight: 1.5, textWrap: 'pretty' }}>
          The body keeps the score — stress is stored in it as sensation. It releases only when you observe those sensations and emotions objectively, untying the knots held deep in the body and the subconscious mind.
        </div>
      </div>

      {/* interactive after-sit body map */}
      <div style={{ display: 'flex', gap: 16, alignItems: 'center', marginBottom: 8 }}>
        <div style={{ width: 130, height: 232, flexShrink: 0 }}>
          <BodyFigure interactive heat={heat} markers={markers} onRegionTap={(id) => setSheet(id)} selected={sheet} />
        </div>
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 10 }}>
          {[['timer', `${Math.max(1, Math.round((result.elapsedSec || 0) / 60))} min`, 'time sat'], ['spark', markers.length, 'sensations mapped'], ['atlas', regionsTouched, 'regions touched']].map(([ic, val, lab]) => (
            <div key={lab} style={{ display: 'flex', alignItems: 'center', gap: 11 }}>
              <div style={{ width: 38, height: 38, borderRadius: 11, background: 'rgba(54,232,210,0.08)', display: 'grid', placeItems: 'center', color: C.teal }}>
                <MTIcon name={ic} size={19} />
              </div>
              <div>
                <div style={{ fontFamily: 'var(--mono)', fontSize: 19, color: C.ink, lineHeight: 1 }}>{val}</div>
                <div style={{ fontSize: 12, color: C.inkFaint, marginTop: 2 }}>{lab}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
      <div style={{ textAlign: 'center', fontSize: 11, color: C.inkFaint, fontFamily: 'var(--mono)', letterSpacing: 1, marginBottom: 22 }}>
        TAP THE BODY TO MAP A SENSATION
      </div>

      <MTEyebrow>One line for the diary</MTEyebrow>
      <textarea value={reflection} onChange={e => setReflection(e.target.value)}
        placeholder="Where did attention catch? What softened? What held on?"
        style={{ width: '100%', boxSizing: 'border-box', marginTop: 10, marginBottom: 20, minHeight: 76, resize: 'none',
          background: 'rgba(255,255,255,0.03)', border: `1px solid ${C.inkGhost}`, borderRadius: 16, padding: 14,
          color: C.ink, font: 'italic 300 16px/1.5 var(--serif)', outline: 'none' }} />

      <MTEyebrow>The overall tone</MTEyebrow>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7, marginTop: 10 }}>
        {MT_EMOTIONS.map(e => <MTChip key={e} label={e} sub active={emotion === e} onClick={() => setEmotion(emotion === e ? null : e)} />)}
      </div>

      {parked.length > 0 && (
        <div style={{ marginTop: 26, position: 'relative', borderRadius: 20, border: `1px solid ${hexA('#FFC78A', 0.3)}`,
          background: 'linear-gradient(160deg, rgba(38,28,16,0.5), rgba(10,18,28,0.5))', padding: '16px 16px 18px' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 4 }}>
            <div style={{ width: 34, height: 34, borderRadius: 10, display: 'grid', placeItems: 'center', background: 'rgba(255,199,138,0.12)', color: '#FFC78A', flexShrink: 0 }}>
              <MTIcon name="tray" size={19} color="#FFC78A" />
            </div>
            <div>
              <div style={{ fontSize: 15.5, fontWeight: 600, color: C.ink }}>Pick your mind back up</div>
              <div style={{ fontSize: 12, color: C.inkFaint }}>What you set down — here it is again. Tap to let any go.</div>
            </div>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 7, marginTop: 12 }}>
            {parked.map(it => (
              <button key={it.id} onClick={() => dismiss(it.id)} style={{ appearance: 'none', textAlign: 'left', cursor: 'pointer',
                display: 'flex', alignItems: 'center', gap: 10, padding: '11px 12px', borderRadius: 11,
                background: 'rgba(255,255,255,0.03)', border: `1px solid ${C.inkGhost}`, fontFamily: 'var(--sans)' }}>
                <span style={{ width: 18, height: 18, borderRadius: 6, border: `1px solid ${hexA('#FFC78A', 0.6)}`, display: 'grid', placeItems: 'center', flexShrink: 0 }}>
                  <MTIcon name="check" size={13} color="#FFC78A" sw={2.4} />
                </span>
                <span style={{ flex: 1, minWidth: 0, fontSize: 14.5, color: C.ink, wordBreak: 'break-word' }}>{it.text}</span>
              </button>
            ))}
          </div>
        </div>
      )}

      <div style={{ marginTop: 26, paddingTop: 22, borderTop: `1px solid ${C.stroke}` }}>
        <QuoteBlock quote={React.useMemo(() => mtQuotePhase('stop'), [])} shuffle align="center" size={16} />
      </div>

      <div style={{ flex: 1, minHeight: 20 }} />
      {/* two equal choices — no alarming words, nothing shouting */}
      <div style={{ display: 'flex', gap: 12, marginTop: 24 }}>
        <MTButton size="md" tone="ghost" full onClick={() => finishSave({ ...result, markers, reflection, emotion })}>
          <MTIcon name="check" size={18} color={C.teal} /> Save observation log
        </MTButton>
        <MTButton size="md" tone="ghost" full onClick={finishDiscard}>
          <MTIcon name="today" size={18} color={C.inkDim} /> Go to home
        </MTButton>
      </div>
      <div style={{ textAlign: 'center', marginTop: 12, fontSize: 12.5, color: C.inkFaint }}>
        Your sitting time is counted either way — saving also keeps your notes and body map.
      </div>

      {sheet && <NoteSheet region={sheet} startPick={false} onClose={() => setSheet(null)} onSave={addMark} onRegionChange={(id) => setSheet(id)} />}
    </div>
  );
}

// ── Journal ───────────────────────────────────────────────────────
function JournalScreen({ sessions, vp }) {
  const C = MT_COLORS;
  const fileRef = React.useRef(null);
  return (
    <div style={{ padding: '8px 20px 120px' }}>
      <h1 style={{ font: '300 32px/1.1 var(--serif)', color: C.ink, margin: '12px 0 6px' }}>Diary</h1>
      <div style={{ fontSize: 14, color: C.inkFaint, marginBottom: 22 }}>A somatic record — the body keeping its own score.</div>
      {sessions.length === 0 && <div style={{ color: C.inkFaint, textAlign: 'center', marginTop: 60 }}>No sittings yet.</div>}
      <div style={{ display: 'grid', gap: vp && vp.isWide ? 18 : 22, gridTemplateColumns: vp && vp.isWide ? '1fr 1fr' : '1fr', alignItems: 'start' }}>
        {sessions.map(s => (
          <div key={s.id}>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, margin: '0 4px 9px' }}>
              <span style={{ font: '500 16px var(--serif)', color: C.ink }}>{relDay(s.date)}</span>
              <span style={{ fontSize: 12, color: C.inkFaint, fontFamily: 'var(--mono)' }}>
                {new Date(s.date).toLocaleDateString(undefined, { month: 'short', day: 'numeric' })}
              </span>
            </div>
            <SessionCard s={s} />
          </div>
        ))}
      </div>

      {/* backup — the diary is the data, so this is where it lives */}
      <div style={{ marginTop: 36, borderTop: `1px solid ${C.stroke}`, paddingTop: 20, maxWidth: 460 }}>
        <MTEyebrow>Your data</MTEyebrow>
        <div style={{ fontSize: 13, color: C.inkFaint, lineHeight: 1.55, margin: '8px 0 14px' }}>
          Everything lives only in this browser — nothing is sent anywhere.
          Download a backup to keep your history safe, or restore one on a new device.
        </div>
        <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
          <MTButton size="sm" tone="ghost" onClick={mtExportData}>
            <MTIcon name="chevR" size={15} color={C.teal} /> Export backup
          </MTButton>
          <MTButton size="sm" tone="ghost" onClick={() => fileRef.current && fileRef.current.click()}>
            Import backup
          </MTButton>
          <DailyReminderIcs C={C} />
          <input ref={fileRef} type="file" accept=".json,application/json" style={{ display: 'none' }}
            onChange={(e) => {
              const f = e.target.files && e.target.files[0]; e.target.value = '';
              if (!f) return;
              if (!window.confirm('Replace the data in this browser with the backup file?')) return;
              mtImportData(f, (ok, msg) => { if (ok) window.location.reload(); else window.alert(msg || 'Import failed.'); });
            }} />
        </div>
      </div>
    </div>
  );
}

// "Daily reminder" — a calendar file is the one reminder mechanism
// that works reliably everywhere without a server or notifications.
function DailyReminderIcs({ C }) {
  const [time, setTime] = React.useState('07:00');
  const download = () => {
    const [h, m] = time.split(':').map(Number);
    const d = new Date(); d.setDate(d.getDate() + 1); d.setHours(h, m, 0, 0);
    const pad = (x) => String(x).padStart(2, '0');
    const dt = `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}T${pad(h)}${pad(m)}00`;
    // pin the user's timezone explicitly (unambiguous across calendar apps),
    // and run for one year rather than forever — re-download to renew
    const tz = (Intl.DateTimeFormat().resolvedOptions() || {}).timeZone;
    const ics = ['BEGIN:VCALENDAR', 'VERSION:2.0', 'PRODID:-//Anicca//EN', 'BEGIN:VEVENT',
      `UID:anicca-daily-${dt}@meditate.ajinkya.ai`, tz ? `DTSTART;TZID=${tz}:${dt}` : `DTSTART:${dt}`, 'DURATION:PT20M', 'RRULE:FREQ=DAILY;COUNT=365',
      'SUMMARY:Sit \u00b7 Anicca', 'DESCRIPTION:https://meditate.ajinkya.ai', 'END:VEVENT', 'END:VCALENDAR'].join('\r\n');
    const a = document.createElement('a');
    a.href = URL.createObjectURL(new Blob([ics], { type: 'text/calendar' }));
    a.download = 'anicca-daily-sit.ics';
    document.body.appendChild(a); a.click(); a.remove();
    setTimeout(() => URL.revokeObjectURL(a.href), 2000);
  };
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, width: '100%', marginTop: 4 }}>
      <input type="time" value={time} onChange={(e) => setTime(e.target.value)}
        style={{ background: 'rgba(255,255,255,0.04)', border: `1px solid ${C.inkGhost}`, borderRadius: 10, color: C.ink, padding: '8px 10px', fontFamily: 'var(--mono)', fontSize: 14, colorScheme: 'dark' }} />
      <MTButton size="sm" tone="ghost" onClick={download}>Daily reminder \u2192 calendar</MTButton>
    </div>
  );
}

// ── Atlas (body heat-map across time) ─────────────────────────────
function AtlasScreen({ sessions, vp }) {
  const C = MT_COLORS;
  const wide = vp && vp.isWide;
  const [view, setView] = React.useState('map'); // 'map' | 'trends'
  const [range, setRange] = React.useState('all');
  const filtered = React.useMemo(() => {
    if (range === 'all') return sessions;
    const days = range === 'week' ? 7 : 30;
    const cut = Date.now() - days * 864e5;
    return sessions.filter(s => new Date(s.date).getTime() >= cut);
  }, [sessions, range]);
  const heat = React.useMemo(() => buildHeat(filtered), [filtered]);
  const ranked = React.useMemo(() => Object.entries(heat).sort((a, b) => b[1].total - a[1].total).slice(0, 5), [heat]);
  const totalNotes = filtered.reduce((n, s) => n + s.markers.length, 0);

  const rangeRow = (
    <div style={{ display: 'flex', gap: 8, marginBottom: 18 }}>
      {[['week', '7 days'], ['month', '30 days'], ['all', 'All time']].map(([id, lab]) => (
        <button key={id} onClick={() => setRange(id)} style={{
          flex: 1, appearance: 'none', cursor: 'pointer', font: 'inherit', padding: '10px 0', borderRadius: 12,
          border: `1px solid ${range === id ? C.teal : C.inkGhost}`, background: range === id ? 'rgba(54,232,210,0.1)' : 'transparent',
          color: range === id ? C.ink : C.inkDim, fontSize: 13, fontWeight: 600,
        }}>{lab}</button>
      ))}
    </div>
  );

  const bodyPanel = (
    <MTPanel style={{ padding: '16px 10px 16px', marginBottom: wide ? 0 : 18 }}>
      <div style={{ width: 172, aspectRatio: '300 / 660', margin: '0 auto 14px' }}>
        <BodyFigure interactive={false} heat={heat} markers={[]} />
      </div>
      <div style={{ display: 'flex', justifyContent: 'center', gap: 18, flexWrap: 'wrap', padding: '4px 8px 0' }}>
        {MT_SENSATIONS.filter(s => Object.values(heat).some(h => h.topSens === s.id)).map(s => (
          <span key={s.id} style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 11, color: C.inkDim }}>
            <span style={{ width: 8, height: 8, borderRadius: 8, background: s.hue }} />{s.label}
          </span>
        ))}
      </div>
    </MTPanel>
  );

  const listSection = (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', margin: '0 4px 12px' }}>
        <MTEyebrow>Where you hold things</MTEyebrow>
        <span style={{ fontSize: 11, color: C.inkFaint, fontFamily: 'var(--mono)' }}>{totalNotes} notings · {filtered.length} sits</span>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {ranked.map(([rid, h]) => (
          <MTPanel key={rid} style={{ padding: '13px 16px', display: 'flex', alignItems: 'center', gap: 12 }}>
            <span style={{ width: 11, height: 11, borderRadius: 11, background: h.hue, boxShadow: `0 0 10px ${hexA(h.hue, 0.6)}`, flexShrink: 0 }} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 15, color: C.ink, marginBottom: 6 }}>{MT_REGION_LABEL[rid] || rid}</div>
              <div style={{ height: 5, borderRadius: 5, background: 'rgba(255,255,255,0.05)', overflow: 'hidden' }}>
                <div style={{ width: `${h.weight * 100}%`, height: '100%', background: h.hue, borderRadius: 5 }} />
              </div>
            </div>
            <span style={{ fontSize: 12, color: C.inkDim, fontFamily: 'var(--mono)' }}>
              mostly {(MT_SENS_MAP[h.topSens] || {}).label?.toLowerCase()}
            </span>
          </MTPanel>
        ))}
        {ranked.length === 0 && <div style={{ color: C.inkFaint, textAlign: 'center', padding: 30 }}>No sittings in this range.</div>}
      </div>
    </div>
  );

  return (
    <div style={{ padding: '8px 20px 120px' }}>
      <h1 style={{ font: '300 32px/1.1 var(--serif)', color: C.ink, margin: '12px 0 6px' }}>Body atlas</h1>
      <div style={{ fontSize: 14, color: C.inkFaint, marginBottom: 16 }}>Where sensation gathers — and how it changes.</div>

      {/* Map / Trends toggle */}
      <div style={{ display: 'flex', gap: 6, padding: 4, borderRadius: 14, background: 'rgba(255,255,255,0.03)', border: `1px solid ${C.inkGhost}`, marginBottom: 18 }}>
        {[['map', 'Map'], ['trends', 'Trends']].map(([id, lab]) => (
          <button key={id} onClick={() => setView(id)} style={{
            flex: 1, appearance: 'none', cursor: 'pointer', font: 'inherit', padding: '10px 0', borderRadius: 10,
            border: 'none', background: view === id ? 'rgba(54,232,210,0.14)' : 'transparent',
            color: view === id ? C.ink : C.inkDim, fontSize: 14, fontWeight: 600, fontFamily: 'var(--sans)',
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7,
          }}>
            <MTIcon name={id === 'map' ? 'atlas' : 'spark'} size={16} color={view === id ? C.teal : C.inkFaint} /> {lab}
          </button>
        ))}
      </div>

      {view === 'trends' ? (
        <TrendsView sessions={sessions} />
      ) : wide ? (
        <div style={{ display: 'flex', gap: 28, alignItems: 'flex-start' }}>
          <div style={{ flex: '0 0 300px', position: 'sticky', top: 8 }}>{rangeRow}{bodyPanel}</div>
          <div style={{ flex: 1, minWidth: 0 }}>{listSection}</div>
        </div>
      ) : (
        <React.Fragment>{rangeRow}{bodyPanel}{listSection}</React.Fragment>
      )}
    </div>
  );
}

Object.assign(window, {
  TodayScreen, SetupScreen, CompleteScreen, JournalScreen, AtlasScreen,
  SessionCard, buildHeat, relDay,
});
