// Dateora — mobile version. Single-column layouts inside an IOSDevice frame.
// Reuses Btn / Field / AvatarPortrait / Bubble / Icon / Display / Eyebrow
// from the web version. The IOSDevice wrapper is added by Dateora.html — this
// component just renders the content (which fills the full device, status bar
// hover-overlays at the top).

const M_TOP_INSET = 56; // leave room for status bar / dynamic island

// ─── Mobile shell ─────────────────────────────────────────────
function MobileDateoraApp({ themeId = 'mentor' }) {
  const t = window.DateoraThemes[themeId];
  const [screen, setScreen] = React.useState('welcome');
  const [user, setUser] = React.useState(null);
  const [tab, setTab] = React.useState('conversation');
  const [messages, setMessages] = React.useState(window.__DateoraSeedMessages || []);
  const [sessions, setSessions] = React.useState(window.__DateoraSeedHistory || []);
  const [sending, setSending] = React.useState(false);

  const reset = () => { setScreen('welcome'); setUser(null); setTab('conversation'); };
  const handleSend = async (text) => {
    const next = [...messages, { role: 'user', text }];
    setMessages(next); setSending(true);
    try {
      const transcript = next.map((m) => (m.role === 'coach' ? 'Adam: ' : 'User: ') + m.text).join('\n\n');
      const reply = await window.claude.complete(window.__DateoraCoachSystem + '\n\nConversation so far:\n' + transcript + '\n\nAdam:');
      setMessages((m) => [...m, { role: 'coach', text: (reply || '').trim() || "Tell me more — what happened next?" }]);
    } catch {
      const fb = ["Stay with that. Smallest version of that you could try this week?",
        "You went abstract. Bring it back to the actual person. What was she wearing?",
        "Good. Rep that line out loud. Three times. How does it land in your mouth?"];
      setMessages((m) => [...m, { role: 'coach', text: fb[Math.floor(Math.random() * fb.length)] }]);
    } finally { setSending(false); }
  };

  const containerStyle = {
    width: '100%', height: '100%',
    background: t.bg, color: t.ink,
    fontFamily: t.fontBody, overflow: 'hidden', position: 'relative',
    backgroundImage: t.bgGradient,
  };

  let body;
  if (screen === 'welcome') body = <MWelcome t={t} onStart={() => setScreen('signup')} onSignIn={() => setScreen('signin')} />;
  else if (screen === 'signup' || screen === 'signin') body = <MAuth t={t} mode={screen} onSubmit={({ email }) => { setUser({ email }); setScreen(screen === 'signup' ? 'plan' : 'app'); }} onBack={() => setScreen(screen === 'signup' ? 'welcome' : 'signup')} />;
  else if (screen === 'plan') body = <MPlan t={t} onStart={() => setScreen('payment')} onBack={() => setScreen('signup')} />;
  else if (screen === 'payment') body = <MPayment t={t} onPaid={() => setScreen('app')} onBack={() => setScreen('plan')} />;
  else if (screen === 'app') body = (
    <MAppShell t={t} tab={tab} onTab={setTab} onLogout={reset}>
      {tab === 'conversation' && <MConversation t={t} messages={messages} onSend={handleSend} sending={sending} />}
      {tab === 'history' && <MHistory t={t} sessions={sessions} onDelete={(id) => setSessions((s) => s.filter((x) => x.id !== id))} onOpen={() => setTab('conversation')} />}
      {tab === 'account' && <MAccount t={t} email={user?.email} />}
    </MAppShell>
  );

  return (
    <div style={containerStyle} key={screen}>
      {body}
      <MScreenNav t={t} screen={screen} onJump={(s) => s === 'welcome' ? reset() : setScreen(s)} />
    </div>
  );
}

// ─── Welcome ─────────────────────────────────────────────────
const MWelcome = ({ t, onStart, onSignIn }) => (
  <div style={{ width: '100%', height: '100%', position: 'relative', overflow: 'hidden' }}>
    <AvatarPortrait t={t} />
    <div style={{ position: 'absolute', inset: 0, background: t.id === 'editorial'
      ? 'linear-gradient(180deg, rgba(244,239,229,0) 30%, rgba(244,239,229,0.95) 65%, #F4EFE5 100%)'
      : 'linear-gradient(180deg, rgba(20,17,15,0) 25%, rgba(20,17,15,0.85) 60%, rgba(10,8,6,1) 100%)',
      pointerEvents: 'none' }}></div>
    <div style={{ position: 'absolute', top: M_TOP_INSET + 8, left: 20, right: 20, zIndex: 2 }}>
      <Wordmark t={t} size={14} />
    </div>
    <div style={{ position: 'absolute', left: 24, right: 24, bottom: 44, zIndex: 2 }}>
      <Eyebrow t={t} style={{ marginBottom: 14, color: t.id === 'editorial' ? t.muted : 'rgba(244,237,227,0.7)' }}>
        For men who freeze
      </Eyebrow>
      <Display t={t} size={t.id === 'editorial' ? 44 : 38} style={{ marginBottom: 14, color: t.ink }}>
        {t.welcomeHeadline}
      </Display>
      <p style={{ fontSize: 14, lineHeight: 1.5, color: t.id === 'editorial' ? t.muted : 'rgba(244,237,227,0.7)', marginBottom: 22, textWrap: 'pretty' }}>
        {t.welcomeSub}
      </p>
      <Btn t={t} variant="primary" size="lg" full onClick={onStart}>{t.welcomeCTA}</Btn>
      <button onClick={onSignIn} style={{
        marginTop: 10, width: '100%', padding: '12px',
        border: 'none', background: 'transparent',
        color: t.id === 'editorial' ? t.muted : 'rgba(244,237,227,0.7)',
        fontSize: 14, fontFamily: t.fontBody, cursor: 'pointer',
      }}>{t.welcomeAlt}</button>
    </div>
  </div>
);

// ─── Auth ─────────────────────────────────────────────────
const MAuth = ({ t, mode, onSubmit, onBack }) => {
  const [email, setEmail] = React.useState(mode === 'signin' ? 'you@example.com' : '');
  const [pw, setPw] = React.useState(mode === 'signin' ? '••••••••' : '');
  const isSignup = mode === 'signup';
  return (
    <div style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column', paddingTop: M_TOP_INSET }}>
      <div style={{ display: 'flex', alignItems: 'center', padding: '12px 16px' }}>
        <button onClick={onBack} style={{ background: 'transparent', border: 'none', color: t.muted, cursor: 'pointer', padding: 8, display: 'flex' }}><Icon.back /></button>
        <div style={{ flex: 1, textAlign: 'center', fontSize: 13, color: t.muted, fontFamily: t.fontBody }}>
          {isSignup ? 'Step 1 of 3' : 'Sign in'}
        </div>
        <div style={{ width: 34 }}></div>
      </div>
      <div style={{ flex: 1, padding: '20px 24px 24px', overflow: 'auto' }}>
        <Display t={t} size={32} style={{ marginBottom: 10 }}>
          {isSignup ? 'Create your account' : 'Welcome back'}
        </Display>
        <p style={{ fontSize: 14, color: t.muted, lineHeight: 1.5, marginBottom: 28 }}>
          {isSignup ? 'Email and a password. Nothing else right now.' : 'Sign in to continue with Adam.'}
        </p>
        <form onSubmit={(e) => { e.preventDefault(); onSubmit({ email }); }} style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <Field t={t} label="Email" type="email" value={email} onChange={setEmail} placeholder="you@example.com" />
          <Field t={t} label="Password" type="password" value={pw} onChange={setPw} placeholder="At least 8 characters" />
          <Btn t={t} variant="primary" size="lg" full type="submit" onClick={() => onSubmit({ email })}>
            {isSignup ? 'Continue' : 'Sign in'}
          </Btn>
        </form>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, margin: '20px 0', color: t.subtle, fontSize: 12 }}>
          <div style={{ flex: 1, height: 1, background: t.border }}></div>or<div style={{ flex: 1, height: 1, background: t.border }}></div>
        </div>
        <Btn t={t} variant="secondary" full onClick={() => onSubmit({ email: 'google@example.com' })}>
          <GoogleG /> Continue with Google
        </Btn>
        <div style={{ marginTop: 22, fontSize: 13, color: t.muted, textAlign: 'center' }}>
          {isSignup ? 'Have an account? ' : 'New here? '}
          <span onClick={onBack} style={{ color: t.accent, cursor: 'pointer', fontWeight: 500 }}>
            {isSignup ? 'Sign in' : 'Create one'}
          </span>
        </div>
      </div>
    </div>
  );
};

// ─── Plan ─────────────────────────────────────────────────
const MPlan = ({ t, onStart, onBack }) => {
  const features = ['Unlimited sessions with Adam', 'Voice and text conversations', 'Saved history — review your reps', 'Cancel two clicks, any page'];
  return (
    <div style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column', paddingTop: M_TOP_INSET }}>
      <div style={{ display: 'flex', alignItems: 'center', padding: '12px 16px' }}>
        <button onClick={onBack} style={{ background: 'transparent', border: 'none', color: t.muted, cursor: 'pointer', padding: 8, display: 'flex' }}><Icon.back /></button>
        <div style={{ flex: 1, textAlign: 'center', fontSize: 13, color: t.muted, fontFamily: t.fontBody }}>Step 2 of 3</div>
        <div style={{ width: 34 }}></div>
      </div>
      <div style={{ flex: 1, padding: '16px 24px 20px', overflow: 'auto' }}>
        <Eyebrow t={t} style={{ marginBottom: 10 }}>{t.planEyebrow}</Eyebrow>
        <Display t={t} size={t.id === 'editorial' ? 44 : 32} style={{ marginBottom: 12 }}>{t.planTitle}</Display>
        <p style={{ fontSize: 14, color: t.muted, lineHeight: 1.55, marginBottom: 24, textWrap: 'pretty' }}>{t.planBody}</p>
        <div style={{
          background: t.surface, border: '1px solid ' + (t.id === 'studio' ? t.accent : t.borderStrong),
          borderRadius: t.radiusXl, padding: 22, position: 'relative',
          boxShadow: t.id === 'studio' ? '0 0 30px -8px ' + t.accentSoft : 'none',
        }}>
          {t.id === 'studio' && (
            <div style={{ position: 'absolute', top: -8, left: 18, padding: '2px 9px', background: t.accent, color: t.accentInk, fontSize: 10, fontFamily: t.fontMono, fontWeight: 600, borderRadius: 100 }}>FREE 14 DAYS</div>
          )}
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 18, paddingBottom: 18, borderBottom: '1px solid ' + t.border }}>
            <div>
              <div style={{ fontSize: 11, color: t.muted, marginBottom: 4 }}>Membership</div>
              <div style={{ fontFamily: t.fontDisplay, fontStyle: t.displayStyle, fontWeight: t.displayWeight, fontSize: 18, color: t.ink, letterSpacing: t.displayLetterSpacing }}>Dateora · Unlimited</div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div style={{ fontFamily: t.fontDisplay, fontWeight: t.id === 'studio' ? 700 : 400, fontStyle: t.displayStyle, fontSize: 32, lineHeight: 1, color: t.ink }}>{t.planPrice}</div>
              <div style={{ fontSize: 10, color: t.muted, marginTop: 2 }}>{t.planPeriod}</div>
            </div>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {features.map((f) => (
              <div key={f} style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 13, color: t.ink }}>
                <div style={{ width: 16, height: 16, borderRadius: 8, background: t.accentSoft, color: t.accent, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon.check /></div>
                {f}
              </div>
            ))}
          </div>
        </div>
        <div style={{ fontSize: 12, color: t.subtle, marginTop: 14, textAlign: 'center' }}>{t.planFinePrint}</div>
      </div>
      <div style={{ padding: '12px 24px 34px', borderTop: '1px solid ' + t.border, background: t.bg }}>
        <Btn t={t} variant="primary" size="lg" full onClick={onStart}>{t.planCTA}</Btn>
      </div>
    </div>
  );
};

// ─── Payment ─────────────────────────────────────────────────
const MPayment = ({ t, onPaid, onBack }) => {
  const [card, setCard] = React.useState('4242 4242 4242 4242');
  const [exp, setExp] = React.useState('12 / 28');
  const [cvc, setCvc] = React.useState('123');
  const [processing, setProcessing] = React.useState(false);
  const submit = () => { setProcessing(true); setTimeout(onPaid, 1100); };
  return (
    <div style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column', paddingTop: M_TOP_INSET }}>
      <div style={{ display: 'flex', alignItems: 'center', padding: '12px 16px' }}>
        <button onClick={onBack} style={{ background: 'transparent', border: 'none', color: t.muted, cursor: 'pointer', padding: 8, display: 'flex' }}><Icon.back /></button>
        <div style={{ flex: 1, textAlign: 'center', fontSize: 13, color: t.muted, fontFamily: t.fontBody }}>Step 3 of 3</div>
        <div style={{ width: 34 }}></div>
      </div>
      <div style={{ flex: 1, padding: '16px 24px', overflow: 'auto' }}>
        <Display t={t} size={28} style={{ marginBottom: 6 }}>Card to start your trial</Display>
        <p style={{ fontSize: 13, color: t.muted, lineHeight: 1.5, marginBottom: 20 }}>No charge today. Email 3 days before trial ends.</p>
        <button onClick={submit} style={{
          width: '100%', padding: '13px', borderRadius: t.radius,
          border: 'none', background: '#000', color: '#fff',
          fontSize: 15, fontWeight: 600, cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
        }}>
          <svg width="40" height="16" viewBox="0 0 40 16" fill="#fff"><path d="M5.8 4.4c-.4.5-1.1.9-1.7.8-.1-.7.2-1.4.6-1.8.4-.5 1.1-.8 1.7-.9.1.7-.2 1.4-.6 1.9zm.6.9c-1 0-1.8.5-2.3.5s-1.2-.5-2-.5c-1 0-2 .6-2.5 1.6-1.1 1.9-.3 4.7.8 6.2.5.7 1.1 1.6 1.9 1.6.8 0 1.1-.5 2-.5.9 0 1.2.5 2 .5.8 0 1.4-.7 1.9-1.5.6-.8.8-1.7.8-1.7s-1.6-.6-1.6-2.4c0-1.5 1.2-2.2 1.3-2.3-.7-1-1.8-1.1-2.3-1.5zm6.7-3.2v11h1.7v-3.8h2.3c2.1 0 3.6-1.4 3.6-3.6 0-2.1-1.5-3.6-3.6-3.6h-4zM15 3.5h2c1.5 0 2.3.8 2.3 2.2s-.8 2.2-2.3 2.2h-2V3.5zm8.5 9.8c1.1 0 2-.5 2.5-1.4h.1v1.3h1.6V7.7c0-1.6-1.3-2.7-3.3-2.7-1.9 0-3.2 1.1-3.3 2.6h1.6c.1-.7.8-1.2 1.7-1.2 1.1 0 1.7.5 1.7 1.4v.6l-2.2.1c-2 .1-3.1 1-3.1 2.4 0 1.5 1.1 2.4 2.7 2.4zm.5-1.3c-.9 0-1.5-.4-1.5-1.1 0-.7.6-1.1 1.7-1.2l2-.1v.6c0 1.1-1 1.8-2.2 1.8zm6 4.2c1.6 0 2.4-.6 3-2.4l3-8.6h-1.7l-2 6.5-2-6.5h-1.8l2.9 8-.2.5c-.3.8-.7 1.1-1.4 1.1-.1 0-.4 0-.5 0v1.3c.1.1.6.1.7.1z"/></svg>
          Pay
        </button>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, margin: '18px 0', color: t.subtle, fontSize: 12 }}>
          <div style={{ flex: 1, height: 1, background: t.border }}></div>or pay with card<div style={{ flex: 1, height: 1, background: t.border }}></div>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          <Field t={t} label="Card number" value={card} onChange={setCard} />
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
            <Field t={t} label="Expiry" value={exp} onChange={setExp} />
            <Field t={t} label="CVC" value={cvc} onChange={setCvc} />
          </div>
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', padding: '20px 0 12px', borderTop: '1px solid ' + t.border, marginTop: 24, fontSize: 14, color: t.ink, fontWeight: 600 }}>
          <span>Due today</span>
          <span style={{ fontFamily: t.fontDisplay, fontSize: 20 }}>$0.00</span>
        </div>
      </div>
      <div style={{ padding: '12px 24px 34px', borderTop: '1px solid ' + t.border, background: t.bg }}>
        <Btn t={t} variant="primary" size="lg" full onClick={submit}>
          {processing ? <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}><Spinner /> Starting…</span> : 'Start 14-day trial'}
        </Btn>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 11, color: t.subtle, justifyContent: 'center', marginTop: 8 }}>
          <Icon.lock /> Secured by Stripe · No charge today
        </div>
      </div>
    </div>
  );
};

// ─── App shell with bottom tab nav ─────────────────────────────
const MAppShell = ({ t, tab, onTab, onLogout, children }) => {
  const items = [
    { id: 'conversation', label: 'Session', icon: <Icon.chat /> },
    { id: 'history', label: 'History', icon: <Icon.history /> },
    { id: 'account', label: 'Account', icon: <Icon.user /> },
  ];
  return (
    <div style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column' }}>
      <div style={{ flex: 1, minHeight: 0, overflow: 'hidden' }}>{children}</div>
      <div style={{
        flexShrink: 0, display: 'flex', justifyContent: 'space-around',
        padding: '8px 8px 30px',
        borderTop: '1px solid ' + t.border,
        background: t.id === 'mentor' ? 'rgba(20,17,15,0.85)' : t.bg,
        backdropFilter: 'blur(20px)',
      }}>
        {items.map((it) => {
          const active = it.id === tab;
          return (
            <button key={it.id} onClick={() => onTab(it.id)}
              style={{
                flex: 1, padding: '8px 4px',
                border: 'none', background: 'transparent',
                color: active ? t.accent : t.muted,
                cursor: 'pointer',
                display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3,
                fontSize: 10, fontFamily: t.fontBody, fontWeight: 500,
                transition: 'color .15s',
              }}>
              {it.icon}
              <span>{it.label}</span>
            </button>
          );
        })}
      </div>
    </div>
  );
};

// ─── Conversation Mobile ─────────────────────────────────────
const MConversation = ({ t, messages, onSend, sending }) => {
  const [draft, setDraft] = React.useState('');
  const ref = React.useRef(null);
  React.useEffect(() => { if (ref.current) ref.current.scrollTop = ref.current.scrollHeight; }, [messages, sending]);
  const send = () => { const v = draft.trim(); if (!v || sending) return; onSend(v); setDraft(''); };
  const lastIsCoach = messages.length > 0 && messages[messages.length - 1].role === 'coach';

  return (
    <div style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column', paddingTop: M_TOP_INSET }}>
      {/* compact header */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 10,
        padding: '10px 16px 12px', borderBottom: '1px solid ' + t.border, flexShrink: 0,
      }}>
        <div style={{ width: 32, height: 32, borderRadius: '50%', overflow: 'hidden', position: 'relative', border: '1px solid ' + t.border }}>
          <AvatarPortrait t={t} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: t.ink, fontFamily: t.fontBody }}>Adam · {t.coachRole}</div>
          <div style={{ fontSize: 10, color: t.muted, display: 'flex', alignItems: 'center', gap: 5 }}>
            <span style={{ width: 5, height: 5, borderRadius: 3, background: t.success, animation: 'dateora-pulse 1.4s infinite' }}></span>
            Live · session 04 · 06:18
          </div>
        </div>
        <button style={{ background: 'transparent', border: '1px solid ' + t.border, color: t.muted, padding: '5px 9px', borderRadius: t.radius, fontSize: 11, fontFamily: t.fontBody, cursor: 'pointer' }}>End</button>
      </div>
      {/* avatar card */}
      <div style={{ flexShrink: 0, padding: '12px 16px 4px' }}>
        <div style={{
          height: 160, borderRadius: t.radiusLg, overflow: 'hidden', position: 'relative',
          border: '1px solid ' + t.border, background: t.surface,
        }}>
          <AvatarPortrait t={t} />
          <div style={{ position: 'absolute', top: 10, left: 10, padding: '3px 8px', borderRadius: 100, background: 'rgba(10,8,6,0.6)', backdropFilter: 'blur(10px)', fontSize: 10, fontFamily: t.fontMono || t.fontBody, color: '#fff', display: 'flex', alignItems: 'center', gap: 5 }}>
            <span style={{ width: 5, height: 5, borderRadius: 3, background: t.accent, animation: 'dateora-pulse 1.2s infinite' }}></span>
            LIVE
          </div>
          <div style={{ position: 'absolute', bottom: 10, right: 10, display: 'flex', gap: 3, alignItems: 'flex-end', height: 18 }}>
            {[3, 7, 11, 14, 9, 5, 11, 14, 8].map((h, i) => (
              <div key={i} style={{ width: 2.5, height: h, borderRadius: 1, background: t.accent, opacity: 0.5 + (i / 18), animation: `dateora-wave 1.2s ${i * 0.1}s infinite ease-in-out` }}></div>
            ))}
          </div>
        </div>
      </div>
      {/* chat scroll */}
      <div ref={ref} style={{ flex: 1, padding: '10px 16px', overflow: 'auto', display: 'flex', flexDirection: 'column', gap: 10 }}>
        {messages.map((m, i) => <Bubble key={i} t={t} m={m} />)}
        {sending && <TypingIndicator t={t} />}
      </div>
      {/* quick reply chips */}
      {lastIsCoach && !draft && !sending && (
        <div style={{ flexShrink: 0, padding: '0 16px 8px', display: 'flex', gap: 6, overflowX: 'auto' }}>
          {["I went blank again", "Give me a real opener", "What should I have said?"].map((s) => (
            <button key={s} onClick={() => setDraft(s)} style={{
              padding: '5px 10px', borderRadius: 100, fontSize: 11,
              fontFamily: t.fontBody, fontWeight: 500,
              border: '1px solid ' + t.border, background: t.surface,
              color: t.muted, cursor: 'pointer', whiteSpace: 'nowrap', flexShrink: 0,
            }}>{s}</button>
          ))}
        </div>
      )}
      {/* input */}
      <div style={{ flexShrink: 0, padding: '8px 12px 12px', borderTop: '1px solid ' + t.border, background: t.bg }}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 8,
          background: t.surface, border: '1px solid ' + t.border,
          borderRadius: 100, padding: '4px 4px 4px 14px',
        }}>
          <button style={{ border: 'none', background: 'transparent', color: t.muted, cursor: 'pointer', padding: 6, display: 'flex' }}><Icon.mic /></button>
          <input value={draft} onChange={(e) => setDraft(e.target.value)}
            onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); send(); } }}
            placeholder={sending ? 'Adam is thinking…' : 'Message Adam…'}
            disabled={sending}
            style={{ flex: 1, border: 'none', outline: 'none', background: 'transparent', color: t.ink, fontSize: 14, fontFamily: t.fontBody, padding: '8px 0', minWidth: 0 }} />
          <button onClick={send} disabled={sending || !draft.trim()} style={{
            border: 'none',
            background: draft.trim() && !sending ? t.accent : t.surface2,
            color: draft.trim() && !sending ? t.accentInk : t.muted,
            cursor: draft.trim() && !sending ? 'pointer' : 'default',
            width: 34, height: 34, borderRadius: 17,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}><Icon.send /></button>
        </div>
      </div>
    </div>
  );
};

// ─── History Mobile ──────────────────────────────────────────
const MHistory = ({ t, sessions, onDelete, onOpen }) => (
  <div style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column', paddingTop: M_TOP_INSET }}>
    <div style={{ flexShrink: 0, padding: '12px 20px 16px', borderBottom: '1px solid ' + t.border }}>
      <Eyebrow t={t} style={{ marginBottom: 4 }}>Your reps</Eyebrow>
      <Display t={t} size={28}>History</Display>
    </div>
    <div style={{ flex: 1, overflow: 'auto', padding: '8px 12px' }}>
      {sessions.map((s) => (
        <div key={s.id} onClick={() => onOpen(s.id)} style={{
          padding: '12px 10px', display: 'flex', alignItems: 'center', gap: 12,
          borderBottom: '1px solid ' + t.border, cursor: 'pointer',
        }}>
          <div style={{
            width: 36, height: 36, borderRadius: t.id === 'studio' ? t.radius : '50%',
            background: t.accentSoft, color: t.accent, fontFamily: t.fontMono || t.fontBody, fontWeight: 600,
            display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, fontSize: 12,
          }}>{String(s.idx).padStart(2, '0')}</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 13, fontWeight: 600, color: t.ink, marginBottom: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{s.title}</div>
            <div style={{ fontSize: 11, color: t.muted }}>{s.when} · {s.minutes} min · {s.reps} reps</div>
          </div>
          <button onClick={(e) => { e.stopPropagation(); onDelete(s.id); }} style={{ background: 'transparent', border: 'none', color: t.subtle, padding: 6, cursor: 'pointer', display: 'flex' }}>
            <Icon.trash />
          </button>
        </div>
      ))}
    </div>
  </div>
);

// ─── Account Mobile ──────────────────────────────────────────
const MAccount = ({ t, email }) => (
  <div style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column', paddingTop: M_TOP_INSET }}>
    <div style={{ flexShrink: 0, padding: '12px 20px 16px', borderBottom: '1px solid ' + t.border }}>
      <Eyebrow t={t} style={{ marginBottom: 4 }}>Settings</Eyebrow>
      <Display t={t} size={28}>Account</Display>
    </div>
    <div style={{ flex: 1, overflow: 'auto', padding: '16px 16px 30px' }}>
      <MSection t={t} title="Profile">
        <MRow t={t} label="Email" value={email || 'you@example.com'} />
        <MRow t={t} label="Password" value="Last changed 2 weeks ago" />
      </MSection>
      <MSection t={t} title="Subscription">
        <MRow t={t} label="Plan" value="Dateora · Unlimited" />
        <MRow t={t} label="Trial" value={<span style={{ color: t.success }}>12 days remaining</span>} />
        <MRow t={t} label="First charge" value="May 28 · $24.00" />
        <MRow t={t} label="Payment" value="•••• 4242" />
      </MSection>
      <MSection t={t} title="Notifications">
        <MRow t={t} label="Daily nudges" value={<MToggle t={t} on />} />
        <MRow t={t} label="Weekly recap" value={<MToggle t={t} on />} />
      </MSection>
      <MSection t={t} title="Data">
        <MRow t={t} label="Export history" value="Download" actionable />
        <MRow t={t} label="Delete account" value={<span style={{ color: t.danger }}>Erase everything</span>} actionable />
      </MSection>
    </div>
  </div>
);

const MSection = ({ t, title, children }) => (
  <section style={{ marginBottom: 20 }}>
    <div style={{
      fontSize: 11, color: t.muted, marginBottom: 8, padding: '0 4px',
      letterSpacing: '0.1em', textTransform: 'uppercase', fontWeight: 600,
      fontFamily: t.id === 'studio' ? (t.fontMono || t.fontBody) : t.fontBody,
    }}>{title}</div>
    <div style={{ background: t.surface, border: '1px solid ' + t.border, borderRadius: t.radiusLg, overflow: 'hidden' }}>{children}</div>
  </section>
);

const MRow = ({ t, label, value, actionable }) => (
  <div style={{
    display: 'flex', alignItems: 'center', justifyContent: 'space-between',
    padding: '12px 14px', borderBottom: '1px solid ' + t.border,
    cursor: actionable ? 'pointer' : 'default',
  }}>
    <div style={{ fontSize: 13, color: t.ink, fontFamily: t.fontBody }}>{label}</div>
    <div style={{ fontSize: 13, color: t.muted, display: 'flex', alignItems: 'center', gap: 6 }}>
      {value}
      {actionable && <span style={{ color: t.subtle, fontSize: 14 }}>›</span>}
    </div>
  </div>
);

const MToggle = ({ t, on }) => {
  const [v, setV] = React.useState(on);
  return (
    <button onClick={() => setV(!v)} style={{
      width: 40, height: 24, borderRadius: 12, border: 'none', cursor: 'pointer',
      background: v ? t.accent : t.border, position: 'relative',
      transition: 'background .15s',
    }}>
      <span style={{
        position: 'absolute', top: 2, left: v ? 18 : 2, width: 20, height: 20,
        borderRadius: 10, background: '#fff', transition: 'left .15s',
        boxShadow: '0 1px 3px rgba(0,0,0,0.2)',
      }}></span>
    </button>
  );
};

// Tiny floating jump-screens pill, sized for mobile
function MScreenNav({ t, screen, onJump }) {
  const [open, setOpen] = React.useState(false);
  const steps = [
    { id: 'welcome', label: '01' },
    { id: 'signup', label: '02' },
    { id: 'plan', label: '03' },
    { id: 'payment', label: '04' },
    { id: 'app', label: '05' },
  ];
  return (
    <div onMouseEnter={() => setOpen(true)} onMouseLeave={() => setOpen(false)}
      style={{
        position: 'absolute', top: 16, left: '50%', transform: 'translateX(-50%)',
        zIndex: 100, padding: 3, borderRadius: 100,
        background: 'rgba(0,0,0,0.5)', backdropFilter: 'blur(20px)',
        border: '1px solid rgba(255,255,255,0.12)',
        display: 'flex', gap: 2, fontSize: 10,
        opacity: open ? 1 : 0.3, transition: 'opacity .2s',
      }}>
      {steps.map((s) => (
        <button key={s.id} onClick={() => onJump(s.id)} style={{
          padding: '4px 8px', border: 'none', borderRadius: 100,
          background: s.id === screen ? 'rgba(255,255,255,0.18)' : 'transparent',
          color: s.id === screen ? '#fff' : 'rgba(255,255,255,0.6)',
          cursor: 'pointer', fontSize: 10, fontFamily: t.fontMono || t.fontBody,
        }}>{s.label}</button>
      ))}
    </div>
  );
}

Object.assign(window, { MobileDateoraApp });
