// VYB LIFE — Auth screen (email/password)
// Reuses C / Input / Button / Label from dashboard-ui.jsx.

const AuthScreen = ({ onAuthed, initialError }) => {
  const tr = useT();
  const [mode, setMode] = React.useState('signin'); // 'signin' | 'signup'
  const [name, setName]     = React.useState('');
  const [email, setEmail]   = React.useState('');
  const [pass, setPass]     = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [err, setErr]       = React.useState(initialError || '');
  const [info, setInfo]     = React.useState('');

  const submit = async () => {
    setErr(''); setInfo(''); setLoading(true);
    try {
      const sb = window.initSupabase();
      if (mode === 'signup') {
        const { data, error } = await sb.auth.signUp({
          email: email.trim(), password: pass,
          options: { data: { name: name.trim() } },
        });
        if (error) throw error;
        if (!data.session) {
          setInfo('Check your email to confirm your account, then sign in.');
          setMode('signin');
        } else {
          onAuthed(data.session);
        }
      } else {
        const { data, error } = await sb.auth.signInWithPassword({
          email: email.trim(), password: pass,
        });
        if (error) throw error;
        onAuthed(data.session);
      }
    } catch (e) {
      setErr(e.message || 'Something went wrong.');
    } finally {
      setLoading(false);
    }
  };

  const canSubmit = email.trim() && pass.length >= 6 && (mode==='signin' || name.trim());

  // Lock body/html scroll while the auth screen is mounted so iOS Safari
  // does not rubber-band when content fits in the viewport.
  React.useEffect(() => {
    const html = document.documentElement;
    const body = document.body;
    const prev = {
      htmlOverflow: html.style.overflow,
      bodyOverflow: body.style.overflow,
      bodyOverscroll: body.style.overscrollBehavior,
    };
    html.style.overflow = 'hidden';
    body.style.overflow = 'hidden';
    body.style.overscrollBehavior = 'none';
    return () => {
      html.style.overflow = prev.htmlOverflow;
      body.style.overflow = prev.bodyOverflow;
      body.style.overscrollBehavior = prev.bodyOverscroll;
    };
  }, []);

  return (
    <div className="vyb-auth-screen"
      style={{position:'fixed',inset:0,background:'var(--c-bg)',zIndex:2000,
        display:'flex',alignItems:'center',justifyContent:'center',
        padding:'24px 24px calc(24px + env(safe-area-inset-bottom)) 24px',
        paddingTop:'calc(24px + env(safe-area-inset-top))',
        overflowY:'auto',overscrollBehavior:'contain',
        WebkitOverflowScrolling:'touch'}}>
      <div style={{maxWidth:420,width:'100%',textAlign:'center'}} className="view-fade">
        <img src="assets/logo-white.png" alt="VYB LIFE" className="vyb-logo" style={{width:110,opacity:0.95,marginBottom:40}}/>
        <div style={{fontSize:11,fontWeight:200,letterSpacing:'0.3em',color:C.textFaint,textTransform:'uppercase',marginBottom:14}}>
          {mode==='signup' ? tr('auth.createAccountKicker','Create account') : tr('auth.welcomeBack','Welcome back')}
        </div>
        <div className="vyb-page-title" style={{fontSize:36,fontWeight:900,fontStyle:'italic',color:C.textPrimary,letterSpacing:'-0.025em',textTransform:'uppercase',lineHeight:1,marginBottom:36}}>
          {mode==='signup'
            ? <>Begin your<br/>quiet practice.</>
            : tr('auth.createYourReality','Create your reality.')}
        </div>

        <div style={{textAlign:'left',display:'flex',flexDirection:'column',gap:14}}>
          {mode==='signup' && (
            <div>
              <div style={{fontSize:10,fontWeight:700,letterSpacing:'0.2em',color:C.textFaint,textTransform:'uppercase',marginBottom:8}}>Name</div>
              <Input value={name} onChange={e=>setName(e.target.value)} placeholder="What should we call you?" style={{fontSize:15,padding:'13px 16px'}}/>
            </div>
          )}
          <div>
            <div style={{fontSize:10,fontWeight:700,letterSpacing:'0.2em',color:C.textFaint,textTransform:'uppercase',marginBottom:8}}>Email</div>
            <Input type="email" value={email} onChange={e=>setEmail(e.target.value)} placeholder="you@example.com" autoFocus style={{fontSize:15,padding:'13px 16px'}}/>
          </div>
          <div>
            <div style={{fontSize:10,fontWeight:700,letterSpacing:'0.2em',color:C.textFaint,textTransform:'uppercase',marginBottom:8}}>Password</div>
            <Input type="password" value={pass} onChange={e=>setPass(e.target.value)}
              onKeyDown={e=>e.key==='Enter'&&canSubmit&&submit()}
              placeholder="At least 6 characters" style={{fontSize:15,padding:'13px 16px'}}/>
          </div>

          {err  && <div style={{fontSize:11,color:'#D67B7B',fontWeight:400,marginTop:2}}>{err}</div>}
          {info && <div style={{fontSize:11,color:C.textSecondary,fontWeight:400,marginTop:2}}>{info}</div>}

          <Button onClick={submit} disabled={!canSubmit || loading}
            style={{width:'100%',marginTop:10,padding:'14px 20px',fontSize:12,opacity:(!canSubmit||loading)?0.5:1}}>
            {loading ? 'Please wait…' : (mode==='signup' ? 'Create account' : 'Sign in')}
          </Button>

          <div style={{display:'flex',alignItems:'center',gap:12,margin:'6px 0 2px'}}>
            <div style={{flex:1,height:1,background:C.border}}/>
            <div style={{fontSize:9,fontWeight:600,letterSpacing:'0.22em',color:C.textFaint,textTransform:'uppercase'}}>or</div>
            <div style={{flex:1,height:1,background:C.border}}/>
          </div>

          <button onClick={async ()=>{
              setErr('');
              const sb = window.initSupabase();
              const redirectTo = `${window.location.origin}/auth/callback.html`;
              console.log('[auth] starting Google OAuth, redirectTo=', redirectTo);
              const { error } = await sb.auth.signInWithOAuth({
                provider: 'google',
                options: { redirectTo },
              });
              if (error) { console.error('[auth] signInWithOAuth error', error); setErr(error.message); }
            }}
            style={{width:'100%',padding:'13px 20px',borderRadius:10,cursor:'pointer',
              background:'#FAFAF8',color:'#0D0C0B',border:'none',
              display:'flex',alignItems:'center',justifyContent:'center',gap:10,
              fontSize:12,fontWeight:600,letterSpacing:'0.06em',textTransform:'uppercase'}}>
            <svg width="16" height="16" viewBox="0 0 48 48" aria-hidden="true">
              <path fill="#EA4335" d="M24 9.5c3.54 0 6.71 1.22 9.21 3.6l6.85-6.85C35.9 2.38 30.47 0 24 0 14.62 0 6.51 5.38 2.56 13.22l7.98 6.19C12.43 13.72 17.74 9.5 24 9.5z"/>
              <path fill="#4285F4" d="M46.98 24.55c0-1.57-.15-3.09-.38-4.55H24v9.02h12.94c-.58 2.96-2.26 5.48-4.78 7.18l7.73 6c4.51-4.18 7.09-10.36 7.09-17.65z"/>
              <path fill="#FBBC05" d="M10.53 28.59c-.48-1.45-.76-2.99-.76-4.59s.27-3.14.76-4.59l-7.98-6.19C.92 16.46 0 20.12 0 24c0 3.88.92 7.54 2.56 10.78l7.97-6.19z"/>
              <path fill="#34A853" d="M24 48c6.48 0 11.93-2.13 15.89-5.81l-7.73-6c-2.15 1.45-4.92 2.3-8.16 2.3-6.26 0-11.57-4.22-13.47-9.91l-7.98 6.19C6.51 42.62 14.62 48 24 48z"/>
            </svg>
            Continue with Google
          </button>

          <div style={{textAlign:'center',marginTop:14}}>
            <button onClick={()=>{ setErr(''); setInfo(''); setMode(mode==='signup'?'signin':'signup'); }}
              style={{background:'none',border:'none',cursor:'pointer',fontSize:11,fontWeight:400,
                color:C.textMuted,letterSpacing:'0.08em',textTransform:'uppercase'}}>
              {mode==='signup' ? 'Have an account? Sign in' : 'New here? Create account'}
            </button>
          </div>
          <div style={{fontSize:10,fontWeight:300,color:C.textFaint,textAlign:'center',marginTop:10,fontStyle:'italic'}}>
            Your data is encrypted at rest and scoped to you.
          </div>
        </div>
      </div>
    </div>
  );
};

// ─── Theme helpers ──────────────────────────────────────────────
const THEME_KEY = 'vyb-theme';
const applyTheme = (pref) => {
  const resolved = pref === 'system'
    ? ((window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches) ? 'light' : 'dark')
    : pref;
  document.documentElement.dataset.theme = resolved;
  document.documentElement.dataset.themePref = pref;
  const meta = document.querySelector('meta[name="theme-color"]');
  if (meta) meta.setAttribute('content', resolved === 'light' ? '#F2EDE2' : '#0D0C0B');
};
const getStoredTheme = () => {
  try { return localStorage.getItem(THEME_KEY) || 'dark'; } catch { return 'dark'; }
};
// Live-react to system preference when user pref is 'system'.
if (typeof window !== 'undefined' && window.matchMedia) {
  try {
    const mq = window.matchMedia('(prefers-color-scheme: light)');
    const handler = () => { if (getStoredTheme() === 'system') applyTheme('system'); };
    mq.addEventListener ? mq.addEventListener('change', handler) : mq.addListener(handler);
  } catch {}
}
window.applyVybTheme = applyTheme;

const AppearanceSection = () => {
  const tr = useT();
  const [pref, setPref] = React.useState(getStoredTheme);
  const choose = (v) => {
    setPref(v);
    try { localStorage.setItem(THEME_KEY, v); } catch {}
    applyTheme(v);
  };
  const options = [
    { v:'dark',   l:tr('profile.themeDark'),   icon:'moon' },
    { v:'light',  l:tr('profile.themeLight'),  icon:'sun' },
    { v:'system', l:tr('profile.themeSystem'), icon:'monitor' },
  ];
  return (
    <div style={{marginTop:24,paddingTop:20,borderTop:`1px solid ${C.border}`}}>
      <div style={{fontSize:10,fontWeight:700,letterSpacing:'0.2em',color:C.textFaint,textTransform:'uppercase',marginBottom:6}}>{tr('profile.appearance')}</div>
      <div style={{fontSize:11,fontWeight:300,color:C.textMuted,marginBottom:12,fontStyle:'italic',letterSpacing:'0.02em'}}>
        {tr('profile.appearanceHint')}
      </div>
      <div style={{display:'grid',gridTemplateColumns:'repeat(3,1fr)',gap:8}}>
        {options.map(o => {
          const active = pref === o.v;
          return (
            <button key={o.v} onClick={()=>choose(o.v)}
              style={{
                display:'flex',flexDirection:'column',alignItems:'center',justifyContent:'center',gap:6,
                padding:'12px 8px',borderRadius:10,cursor:'pointer',
                background: active ? C.sandFaint : 'transparent',
                border: `1px solid ${active ? C.sand : C.border}`,
                color: active ? C.textPrimary : C.textMuted,
                fontFamily:'Montserrat,sans-serif',fontSize:11,fontWeight:600,letterSpacing:'0.04em',
                transition:'all 0.18s ease',
              }}>
              <Icon name={o.icon} size={16} color={active ? C.sand : C.textMuted}/>
              {o.l}
            </button>
          );
        })}
      </div>
    </div>
  );
};

// ─── Language section ──────────────────────────────────────────
const LanguageSection = () => {
  const tr = useT();
  const [lang, setL] = React.useState(getLang);
  const choose = (v) => { setL(v); setLang(v); };
  const options = [
    { v:'en', l:tr('profile.langEn') },
    { v:'es', l:tr('profile.langEs') },
  ];
  return (
    <div style={{marginTop:20,paddingTop:18,borderTop:`1px solid ${C.border}`}}>
      <div style={{fontSize:10,fontWeight:700,letterSpacing:'0.2em',color:C.textFaint,textTransform:'uppercase',marginBottom:6}}>{tr('profile.language')}</div>
      <div style={{fontSize:11,fontWeight:300,color:C.textMuted,marginBottom:12,fontStyle:'italic',letterSpacing:'0.02em'}}>
        {tr('profile.languageHint')}
      </div>
      <div style={{display:'grid',gridTemplateColumns:'repeat(2,1fr)',gap:8}}>
        {options.map(o => {
          const active = lang === o.v;
          return (
            <button key={o.v} onClick={()=>choose(o.v)}
              style={{
                display:'flex',alignItems:'center',justifyContent:'center',gap:6,
                padding:'12px 8px',borderRadius:10,cursor:'pointer',
                background: active ? C.sandFaint : 'transparent',
                border: `1px solid ${active ? C.sand : C.border}`,
                color: active ? C.textPrimary : C.textMuted,
                fontFamily:'Montserrat,sans-serif',fontSize:11,fontWeight:600,letterSpacing:'0.04em',
                transition:'all 0.18s ease',
              }}>
              {o.l}
            </button>
          );
        })}
      </div>
    </div>
  );
};

// ─── Developer Tools section (inside ProfileModal) ──────────────
const RESET_OPTIONS = [
  { key:'habits',   labelKey:'dev.categoryHabits',   desc:'Habits, areas, and check-ins.' },
  { key:'tasks',    labelKey:'dev.categoryTasks',    desc:'All tasks.' },
  { key:'ideas',    labelKey:'dev.categoryIdeas',    desc:'All captured content ideas.' },
  { key:'reading',  labelKey:'dev.categoryReading',  desc:'Books, reading notes, and goals.' },
  { key:'mood',     labelKey:'dev.categoryMood',     desc:'Daily mood entries.' },
  { key:'focus',    labelKey:'dev.categoryFocus',    desc:'Focus sessions, if any.' },
  { key:'workouts', labelKey:'dev.categoryWorkouts', desc:'Legacy workout data, if any.' },
  { key:'notes',    labelKey:'dev.categoryNotes',    desc:'Quick notes and affirmations.' },
];
const RESET_LOCAL_KEY = '__local__';

const DeveloperTools = ({ store }) => {
  const tr = useT();
  const [open, setOpen]               = React.useState(false);
  const [selected, setSelected]       = React.useState(() => new Set());
  const [confirmText, setConfirmText] = React.useState('');
  const [busy, setBusy]               = React.useState(false);
  const [msg, setMsg]                 = React.useState('');
  const [err, setErr]                 = React.useState('');
  const [summary, setSummary]         = React.useState(null); // {done:[], failed:[]}

  const allDbKeys = RESET_OPTIONS.map(o => o.key);
  const allChecked = allDbKeys.every(k => selected.has(k)) && selected.has(RESET_LOCAL_KEY);
  const noneSelected = selected.size === 0;
  const canReset = !noneSelected && confirmText === 'RESET' && !busy;

  const toggle = (key) => {
    setSelected(prev => {
      const next = new Set(prev);
      next.has(key) ? next.delete(key) : next.add(key);
      return next;
    });
    setErr(''); setMsg(''); setSummary(null);
  };
  const toggleAll = () => {
    if (allChecked) setSelected(new Set());
    else setSelected(new Set([...allDbKeys, RESET_LOCAL_KEY]));
    setErr(''); setMsg(''); setSummary(null);
  };

  const clearLocal = () => {
    try {
      const toDelete = [];
      for (let i = 0; i < localStorage.length; i++) {
        const k = localStorage.key(i);
        if (k && (k.startsWith('vyb-') || k.startsWith('vyb_'))) toDelete.push(k);
      }
      for (const k of toDelete) localStorage.removeItem(k);
      return { ok: true };
    } catch (e) {
      return { ok: false, error: e.message || 'localStorage error' };
    }
  };

  const doReset = async () => {
    if (!canReset) return;
    setBusy(true); setErr(''); setMsg(''); setSummary(null);

    const dbKeys = [...selected].filter(k => k !== RESET_LOCAL_KEY);
    const wantLocal = selected.has(RESET_LOCAL_KEY);
    const done = [];
    const failed = [];

    try {
      if (dbKeys.length && store?.resetAccountData) {
        const r = await store.resetAccountData(dbKeys);
        const failedSet = new Set((r.errors || []).map(e => e.category));
        const labelOf = (k) => {
          const o = RESET_OPTIONS.find(o => o.key === k);
          return o ? tr(o.labelKey) : k;
        };
        for (const k of dbKeys) {
          if (failedSet.has(k)) {
            const errs = (r.errors || []).filter(e => e.category === k);
            failed.push({ label: labelOf(k), tables: errs.map(e => e.table).join(', ') });
          } else {
            done.push(labelOf(k));
          }
        }
      }
      if (wantLocal) {
        const r = clearLocal();
        if (r.ok) done.push(tr('dev.categoryLocal'));
        else failed.push({ label: tr('dev.categoryLocal'), tables: r.error || 'localStorage' });
      }
      setSummary({ done, failed });
      if (failed.length === 0) {
        setMsg(tr('dev.selectedReset'));
        setConfirmText('');
        setSelected(new Set());
      } else {
        setErr(`Some areas failed: ${failed.map(f => f.label).join(', ')}`);
      }
    } catch (e) {
      setErr(e.message || 'Reset failed.');
    } finally {
      setBusy(false);
    }
  };

  return (
    <div style={{marginTop:20,paddingTop:18,borderTop:`1px solid ${C.border}`}}>
      <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',cursor:'pointer'}}
        onClick={()=>setOpen(o=>!o)}>
        <div style={{fontSize:10,fontWeight:700,letterSpacing:'0.22em',color:C.textFaint,textTransform:'uppercase'}}>
          {tr('profile.developerTools')}
        </div>
        <Icon name={open?'chevron-up':'chevron-down'} size={14} color={C.textFaint}/>
      </div>

      {open && (
        <div style={{marginTop:14}}>
          <div style={{padding:'14px 14px 12px',borderRadius:10,border:`1px solid ${C.border}`,
            background:'rgba(255,255,255,0.02)'}}>
            <div style={{fontSize:11,fontWeight:600,color:C.textPrimary,letterSpacing:'0.02em',marginBottom:6}}>
              {tr('dev.reset')}
            </div>
            <div style={{fontSize:11,fontWeight:300,color:C.textMuted,lineHeight:1.5,marginBottom:14,fontStyle:'italic'}}>
              {tr('dev.chooseWhatToReset')}
            </div>

            {/* Category checkboxes */}
            <div style={{display:'flex',flexDirection:'column',gap:4,marginBottom:10}}>
              {RESET_OPTIONS.map(o => (
                <CheckRow key={o.key} checked={selected.has(o.key)} onToggle={()=>toggle(o.key)}
                  label={tr(o.labelKey)} desc={o.desc}/>
              ))}
              <CheckRow checked={selected.has(RESET_LOCAL_KEY)} onToggle={()=>toggle(RESET_LOCAL_KEY)}
                label={tr('dev.categoryLocal')} desc={tr('dev.localDesc')}/>
            </div>

            {/* Select all */}
            <div onClick={toggleAll}
              style={{fontSize:10,fontWeight:600,letterSpacing:'0.16em',textTransform:'uppercase',
                color:allChecked?C.sand:C.textFaint,cursor:'pointer',padding:'6px 0',marginBottom:10}}>
              {allChecked ? tr('dev.selectAllOn') : tr('dev.selectAllOff')}
            </div>

            {/* Confirmation */}
            <div style={{fontSize:9,fontWeight:600,letterSpacing:'0.18em',color:C.textFaint,
              textTransform:'uppercase',marginBottom:6}}>
              {tr('dev.typeResetToConfirm')}
            </div>
            <Input value={confirmText} onChange={e=>setConfirmText(e.target.value)}
              placeholder="RESET" style={{fontSize:12,padding:'9px 12px',marginBottom:10}}/>

            {noneSelected && (
              <div style={{fontSize:10,fontWeight:300,color:C.sand,fontStyle:'italic',marginBottom:8}}>
                {tr('dev.selectAtLeastOne')}
              </div>
            )}

            <Button variant="danger" size="sm" icon="trash-2"
              onClick={canReset ? doReset : (()=>{})}
              style={{width:'100%',opacity: canReset?1:0.4, cursor: canReset?'pointer':'not-allowed',
                pointerEvents: canReset?'auto':'none'}}>
              {busy ? tr('dev.resetting') : tr('dev.resetSelected')}
            </Button>
          </div>

          {msg && <div style={{marginTop:10,fontSize:11,color:C.sageLight,fontWeight:400}}>{msg}</div>}
          {err && <div style={{marginTop:10,fontSize:11,color:'#D67B7B',fontWeight:400}}>{err}</div>}

          {summary && (summary.done.length > 0 || summary.failed.length > 0) && (
            <div style={{marginTop:10,padding:'10px 12px',borderRadius:8,border:`1px solid ${C.border}`,
              background:'rgba(255,255,255,0.02)'}}>
              <div style={{fontSize:9,fontWeight:700,letterSpacing:'0.18em',color:C.textFaint,
                textTransform:'uppercase',marginBottom:6}}>{tr('dev.resetComplete')}</div>
              {summary.done.map(d => (
                <div key={d} style={{fontSize:11,color:C.textSecondary,padding:'2px 0'}}>
                  <span style={{color:C.sageLight}}>✓</span> {d}
                </div>
              ))}
              {summary.failed.map(f => (
                <div key={f.label} style={{fontSize:11,color:'#D67B7B',padding:'2px 0'}}>
                  ✗ {f.label} <span style={{color:C.textFaint,fontSize:10}}>({f.tables})</span>
                </div>
              ))}
            </div>
          )}
        </div>
      )}
    </div>
  );
};

const CheckRow = ({ checked, onToggle, label, desc }) => (
  <div onClick={onToggle}
    style={{display:'flex',alignItems:'flex-start',gap:10,padding:'8px 8px',borderRadius:8,
      cursor:'pointer',background: checked ? 'rgba(160,138,86,0.06)' : 'transparent',
      border:`1px solid ${checked ? C.sand : 'transparent'}`,transition:'all 0.15s'}}>
    <div style={{width:16,height:16,borderRadius:4,flexShrink:0,marginTop:1,
      background: checked ? C.sand : 'transparent',
      border:`1px solid ${checked ? C.sand : C.borderMid}`,
      display:'flex',alignItems:'center',justifyContent:'center'}}>
      {checked && <Icon name="check" size={11} color={C.bg} sw={3}/>}
    </div>
    <div style={{flex:1,minWidth:0}}>
      <div style={{fontSize:12,fontWeight:600,color: checked ? C.textPrimary : C.textSecondary,letterSpacing:'-0.005em'}}>{label}</div>
      <div style={{fontSize:10.5,fontWeight:300,color:C.textFaint,marginTop:1,lineHeight:1.4}}>{desc}</div>
    </div>
  </div>
);

// ─── Modal shell ────────────────────────────────────────────────
const ModalShell = ({ title, subtitle, onClose, children, maxWidth=460 }) => (
  <div onClick={onClose} className="vyb-modal-shell-v2"
    style={{position:'fixed',inset:0,background:'var(--c-overlay)',backdropFilter:'blur(6px)',WebkitBackdropFilter:'blur(6px)',
      zIndex:1500,display:'flex',alignItems:'center',justifyContent:'center',padding:24}}>
    <div onClick={e=>e.stopPropagation()} className="view-fade vyb-modal-panel-v2"
      style={{width:'100%',maxWidth,background:C.card,border:`1px solid ${C.borderMid}`,borderRadius:18,
        boxShadow:'0 40px 100px rgba(0,0,0,0.7)',
        maxHeight:'calc(100dvh - 48px)',display:'flex',flexDirection:'column',overflow:'hidden'}}>
      <div className="vyb-modal-head-v2"
        style={{flexShrink:0,display:'flex',justifyContent:'space-between',alignItems:'flex-start',gap:12,
          padding:'24px 28px 14px',borderBottom:`1px solid ${C.border}`,background:C.card}}>
        <div style={{minWidth:0}}>
          <div style={{fontSize:11,fontWeight:700,letterSpacing:'0.22em',textTransform:'uppercase',color:C.textPrimary}}>{title}</div>
          {subtitle && <div style={{fontSize:11,fontWeight:300,color:C.textMuted,marginTop:4,fontStyle:'italic',letterSpacing:'0.02em'}}>{subtitle}</div>}
        </div>
        <IconButton icon="x" onClick={onClose} color={C.textMuted}/>
      </div>
      <div className="vyb-modal-body-v2"
        style={{flex:1,minHeight:0,overflowY:'auto',WebkitOverflowScrolling:'touch',overscrollBehavior:'contain',
          padding:'18px 28px calc(28px + env(safe-area-inset-bottom))'}}>
        {children}
      </div>
    </div>
  </div>
);

const Row = ({ label, value }) => (
  <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',padding:'10px 0',borderBottom:`1px solid ${C.border}`}}>
    <div style={{fontSize:10,fontWeight:600,letterSpacing:'0.2em',color:C.textFaint,textTransform:'uppercase'}}>{label}</div>
    <div style={{fontSize:12,fontWeight:400,color:C.textSecondary,textAlign:'right',maxWidth:'60%',overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{value}</div>
  </div>
);

const SectionHeader = ({ label, hint }) => (
  <div style={{margin:'24px 0 10px'}}>
    <div style={{fontSize:10,fontWeight:700,letterSpacing:'0.22em',textTransform:'uppercase',color:C.textPrimary}}>{label}</div>
    {hint && <div style={{fontSize:11,fontWeight:300,color:C.textFaint,marginTop:4,lineHeight:1.4}}>{hint}</div>}
  </div>
);

// Read-only toggle row for "Coming soon" placeholders.
const ComingSoonToggle = ({ label, desc }) => (
  <div style={{display:'flex',alignItems:'center',gap:12,padding:'10px 0',borderBottom:`1px solid ${C.border}`,opacity:0.65}}>
    <div style={{flex:1,minWidth:0}}>
      <div style={{fontSize:12,fontWeight:600,color:C.textSecondary,letterSpacing:'-0.005em'}}>{label}</div>
      {desc && <div style={{fontSize:10.5,fontWeight:300,color:C.textFaint,marginTop:2,lineHeight:1.4}}>{desc}</div>}
    </div>
    <div title="Coming soon" style={{display:'flex',alignItems:'center',gap:8}}>
      <span style={{fontSize:9,letterSpacing:'0.18em',textTransform:'uppercase',color:C.textFaint}}>Coming soon</span>
      <div style={{width:30,height:16,borderRadius:999,background:C.borderMid,position:'relative',cursor:'not-allowed'}}>
        <div style={{position:'absolute',top:2,left:2,width:12,height:12,borderRadius:999,background:C.bg}}/>
      </div>
    </div>
  </div>
);

// ─── Artifact / momentum lookups (safe if Momentum not yet loaded) ─
// Single source of truth: window.ARTIFACTS / window.PATHS (set by Momentum).
// Future: extract to dashboard-artifacts.jsx so Profile + Momentum + future
// public profile route share one definition.
const RARITY_ORDER = ['Signal','Rare Signal','Prime Signal','Legacy Signal','Mythic Signal'];
const RARITY_RANK = (r) => Math.max(0, RARITY_ORDER.indexOf(r));
const getArtifactById = (id) => {
  const A = (typeof window !== 'undefined' && window.ARTIFACTS) || null;
  if (A && A[id]) return A[id];
  return { id, title: id, rarity: 'Signal', description: '', iconType: 'ring' };
};
const allArtifacts = () => {
  const A = (typeof window !== 'undefined' && window.ARTIFACTS) || {};
  return Object.values(A);
};
// Backward-compatible storage. New keys: vyb-unlocked-aura / vyb-active-aura.
// Old keys: vyb-unlocked-artifacts / vyb-active-artifact (auto-migrated).
const _LS_NEW_UNLOCKED = 'vyb-unlocked-aura';
const _LS_OLD_UNLOCKED = 'vyb-unlocked-artifacts';
const _LS_NEW_ACTIVE   = 'vyb-active-aura';
const _LS_OLD_ACTIVE   = 'vyb-active-artifact';
const readUnlockedIds = () => {
  try {
    let raw = localStorage.getItem(_LS_NEW_UNLOCKED);
    if (!raw) {
      raw = localStorage.getItem(_LS_OLD_UNLOCKED);
      if (raw) localStorage.setItem(_LS_NEW_UNLOCKED, raw);
    }
    if (!raw) return new Set();
    const arr = JSON.parse(raw);
    return new Set(Array.isArray(arr) ? arr : []);
  } catch { return new Set(); }
};
const readUnlockedArtifactList = () => Array.from(readUnlockedIds()).map(getArtifactById);
const readActiveArtifactId = () => {
  try {
    let id = localStorage.getItem(_LS_NEW_ACTIVE);
    if (!id) {
      id = localStorage.getItem(_LS_OLD_ACTIVE);
      if (id) localStorage.setItem(_LS_NEW_ACTIVE, id);
    }
    return id || null;
  } catch { return null; }
};
const writeActiveArtifactId = (id) => {
  try {
    if (id) {
      localStorage.setItem(_LS_NEW_ACTIVE, id);
      localStorage.setItem(_LS_OLD_ACTIVE, id);
    } else {
      localStorage.removeItem(_LS_NEW_ACTIVE);
      localStorage.removeItem(_LS_OLD_ACTIVE);
    }
  } catch {}
};
const rarestOf = (list) => {
  if (!list.length) return null;
  return list.slice().sort((a,b) => RARITY_RANK(b.rarity) - RARITY_RANK(a.rarity))[0];
};

// Build artifact id → { pathTitle, stageNumber } from window.PATHS.
const _pathInfoCache = { built:false, map:{} };
const buildPathInfo = () => {
  if (_pathInfoCache.built) return _pathInfoCache.map;
  const PATHS = (typeof window !== 'undefined' && window.PATHS) || [];
  const map = {};
  PATHS.forEach(p => {
    let stageNum = 0;
    (p.stages || []).forEach(s => {
      if (s.locked) return;
      stageNum += 1;
      if (s.reward) map[s.reward] = { pathTitle: p.title, stageNumber: stageNum };
    });
  });
  if (PATHS.length) { _pathInfoCache.built = true; _pathInfoCache.map = map; }
  return map;
};
const PATH_TITLE_BY_ID = { system_builder:'System Builder', reader_path:'Reader Path', creator_path:'Creator Path' };
const sourcePathTitleFor = (artifact) => {
  if (!artifact) return '';
  return PATH_TITLE_BY_ID[artifact.sourcePath] || (artifact.sourcePath || '');
};
const requirementFor = (artifact) => {
  if (!artifact) return '';
  const info = buildPathInfo()[artifact.id];
  if (info) return `Complete ${info.pathTitle} Stage ${info.stageNumber}`;
  const path = sourcePathTitleFor(artifact);
  return path ? `Unlock through ${path}` : 'Locked';
};

// Public profile toggle (local-only for now). No server, no exposure.
// TODO future:
//   • public username
//   • /u/:username route
//   • RLS-backed publish_profile() write
//   • friend visibility tiers
//   • activity event log
const PUBLIC_PROFILE_KEY = 'vyb-public-profile-enabled';
const readPublicProfileEnabled = () => {
  try { return localStorage.getItem(PUBLIC_PROFILE_KEY) === '1'; } catch { return false; }
};
const writePublicProfileEnabled = (on) => {
  try { localStorage.setItem(PUBLIC_PROFILE_KEY, on ? '1' : '0'); } catch {}
};

// Functional on/off pill — local toggle only.
const ToggleRow = ({ label, desc, value, onChange }) => (
  <div style={{display:'flex',alignItems:'center',gap:12,padding:'12px 0',borderBottom:`1px solid ${C.border}`}}>
    <div style={{flex:1,minWidth:0}}>
      <div style={{fontSize:12,fontWeight:600,color:C.textPrimary,letterSpacing:'-0.005em'}}>{label}</div>
      {desc && <div style={{fontSize:10.5,fontWeight:300,color:C.textFaint,marginTop:2,lineHeight:1.4}}>{desc}</div>}
    </div>
    <div onClick={()=>onChange(!value)} role="switch" aria-checked={value}
      style={{width:34,height:18,borderRadius:999,position:'relative',cursor:'pointer',
        background: value ? C.sand : C.borderMid, transition:'background 0.18s'}}>
      <div style={{position:'absolute',top:2,left: value ? 18 : 2,width:14,height:14,borderRadius:999,
        background: value ? C.bg : C.textFaint, transition:'left 0.18s'}}/>
    </div>
  </div>
);

// Compact stat for weekly summary.
const StatChip = ({ label, value }) => (
  <div style={{padding:'12px 14px',background:C.cardSubtle || 'rgba(255,255,255,0.02)',
    border:`1px solid ${C.border}`,borderRadius:12,minWidth:0}}>
    <div style={{fontSize:20,fontWeight:800,color:C.textPrimary,fontStyle:'italic',letterSpacing:'-0.01em'}}>{value}</div>
    <div style={{fontSize:9.5,fontWeight:600,letterSpacing:'0.18em',textTransform:'uppercase',color:C.textFaint,marginTop:4}}>{label}</div>
  </div>
);

// Rarity glow strength scales with rarity tier — keeps premium feel,
// avoids cartoon level-up. Used by ShowcaseCard + CollectionCard.
const rarityGlow = (rarity) => {
  const rank = RARITY_RANK(rarity);
  const W = (typeof window !== 'undefined' && window.RARITY_STYLE) || {};
  const r = W[rarity] || { color:'#A08A56', glow:'rgba(160,138,86,0.18)', border:'rgba(160,138,86,0.45)' };
  // shadow strength escalates: 0..28px
  const blur = [10, 16, 22, 26, 32][rank] || 10;
  const inner = [0.08, 0.12, 0.18, 0.22, 0.28][rank] || 0.08;
  return {
    color: r.color, glow: r.glow, border: r.border,
    boxShadow: `0 0 ${blur}px ${r.glow}`,
    bg: `radial-gradient(120% 80% at 50% 0%, rgba(255,255,255,${inner * 0.5}) 0%, transparent 70%)`,
  };
};

// Featured artifact card (Active / Rarest). Larger, premium.
const ShowcaseCard = ({ artifact, label, helper, isActive, emptyTitle, emptyHint, onCta, ctaLabel }) => {
  const Sigil = (typeof window !== 'undefined' && window.ArtifactSigil) || null;
  const Pill = (typeof window !== 'undefined' && window.RarityPill) || null;
  const g = artifact ? rarityGlow(artifact.rarity) : null;
  return (
    <div style={{position:'relative',padding:18,borderRadius:16,minHeight:160,display:'flex',flexDirection:'column',
      border: artifact ? `1px solid ${g.border}` : `1px solid ${C.border}`,
      background: artifact
        ? `linear-gradient(160deg, rgba(255,255,255,0.025), rgba(0,0,0,0.18))`
        : 'rgba(255,255,255,0.02)',
      boxShadow: artifact ? g.boxShadow : 'none', overflow:'hidden'}}>
      {artifact && <div style={{position:'absolute',inset:0,background:g.bg,pointerEvents:'none'}}/>}
      <div style={{position:'relative',display:'flex',justifyContent:'space-between',alignItems:'flex-start',marginBottom:12,gap:10}}>
        <div>
          <div style={{fontSize:9.5,fontWeight:700,letterSpacing:'0.22em',textTransform:'uppercase',color:C.textPrimary}}>{label}</div>
          {helper && <div style={{fontSize:10.5,fontWeight:300,color:C.textFaint,marginTop:3,fontStyle:'italic'}}>{helper}</div>}
        </div>
        {isActive && artifact && (
          <span style={{fontSize:9,fontWeight:700,letterSpacing:'0.18em',textTransform:'uppercase',
            padding:'3px 8px',borderRadius:999,background:'rgba(156,203,177,0.12)',
            color:'#9CCBB1',border:'1px solid rgba(156,203,177,0.4)'}}>Active</span>
        )}
      </div>
      {artifact ? (
        <div style={{position:'relative',display:'flex',gap:16,alignItems:'center',flex:1}}>
          {Sigil && <Sigil artifact={artifact} size={64} glow/>}
          <div style={{minWidth:0,flex:1}}>
            <div style={{fontSize:16,fontWeight:800,color:C.textPrimary,letterSpacing:'-0.01em',marginBottom:6}}>{artifact.title}</div>
            {Pill ? <Pill rarity={artifact.rarity}/> :
              <div style={{fontSize:9.5,fontWeight:700,letterSpacing:'0.18em',color:C.sandLight,textTransform:'uppercase'}}>{artifact.rarity}</div>}
            {artifact.description && <div style={{fontSize:11,fontWeight:300,color:C.textMuted,marginTop:8,lineHeight:1.5}}>{artifact.description}</div>}
            {sourcePathTitleFor(artifact) && (
              <div style={{fontSize:10,fontWeight:500,color:C.textFaint,marginTop:8,letterSpacing:'0.04em'}}>
                Source path: <span style={{color:C.textSecondary}}>{sourcePathTitleFor(artifact)}</span>
              </div>
            )}
          </div>
        </div>
      ) : (
        <div style={{flex:1,display:'flex',flexDirection:'column',justifyContent:'center'}}>
          <div style={{fontSize:13,fontWeight:600,color:C.textSecondary,fontStyle:'italic'}}>{emptyTitle}</div>
          {emptyHint && <div style={{fontSize:11,fontWeight:300,color:C.textFaint,marginTop:6,lineHeight:1.4}}>{emptyHint}</div>}
          {onCta && (
            <div onClick={onCta} style={{marginTop:12,fontSize:10.5,fontWeight:600,letterSpacing:'0.16em',
              textTransform:'uppercase',color:C.sandLight,cursor:'pointer',display:'inline-flex',alignItems:'center',gap:6}}>
              {ctaLabel} <Icon name="arrow-right" size={12} color={C.sandLight}/>
            </div>
          )}
        </div>
      )}
    </div>
  );
};

// Collection card — compact, used in the grid below the showcase.
const CollectionCard = ({ artifact, unlocked, isActive, onSetActive }) => {
  const Sigil = (typeof window !== 'undefined' && window.ArtifactSigil) || null;
  const Pill = (typeof window !== 'undefined' && window.RarityPill) || null;
  const g = unlocked ? rarityGlow(artifact.rarity) : null;
  return (
    <div style={{position:'relative',padding:14,borderRadius:12,
      border:`1px solid ${unlocked ? g.border : C.border}`,
      background: unlocked
        ? `linear-gradient(160deg, rgba(255,255,255,0.025), rgba(0,0,0,0.18))`
        : 'rgba(255,255,255,0.015)',
      boxShadow: unlocked ? g.boxShadow : 'none',
      opacity: unlocked ? 1 : 0.62,
      display:'flex',flexDirection:'column',gap:10,minHeight:160,overflow:'hidden'}}>
      {unlocked && <div style={{position:'absolute',inset:0,background:g.bg,pointerEvents:'none'}}/>}
      <div style={{position:'relative',display:'flex',gap:10,alignItems:'center'}}>
        {Sigil && <Sigil artifact={artifact} size={36} dim={!unlocked}/>}
        <div style={{minWidth:0,flex:1}}>
          <div style={{fontSize:12,fontWeight:700,color: unlocked ? C.textPrimary : C.textSecondary,letterSpacing:'-0.005em',whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{artifact.title}</div>
          {Pill && <div style={{marginTop:4}}><Pill rarity={artifact.rarity} dim={!unlocked}/></div>}
        </div>
        {!unlocked && (
          <span title="Locked" style={{display:'inline-flex',alignItems:'center',justifyContent:'center',
            width:22,height:22,borderRadius:999,background:'rgba(0,0,0,0.25)',border:`1px solid ${C.border}`}}>
            <Icon name="lock" size={11} color={C.textFaint}/>
          </span>
        )}
      </div>
      <div style={{position:'relative',fontSize:10.5,fontWeight:300,color:C.textMuted,lineHeight:1.45,flex:1}}>
        {unlocked ? (artifact.description || '') : requirementFor(artifact)}
      </div>
      <div style={{position:'relative',display:'flex',justifyContent:'space-between',alignItems:'center',gap:8}}>
        <span style={{fontSize:9,fontWeight:600,letterSpacing:'0.14em',color:C.textFaint,textTransform:'uppercase',whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>
          {sourcePathTitleFor(artifact)}
        </span>
        {unlocked ? (
          isActive ? (
            <span style={{fontSize:9,fontWeight:700,letterSpacing:'0.16em',textTransform:'uppercase',
              padding:'4px 8px',borderRadius:999,background:'rgba(156,203,177,0.12)',
              color:'#9CCBB1',border:'1px solid rgba(156,203,177,0.4)'}}>Active</span>
          ) : (
            <button type="button" onClick={onSetActive}
              style={{fontSize:9,fontWeight:700,letterSpacing:'0.16em',textTransform:'uppercase',
                padding:'4px 10px',borderRadius:999,cursor:'pointer',
                background:'transparent',color:C.sandLight,border:`1px solid ${C.sandGlow}`}}>
              Set as Active Aura
            </button>
          )
        ) : (
          <span style={{fontSize:9,fontWeight:700,letterSpacing:'0.16em',textTransform:'uppercase',color:C.textFaint}}>Locked</span>
        )}
      </div>
    </div>
  );
};

// ─── Profile modal (identity + safe public-style preview) ───────
// Profile is the user's IDENTITY surface. App preferences + dev
// tools live in SettingsModal. Share PROOF, not private details.
//
// Safe surface (NEVER includes free-form text):
//   • avatar / name / email  • active artifact
//   • rarest artifact         • unlocked artifact count
//   • weekly count summary    • path stage progress
// NEVER shown:
//   • task titles, idea text, reading entries, notes, mood, habit names
//
// TODO future:
//   • public username field
//   • /u/:username route + RLS publish_profile()
//   • friend visibility tiers
//   • activity event log w/ SAFE_SOCIAL_EVENT_TYPES guard
const ProfileModal = ({ session, profileName, store, onClose, onOpenSettings, onOpenCircle, onGoTo }) => {
  const u = session?.user || {};
  const meta = u.user_metadata || {};
  const name = profileName || meta.full_name || meta.name || '';
  const email = u.email || '';
  const avatar = meta.avatar_url || meta.picture || '';
  const initial = (name || email || '?').charAt(0).toUpperCase();

  const [unlockedIds, setUnlockedIds] = React.useState(readUnlockedIds);
  const [activeId, setActiveIdState] = React.useState(readActiveArtifactId);
  const [publicOn, setPublicOn] = React.useState(readPublicProfileEnabled);
  const [toast, setToast] = React.useState('');
  const [activityEvents, setActivityEvents] = React.useState(() => {
    try {
      return (window.buildSafeActivityEvents && store)
        ? window.buildSafeActivityEvents({ storeState: store.state })
        : [];
    } catch { return []; }
  });

  // Refresh from storage whenever modal opens (artifacts may have unlocked).
  React.useEffect(() => {
    setUnlockedIds(readUnlockedIds());
    setActiveIdState(readActiveArtifactId());
    try {
      if (window.buildSafeActivityEvents && store) {
        setActivityEvents(window.buildSafeActivityEvents({ storeState: store.state }));
      }
    } catch {}
  }, []);

  const togglePublic = (on) => { setPublicOn(on); writePublicProfileEnabled(on); };

  const setActiveArtifact = (id) => {
    if (!unlockedIds.has(id)) return; // safety: locked cannot be active
    writeActiveArtifactId(id);
    setActiveIdState(id);
    setToast('Active aura updated.');
    setTimeout(() => setToast(''), 1800);
  };

  // Build derived state.
  const ALL = allArtifacts();
  const totalArtifacts = ALL.length || 7;
  // Fallback: if active id no longer unlocked or unknown, treat as none.
  const activeSafe = (activeId && unlockedIds.has(activeId)) ? getArtifactById(activeId) : null;
  const unlocked = Array.from(unlockedIds).map(getArtifactById);
  const rarest = rarestOf(unlocked);
  const active = activeSafe;
  // Collection ordering: unlocked first (by rarity desc), then locked (by rarity asc).
  const collection = [...ALL].sort((a, b) => {
    const ua = unlockedIds.has(a.id) ? 1 : 0;
    const ub = unlockedIds.has(b.id) ? 1 : 0;
    if (ua !== ub) return ub - ua;
    return ua === 1
      ? RARITY_RANK(b.rarity) - RARITY_RANK(a.rarity)
      : RARITY_RANK(a.rarity) - RARITY_RANK(b.rarity);
  });
  const goMomentum = () => onGoTo && onGoTo('momentum');

  // Weekly momentum summary (safe counts only — no titles/text).
  const calc = (typeof window !== 'undefined' && window.calculateMomentum) || (() => null);
  const m = store ? calc({
    habits: store.state.habits,
    tasks:  store.state.tasks,
    ideas:  store.state.ideas,
    books:  store.state.books,
    habitCategories: store.state.habitCategories,
  }) : null;
  const totals = (m && m.totals) || {};
  const fullDays = totals.fullHabitDays || 0;
  const wkHabits = totals.habitsCompleted || 0;
  const wkTasks = totals.tasksCompleted || 0;
  const wkIdeas = totals.ideasCaptured || 0;
  const wkReading = totals.readingSessions || 0;
  const wkPages = totals.pagesRead || 0;
  const booksFinished = ((store && store.state.books) || []).filter(b => b && b.totalPages && (b.currentPage || 0) >= b.totalPages).length;
  const hasAnyData = (wkHabits + wkTasks + wkIdeas + wkReading + fullDays) > 0;

  return (
    <ModalShell title="Profile" subtitle="Share proof, not private details." onClose={onClose} maxWidth={620}>
      {/* Header */}
      <div style={{display:'flex',alignItems:'center',gap:16,marginBottom:18}}>
        {avatar ? (
          <img src={avatar} alt="" style={{width:72,height:72,borderRadius:999,objectFit:'cover',border:`1px solid ${C.sandGlow}`}}/>
        ) : (
          <div style={{width:72,height:72,borderRadius:999,background:C.sandFaint,border:`1px solid ${C.sandGlow}`,display:'flex',alignItems:'center',justifyContent:'center'}}>
            <span style={{fontSize:30,fontWeight:800,color:C.sandLight,fontStyle:'italic'}}>{initial}</span>
          </div>
        )}
        <div style={{minWidth:0,flex:1}}>
          <div style={{fontSize:20,fontWeight:800,fontStyle:'italic',color:C.textPrimary,letterSpacing:'-0.01em',textTransform:'uppercase',lineHeight:1.1,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{name || 'Anonymous'}</div>
          <div style={{fontSize:12,fontWeight:300,color:C.textMuted,marginTop:4,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{email}</div>
          <div style={{display:'flex',gap:8,marginTop:8,flexWrap:'wrap'}}>
            <span style={{fontSize:9,fontWeight:700,letterSpacing:'0.18em',textTransform:'uppercase',
              padding:'3px 8px',borderRadius:999,
              background: publicOn ? 'rgba(156,203,177,0.12)' : 'rgba(255,255,255,0.04)',
              color: publicOn ? '#9CCBB1' : C.textFaint,
              border:`1px solid ${publicOn ? 'rgba(156,203,177,0.4)' : C.border}`}}>
              Public Profile: {publicOn ? 'On' : 'Off'}
            </span>
            <span style={{fontSize:9,fontWeight:700,letterSpacing:'0.18em',textTransform:'uppercase',
              padding:'3px 8px',borderRadius:999,background:'rgba(160,138,86,0.10)',
              color:C.sandLight,border:`1px solid ${C.sandGlow}`}}>
              Private preview
            </span>
          </div>
        </div>
      </div>

      {/* Public profile toggle */}
      <SectionHeader label="Public profile" hint="Off by default. Your public profile will share progress signals, not private details."/>
      <ToggleRow label="Public Profile" value={publicOn} onChange={togglePublic}
        desc={publicOn ? 'On — this is a private preview for now. No data leaves the app.' : 'Off — nothing is shared.'}/>

      {/* ─── Aura Showcase ──────────────────────────────────────── */}
      <SectionHeader label="Aura Showcase" hint="Proof of progress, made visible."/>

      {/* Compact stat row */}
      <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fit,minmax(150px,1fr))',gap:10,marginBottom:12}}>
        <StatChip label="Aura unlocked" value={`${unlocked.length}/${totalArtifacts}`}/>
        <StatChip label="Highest aura" value={rarest ? (window.displayRarity ? window.displayRarity(rarest.rarity) : rarest.rarity) : 'None'}/>
        <StatChip label="Active aura" value={active ? active.title : 'None'}/>
      </div>

      {/* Active + Highest featured cards */}
      <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fit,minmax(260px,1fr))',gap:12,marginBottom:18}}>
        <ShowcaseCard label="Active Aura" helper="Your current progress signal."
          artifact={active} isActive
          emptyTitle="No active aura yet."
          emptyHint="Unlock aura in Momentum and set it as active."
          onCta={goMomentum} ctaLabel="Open Momentum"/>
        <ShowcaseCard label="Highest Aura" helper="Your rarest unlocked signal."
          artifact={rarest}
          emptyTitle="No highest aura yet."
          emptyHint="Complete stages to unlock your first aura signal."
          onCta={goMomentum} ctaLabel="Open Momentum"/>
      </div>

      {/* Full collection */}
      <SectionHeader label="Aura Collection" hint="Proof of what you've built."/>
      {collection.length ? (
        <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fit,minmax(200px,1fr))',gap:10}}>
          {collection.map(a => (
            <CollectionCard key={a.id} artifact={a}
              unlocked={unlockedIds.has(a.id)}
              isActive={activeId === a.id}
              onSetActive={() => setActiveArtifact(a.id)}/>
          ))}
        </div>
      ) : (
        <div style={{padding:14,border:`1px dashed ${C.border}`,borderRadius:12,fontSize:11,color:C.textFaint,textAlign:'center'}}>
          No aura defined.
        </div>
      )}

      {/* Weekly momentum — safe counts */}
      <SectionHeader label="This week" hint="Counts only. No titles, ideas, or notes are shown."/>
      {hasAnyData ? (
        <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fit,minmax(110px,1fr))',gap:10}}>
          <StatChip label="Complete days" value={fullDays}/>
          <StatChip label="Habits done" value={wkHabits}/>
          <StatChip label="Tasks done" value={wkTasks}/>
          <StatChip label="Ideas captured" value={wkIdeas}/>
          {wkPages > 0
            ? <StatChip label="Pages read" value={wkPages}/>
            : <StatChip label="Reading sessions" value={wkReading}/>}
        </div>
      ) : (
        <div style={{padding:16,border:`1px dashed ${C.border}`,borderRadius:12,textAlign:'center'}}>
          <div style={{fontSize:12,fontWeight:600,color:C.textSecondary}}>No weekly momentum yet.</div>
          <div style={{fontSize:11,fontWeight:300,color:C.textFaint,marginTop:4}}>Start with your habits, tasks, ideas, and reading.</div>
        </div>
      )}

      {/* Recent Activity — safe progress signals */}
      <SectionHeader label="Recent Activity" hint="Safe progress signals from your system."/>
      {activityEvents && activityEvents.length ? (
        <div style={{display:'flex',flexDirection:'column',gap:8}}>
          {activityEvents.slice(0, 8).map(ev => {
            const def = (window.SAFE_ACTIVITY_EVENT_TYPES || {})[ev.type] || {};
            return (
              <div key={ev.id} style={{display:'flex',alignItems:'center',gap:12,
                padding:'10px 12px',border:`1px solid ${C.border}`,borderRadius:10,
                background:'rgba(255,255,255,0.015)'}}>
                <div style={{width:28,height:28,borderRadius:8,flexShrink:0,
                  background:C.sandFaint,border:`1px solid ${C.sandGlow}`,
                  display:'flex',alignItems:'center',justifyContent:'center'}}>
                  <Icon name={def.icon || 'sparkles'} size={14} color={C.sandLight}/>
                </div>
                <div style={{minWidth:0,flex:1}}>
                  <div style={{fontSize:12,fontWeight:600,color:C.textPrimary,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{ev.title}</div>
                  {ev.description && <div style={{fontSize:11,fontWeight:300,color:C.textMuted,marginTop:2,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{ev.description}</div>}
                </div>
                <div style={{fontSize:10,fontWeight:500,letterSpacing:'0.08em',color:C.textFaint,flexShrink:0,textTransform:'uppercase'}}>
                  {window.formatActivityTime ? window.formatActivityTime(ev.timestamp) : ''}
                </div>
              </div>
            );
          })}
        </div>
      ) : (
        <div style={{padding:16,border:`1px dashed ${C.border}`,borderRadius:12,textAlign:'center'}}>
          <div style={{fontSize:12,fontWeight:600,color:C.textSecondary}}>No activity signals yet.</div>
          <div style={{fontSize:11,fontWeight:300,color:C.textFaint,marginTop:4}}>Complete your system, unlock Aura, or reach a milestone to see activity here.</div>
        </div>
      )}

      {/* Public profile preview */}
      <SectionHeader label="Public profile preview" hint={publicOn ? 'This is what others would see.' : 'Preview — sharing is currently off.'}/>
      <div style={{padding:18,border:`1px solid ${C.borderMid}`,borderRadius:14,
        background:'linear-gradient(135deg, rgba(160,138,86,0.06), rgba(255,255,255,0.01))',
        opacity: publicOn ? 1 : 0.78}}>
        <div style={{display:'flex',gap:14,alignItems:'center',marginBottom:14}}>
          {avatar ? (
            <img src={avatar} alt="" style={{width:48,height:48,borderRadius:999,objectFit:'cover',border:`1px solid ${C.sandGlow}`}}/>
          ) : (
            <div style={{width:48,height:48,borderRadius:999,background:C.sandFaint,border:`1px solid ${C.sandGlow}`,display:'flex',alignItems:'center',justifyContent:'center'}}>
              <span style={{fontSize:20,fontWeight:800,color:C.sandLight,fontStyle:'italic'}}>{initial}</span>
            </div>
          )}
          <div style={{minWidth:0,flex:1}}>
            <div style={{fontSize:15,fontWeight:700,color:C.textPrimary,letterSpacing:'-0.005em'}}>{name || 'Anonymous'}</div>
            <div style={{fontSize:10,fontWeight:600,letterSpacing:'0.16em',textTransform:'uppercase',color:C.textFaint,marginTop:3}}>
              {unlocked.length} aura unlocked
            </div>
          </div>
        </div>
        <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:10,marginBottom:12}}>
          <div style={{padding:10,borderRadius:10,background:'rgba(0,0,0,0.18)',border:`1px solid ${C.border}`}}>
            <div style={{fontSize:9,fontWeight:600,letterSpacing:'0.18em',color:C.textFaint,textTransform:'uppercase',marginBottom:4}}>Active</div>
            <div style={{fontSize:12,fontWeight:600,color: active ? C.textPrimary : C.textFaint}}>
              {active ? active.title : '—'}
            </div>
          </div>
          <div style={{padding:10,borderRadius:10,background:'rgba(0,0,0,0.18)',border:`1px solid ${C.border}`}}>
            <div style={{fontSize:9,fontWeight:600,letterSpacing:'0.18em',color:C.textFaint,textTransform:'uppercase',marginBottom:4}}>Rarest</div>
            <div style={{fontSize:12,fontWeight:600,color: rarest ? C.textPrimary : C.textFaint}}>
              {rarest ? rarest.title : '—'}
            </div>
          </div>
        </div>
        <div style={{fontSize:11,fontWeight:300,color:C.textMuted,lineHeight:1.5}}>
          This week: <b style={{color:C.textSecondary}}>{fullDays}</b> complete days · <b style={{color:C.textSecondary}}>{wkHabits}</b> habits · <b style={{color:C.textSecondary}}>{wkTasks}</b> tasks · <b style={{color:C.textSecondary}}>{wkIdeas}</b> ideas · <b style={{color:C.textSecondary}}>{wkPages > 0 ? `${wkPages} pages` : `${wkReading} reading sessions`}</b>{booksFinished > 0 && <> · <b style={{color:C.textSecondary}}>{booksFinished}</b> {booksFinished === 1 ? 'book finished' : 'books finished'}</>}
        </div>

        {/* Public Activity Preview */}
        <div style={{marginTop:14,paddingTop:14,borderTop:`1px solid ${C.border}`}}>
          <div style={{fontSize:9,fontWeight:700,letterSpacing:'0.18em',color:C.textFaint,textTransform:'uppercase',marginBottom:8}}>Public activity preview</div>
          {activityEvents && activityEvents.filter(e=>e.safeForPublic).length ? (
            <div style={{display:'flex',flexDirection:'column',gap:6}}>
              {activityEvents.filter(e=>e.safeForPublic).slice(0,3).map(ev => {
                const def = (window.SAFE_ACTIVITY_EVENT_TYPES || {})[ev.type] || {};
                return (
                  <div key={ev.id} style={{display:'flex',alignItems:'center',gap:10,fontSize:11,color:C.textSecondary}}>
                    <Icon name={def.icon || 'sparkles'} size={12} color={C.sandLight}/>
                    <span style={{flex:1,minWidth:0,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>
                      {window.renderSafePublicLabel ? window.renderSafePublicLabel(ev, name || 'Anonymous') : ev.title}
                    </span>
                    <span style={{fontSize:9,color:C.textFaint,flexShrink:0,letterSpacing:'0.08em',textTransform:'uppercase'}}>
                      {window.formatActivityTime ? window.formatActivityTime(ev.timestamp) : ''}
                    </span>
                  </div>
                );
              })}
            </div>
          ) : (
            <div style={{fontSize:11,fontWeight:300,color:C.textFaint,fontStyle:'italic'}}>No public activity preview yet.</div>
          )}
          <div style={{fontSize:10,fontWeight:300,color:C.textFaint,marginTop:8,lineHeight:1.5,fontStyle:'italic'}}>
            Only safe progress signals will be shared. Private details stay hidden.
          </div>
        </div>
      </div>

      <div style={{fontSize:10,fontWeight:300,color:C.textFaint,marginTop:14,lineHeight:1.5,fontStyle:'italic'}}>
        Habits, tasks, ideas, notes, mood, and reading content are never shown. Only artifact unlocks, counts, and milestones can ever become public — and only when you turn it on.
      </div>

      {/* Circle card */}
      <SectionHeader label="Circle" hint="Your private progress circle."/>
      <div style={{padding:16,border:`1px solid ${C.borderMid}`,borderRadius:14,
        background:'linear-gradient(135deg, rgba(160,138,86,0.05), rgba(94,117,88,0.04))',
        display:'flex',alignItems:'center',gap:14}}>
        <div style={{width:44,height:44,borderRadius:999,flexShrink:0,
          background:C.sandFaint,border:`1px solid ${C.sandGlow}`,
          display:'flex',alignItems:'center',justifyContent:'center'}}>
          <Icon name="users" size={18} color={C.sandLight}/>
        </div>
        <div style={{minWidth:0,flex:1}}>
          <div style={{fontSize:13,fontWeight:700,color:C.textPrimary,letterSpacing:'-0.005em'}}>No one in your Circle yet.</div>
          <div style={{fontSize:11,fontWeight:300,color:C.textMuted,marginTop:3,lineHeight:1.5}}>
            Friends will see safe progress signals like Aura, streaks, and weekly momentum.
          </div>
        </div>
        <Button variant="ghost" size="sm" icon="arrow-right" onClick={onOpenCircle} style={{flexShrink:0}}>Open Circle</Button>
      </div>

      <div style={{height:18}}/>
      <Button variant="ghost" size="sm" icon="settings" onClick={onOpenSettings} style={{width:'100%'}}>Open Settings</Button>

      {toast && (
        <div style={{position:'fixed',left:'50%',bottom:32,transform:'translateX(-50%)',
          padding:'10px 18px',borderRadius:999,background:'rgba(13,12,11,0.95)',
          border:`1px solid ${C.sandGlow}`,color:C.sandLight,
          fontSize:11,fontWeight:600,letterSpacing:'0.14em',textTransform:'uppercase',
          boxShadow:'0 12px 40px rgba(0,0,0,0.5)',zIndex:2000,
          animation:'fadeIn 0.18s ease-out'}}>
          {toast}
        </div>
      )}
    </ModalShell>
  );
};

// ─── Profile customization (localStorage MVP) ───────────────────
// TODO (future Supabase): move bio/building/becoming/username into a
//   `profiles` table { user_id, username (unique), bio, building,
//   becoming, avatar_url, public_profile_enabled }. Keep editable
//   client-side and sync on save.
const PROFILE_CUSTOM_KEY = 'vyb-profile-customization';
const readProfileCustom = () => {
  try {
    const raw = localStorage.getItem(PROFILE_CUSTOM_KEY);
    const v = raw ? JSON.parse(raw) : {};
    return { bio: v.bio || '', building: v.building || '', becoming: v.becoming || '' };
  } catch { return { bio:'', building:'', becoming:'' }; }
};
const writeProfileCustom = (v) => {
  try { localStorage.setItem(PROFILE_CUSTOM_KEY, JSON.stringify(v)); } catch {}
};

// ─── ProfilePage (full section) ─────────────────────────────────
// Replaces ProfileModal as the primary surface. Rendered inline in
// the main content area like Overview/Momentum/etc. ProfileModal is
// kept for back-compat but no longer wired in.
const ProfilePage = ({ session, profileName, store, onOpenSettings, onOpenCircle, onGoTo }) => {
  const u = session?.user || {};
  const meta = u.user_metadata || {};
  const name = profileName || meta.full_name || meta.name || '';
  const email = u.email || '';
  const avatar = meta.avatar_url || meta.picture || '';
  const initial = (name || email || '?').charAt(0).toUpperCase();
  const username = (email.split('@')[0] || name.toLowerCase().replace(/\s+/g,'') || 'me').slice(0, 32);

  const [unlockedIds, setUnlockedIds] = React.useState(readUnlockedIds);
  const [activeId, setActiveIdState] = React.useState(readActiveArtifactId);
  const [publicOn, setPublicOn] = React.useState(readPublicProfileEnabled);
  const [toast, setToast] = React.useState('');
  const [custom, setCustom] = React.useState(readProfileCustom);
  const [editing, setEditing] = React.useState(false);
  const [draft, setDraft] = React.useState(custom);
  const [activityEvents, setActivityEvents] = React.useState(() => {
    try {
      return (window.buildSafeActivityEvents && store)
        ? window.buildSafeActivityEvents({ storeState: store.state })
        : [];
    } catch { return []; }
  });

  React.useEffect(() => {
    setUnlockedIds(readUnlockedIds());
    setActiveIdState(readActiveArtifactId());
    setCustom(readProfileCustom());
    try {
      if (window.buildSafeActivityEvents && store) {
        setActivityEvents(window.buildSafeActivityEvents({ storeState: store.state }));
      }
    } catch {}
  }, []);

  const togglePublic = (on) => { setPublicOn(on); writePublicProfileEnabled(on); };
  const setActiveArtifact = (id) => {
    if (!unlockedIds.has(id)) return;
    writeActiveArtifactId(id);
    setActiveIdState(id);
    setToast('Active aura updated.');
    setTimeout(() => setToast(''), 1800);
  };

  const startEdit = () => { setDraft(custom); setEditing(true); };
  const cancelEdit = () => { setDraft(custom); setEditing(false); };
  const saveEdit = () => {
    const v = {
      bio: (draft.bio||'').trim(),
      building: (draft.building||'').trim(),
      becoming: (draft.becoming||'').trim(),
    };
    setCustom(v); writeProfileCustom(v); setEditing(false);
    setToast('Profile updated.'); setTimeout(()=>setToast(''), 1600);
  };

  const ALL = allArtifacts();
  const totalArtifacts = ALL.length || 7;
  const activeSafe = (activeId && unlockedIds.has(activeId)) ? getArtifactById(activeId) : null;
  const unlocked = Array.from(unlockedIds).map(getArtifactById);
  const rarest = rarestOf(unlocked);
  const active = activeSafe;
  const collection = [...ALL].sort((a, b) => {
    const ua = unlockedIds.has(a.id) ? 1 : 0;
    const ub = unlockedIds.has(b.id) ? 1 : 0;
    if (ua !== ub) return ub - ua;
    return ua === 1
      ? RARITY_RANK(b.rarity) - RARITY_RANK(a.rarity)
      : RARITY_RANK(a.rarity) - RARITY_RANK(b.rarity);
  });
  const goMomentum = () => onGoTo && onGoTo('momentum');

  const calc = (typeof window !== 'undefined' && window.calculateMomentum) || (() => null);
  const m = store ? calc({
    habits: store.state.habits,
    tasks:  store.state.tasks,
    ideas:  store.state.ideas,
    books:  store.state.books,
    habitCategories: store.state.habitCategories,
  }) : null;
  const totals = (m && m.totals) || {};
  const fullDays = totals.fullHabitDays || 0;
  const wkHabits = totals.habitsCompleted || 0;
  const wkTasks = totals.tasksCompleted || 0;
  const wkIdeas = totals.ideasCaptured || 0;
  const wkReading = totals.readingSessions || 0;
  const wkPages = totals.pagesRead || 0;
  const streakDays = (m && m.streak && (m.streak.current || m.streak.days)) || 0;

  const heroStatusLine = active
    ? `Active Aura: ${active.title}`
    : (custom.building ? custom.building : 'Building the system.');

  return (
    <>
      {/* ─── Hero ─────────────────────────────────────────────── */}
      <div style={{padding:24,borderRadius:18,marginBottom:18,
        border:`1px solid ${C.borderMid}`,
        background:'linear-gradient(160deg, rgba(160,138,86,0.07), rgba(94,117,88,0.04) 60%, rgba(255,255,255,0.01))'}}>
        <div style={{display:'flex',alignItems:'center',gap:18,flexWrap:'wrap'}}>
          {avatar ? (
            <img src={avatar} alt="" style={{width:88,height:88,borderRadius:999,objectFit:'cover',border:`1px solid ${C.sandGlow}`,flexShrink:0}}/>
          ) : (
            <div style={{width:88,height:88,borderRadius:999,background:C.sandFaint,border:`1px solid ${C.sandGlow}`,
              display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0}}>
              <span style={{fontSize:36,fontWeight:800,color:C.sandLight,fontStyle:'italic'}}>{initial}</span>
            </div>
          )}
          <div style={{minWidth:0,flex:1}}>
            <div style={{fontSize:26,fontWeight:900,fontStyle:'italic',color:C.textPrimary,letterSpacing:'-0.02em',textTransform:'uppercase',lineHeight:1.05}}>{name || 'Anonymous'}</div>
            <div style={{fontSize:12,fontWeight:500,color:C.textMuted,marginTop:4,letterSpacing:'0.02em'}}>@{username}</div>
            <div style={{fontSize:13,fontWeight:300,color:C.textSecondary,marginTop:8,fontStyle:'italic',letterSpacing:'0.01em'}}>{heroStatusLine}</div>
            <div style={{display:'flex',gap:8,marginTop:12,flexWrap:'wrap'}}>
              <span style={{fontSize:9,fontWeight:700,letterSpacing:'0.18em',textTransform:'uppercase',
                padding:'3px 8px',borderRadius:999,
                background: publicOn ? 'rgba(156,203,177,0.12)' : 'rgba(255,255,255,0.04)',
                color: publicOn ? '#9CCBB1' : C.textFaint,
                border:`1px solid ${publicOn ? 'rgba(156,203,177,0.4)' : C.border}`}}>
                Public Profile: {publicOn ? 'On' : 'Off'}
              </span>
              <span style={{fontSize:9,fontWeight:700,letterSpacing:'0.18em',textTransform:'uppercase',
                padding:'3px 8px',borderRadius:999,background:'rgba(160,138,86,0.10)',
                color:C.sandLight,border:`1px solid ${C.sandGlow}`}}>
                Private preview
              </span>
            </div>
          </div>
          <div style={{display:'flex',flexDirection:'column',gap:8,flexShrink:0}}>
            {!editing ? (
              <Button variant="ghost" size="sm" icon="edit-3" onClick={startEdit}>Edit Profile</Button>
            ) : null}
            <Button variant="ghost" size="sm" icon="settings" onClick={onOpenSettings}>Settings</Button>
          </div>
        </div>
      </div>

      {/* ─── About Me ─────────────────────────────────────────── */}
      <SectionHeader label="About Me" hint="A short identity card you can edit anytime."/>
      {!editing ? (
        <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fit,minmax(220px,1fr))',gap:10,marginBottom:18}}>
          {[
            { label:'Bio', value: custom.bio, placeholder:'Write a short line about who you are.' },
            { label:"What I'm building", value: custom.building, placeholder:'Describe the system, business, or life you are building.' },
            { label:"The person I'm becoming", value: custom.becoming, placeholder:'Describe the version of yourself you are working toward.' },
          ].map((f) => (
            <div key={f.label} style={{padding:14,borderRadius:12,border:`1px solid ${C.border}`,background:'rgba(255,255,255,0.015)',minHeight:88}}>
              <div style={{fontSize:9,fontWeight:700,letterSpacing:'0.18em',color:C.textFaint,textTransform:'uppercase',marginBottom:6}}>{f.label}</div>
              <div style={{fontSize:12,fontWeight: f.value?500:300,color: f.value?C.textPrimary:C.textFaint,lineHeight:1.55,fontStyle: f.value?'normal':'italic'}}>
                {f.value || f.placeholder}
              </div>
            </div>
          ))}
        </div>
      ) : (
        <div style={{padding:16,borderRadius:12,border:`1px solid ${C.borderMid}`,background:'rgba(255,255,255,0.02)',marginBottom:18}}>
          {[
            { key:'bio', label:'Bio', placeholder:'Write a short line about who you are.' },
            { key:'building', label:"What I'm building", placeholder:'Describe the system, business, or life you are building.' },
            { key:'becoming', label:"The person I'm becoming", placeholder:'Describe the version of yourself you are working toward.' },
          ].map((f) => (
            <div key={f.key} style={{marginBottom:12}}>
              <div style={{fontSize:9,fontWeight:700,letterSpacing:'0.18em',color:C.textFaint,textTransform:'uppercase',marginBottom:6}}>{f.label}</div>
              <textarea value={draft[f.key]||''}
                onChange={e=>setDraft({...draft,[f.key]:e.target.value})}
                placeholder={f.placeholder}
                style={{width:'100%',minHeight:60,padding:'10px 12px',fontSize:13,
                  fontFamily:'Montserrat,sans-serif',resize:'vertical',
                  background:'rgba(250,250,248,0.03)',border:`1px solid ${C.border}`,
                  borderRadius:8,color:C.textPrimary,outline:'none'}}/>
            </div>
          ))}
          <div style={{display:'flex',gap:8,marginTop:6}}>
            <Button size="sm" icon="check" onClick={saveEdit}>Save</Button>
            <Button variant="ghost" size="sm" icon="x" onClick={cancelEdit}>Cancel</Button>
          </div>
        </div>
      )}

      {/* ─── Aura Showcase ────────────────────────────────────── */}
      <SectionHeader label="Aura Showcase" hint="Proof of progress, made visible."/>
      <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fit,minmax(260px,1fr))',gap:12,marginBottom:14}}>
        <ShowcaseCard label="Active Aura" helper="Your current progress signal."
          artifact={active} isActive
          emptyTitle="No aura unlocked yet."
          emptyHint="Build momentum to unlock your first signal."
          onCta={goMomentum} ctaLabel="Open Momentum"/>
        <ShowcaseCard label="Highest Aura" helper="Your rarest unlocked signal."
          artifact={rarest}
          emptyTitle="No highest aura yet."
          emptyHint="Complete stages to unlock your first aura signal."
          onCta={goMomentum} ctaLabel="Open Momentum"/>
      </div>
      <SectionHeader label="Aura Collection" hint="Proof of what you've built."/>
      {collection.length ? (
        <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fit,minmax(200px,1fr))',gap:10,marginBottom:18}}>
          {collection.map(a => (
            <CollectionCard key={a.id} artifact={a}
              unlocked={unlockedIds.has(a.id)}
              isActive={activeId === a.id}
              onSetActive={() => setActiveArtifact(a.id)}/>
          ))}
        </div>
      ) : (
        <div style={{padding:14,border:`1px dashed ${C.border}`,borderRadius:12,fontSize:11,color:C.textFaint,textAlign:'center',marginBottom:18}}>
          No aura defined.
        </div>
      )}

      {/* ─── Public Stats ─────────────────────────────────────── */}
      <SectionHeader label="Public Stats" hint="Stats that can eventually appear on your public profile."/>
      <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fit,minmax(140px,1fr))',gap:10,marginBottom:18}}>
        <StatChip label="Aura unlocked" value={`${unlocked.length}/${totalArtifacts}`}/>
        <StatChip label="Complete days this week" value={fullDays}/>
        <StatChip label="Current rhythm" value={`${streakDays}d`}/>
        <StatChip label="Tasks this week" value={wkTasks}/>
        <StatChip label="Ideas this week" value={wkIdeas}/>
        {wkPages > 0
          ? <StatChip label="Pages read this week" value={wkPages}/>
          : <StatChip label="Reading sessions" value={wkReading}/>}
      </div>

      {/* ─── Recent Signals ───────────────────────────────────── */}
      <SectionHeader label="Recent Signals" hint="Safe progress events from your system."/>
      {activityEvents && activityEvents.length ? (
        <div style={{display:'flex',flexDirection:'column',gap:8,marginBottom:18}}>
          {activityEvents.slice(0, 8).map(ev => {
            const def = (window.SAFE_ACTIVITY_EVENT_TYPES || {})[ev.type] || {};
            return (
              <div key={ev.id} style={{display:'flex',alignItems:'center',gap:12,
                padding:'10px 12px',border:`1px solid ${C.border}`,borderRadius:10,
                background:'rgba(255,255,255,0.015)'}}>
                <div style={{width:28,height:28,borderRadius:8,flexShrink:0,
                  background:C.sandFaint,border:`1px solid ${C.sandGlow}`,
                  display:'flex',alignItems:'center',justifyContent:'center'}}>
                  <Icon name={def.icon || 'sparkles'} size={14} color={C.sandLight}/>
                </div>
                <div style={{minWidth:0,flex:1}}>
                  <div style={{fontSize:12,fontWeight:600,color:C.textPrimary,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{ev.title}</div>
                  {ev.description && <div style={{fontSize:11,fontWeight:300,color:C.textMuted,marginTop:2,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{ev.description}</div>}
                </div>
                <div style={{fontSize:10,fontWeight:500,letterSpacing:'0.08em',color:C.textFaint,flexShrink:0,textTransform:'uppercase'}}>
                  {window.formatActivityTime ? window.formatActivityTime(ev.timestamp) : ''}
                </div>
              </div>
            );
          })}
        </div>
      ) : (
        <div style={{padding:16,border:`1px dashed ${C.border}`,borderRadius:12,textAlign:'center',marginBottom:18}}>
          <div style={{fontSize:12,fontWeight:600,color:C.textSecondary}}>No signals yet.</div>
          <div style={{fontSize:11,fontWeight:300,color:C.textFaint,marginTop:4}}>Complete your system, unlock Aura, or reach a milestone.</div>
        </div>
      )}

      {/* ─── Profile Visibility ───────────────────────────────── */}
      <SectionHeader label="Profile Visibility" hint={publicOn ? 'Public preview is on (local only).' : 'Private by default.'}/>
      <div style={{padding:16,borderRadius:12,border:`1px solid ${C.borderMid}`,background:'rgba(255,255,255,0.015)',marginBottom:18}}>
        <div style={{display:'flex',alignItems:'center',gap:10,marginBottom:10}}>
          <span style={{fontSize:9,fontWeight:700,letterSpacing:'0.18em',textTransform:'uppercase',
            padding:'3px 8px',borderRadius:999,
            background: publicOn ? 'rgba(156,203,177,0.12)' : 'rgba(255,255,255,0.04)',
            color: publicOn ? '#9CCBB1' : C.textFaint,
            border:`1px solid ${publicOn ? 'rgba(156,203,177,0.4)' : C.border}`}}>
            Current state: {publicOn ? 'Preview on' : 'Private'}
          </span>
        </div>
        <div style={{fontSize:11,fontWeight:300,color:C.textMuted,lineHeight:1.55,marginBottom:10}}>
          Your profile is private by default. Future public profiles will share progress signals, not private details.
        </div>
        <ToggleRow label="Public Profile" value={publicOn} onChange={togglePublic}
          desc={publicOn ? 'On — local preview only. Nothing leaves the app.' : 'Off — nothing is shared.'}/>
        <ComingSoonToggle label="Show Aura" desc="Active and Highest Aura on your public profile."/>
        <ComingSoonToggle label="Show Weekly Stats" desc="Counts only — no titles, ideas, or notes."/>
        <ComingSoonToggle label="Show Recent Signals" desc="Safe activity events only."/>
      </div>

      {/* ─── Circle ───────────────────────────────────────────── */}
      <SectionHeader label="Circle" hint="Your private progress circle."/>
      {(() => {
        const sigCount = (window.getCircleFeedEventCount && store)
          ? window.getCircleFeedEventCount(store.state) : 0;
        return (
          <div style={{padding:16,border:`1px solid ${C.borderMid}`,borderRadius:14,marginBottom:18,
            background:'linear-gradient(135deg, rgba(160,138,86,0.05), rgba(94,117,88,0.04))',
            display:'flex',alignItems:'center',gap:14,flexWrap:'wrap'}}>
            <div style={{width:44,height:44,borderRadius:999,flexShrink:0,
              background:C.sandFaint,border:`1px solid ${C.sandGlow}`,
              display:'flex',alignItems:'center',justifyContent:'center'}}>
              <Icon name="users" size={18} color={C.sandLight}/>
            </div>
            <div style={{minWidth:0,flex:1}}>
              <div style={{fontSize:13,fontWeight:700,color:C.textPrimary,letterSpacing:'-0.005em'}}>No one in your Circle yet.</div>
              <div style={{fontSize:11,fontWeight:300,color:C.textMuted,marginTop:3,lineHeight:1.5}}>
                {sigCount > 0
                  ? <>Recent signals: <b style={{color:C.textSecondary,fontWeight:600}}>{sigCount}</b> · Circle feed ready.</>
                  : 'No signals yet. Friends will see safe progress signals like Aura, streaks, and weekly momentum.'}
              </div>
            </div>
            <Button variant="ghost" size="sm" icon="arrow-right" onClick={onOpenCircle} style={{flexShrink:0}}>Open Circle</Button>
          </div>
        );
      })()}

      <div style={{fontSize:10,fontWeight:300,color:C.textFaint,marginTop:8,marginBottom:18,lineHeight:1.5,fontStyle:'italic'}}>
        Habits, tasks, ideas, notes, mood, and reading content are never shown. Only Aura unlocks, counts, and milestones can ever become public — and only when you turn it on.
      </div>

      {toast && (
        <div style={{position:'fixed',left:'50%',bottom:32,transform:'translateX(-50%)',
          padding:'10px 18px',borderRadius:999,background:'rgba(13,12,11,0.95)',
          border:`1px solid ${C.sandGlow}`,color:C.sandLight,
          fontSize:11,fontWeight:600,letterSpacing:'0.14em',textTransform:'uppercase',
          boxShadow:'0 12px 40px rgba(0,0,0,0.5)',zIndex:2000,
          animation:'fadeIn 0.18s ease-out'}}>
          {toast}
        </div>
      )}
    </>
  );
};

// ─── Settings modal (preferences + tools) ───────────────────────
// Settings is for APP preferences. Identity-related surfaces live
// in ProfileModal. Keep this file English-only for Step 1 — no new
// tr() keys for this scaffolding.
const SettingsModal = ({ store, onClose, onSignOut }) => {
  const tr = useT();
  return (
    <ModalShell title={tr('settings.title')} subtitle={tr('settings.subtitle')} onClose={onClose}>
      <SectionHeader label={tr('settings.appearance')}/>
      <AppearanceSection />

      <SectionHeader label={tr('settings.language')}/>
      <LanguageSection />

      <SectionHeader label={tr('settings.socialPrivacy')} hint={tr('settings.socialPrivacyHint')}/>
      <ComingSoonToggle label="Public profile" desc="Master switch. Off keeps everything private."/>
      <ComingSoonToggle label="Show active artifact" desc="Only when public profile is on."/>
      <ComingSoonToggle label="Show rarest artifact" desc="Only when public profile is on."/>
      <ComingSoonToggle label="Allow friend requests" desc="Mutual-consent friend graph."/>
      <ComingSoonToggle label="Share unlocks to friends feed" desc="Push artifact unlocks only — never your content."/>
      <ComingSoonToggle label="Circle sharing" desc="When enabled, approved friends will see safe progress signals only."/>
      <div style={{fontSize:10,fontWeight:300,color:C.textFaint,marginTop:10,lineHeight:1.5}}>
        Habits, tasks, ideas, notes, reading entries, and free-form text are never shared. Only artifact unlocks and streak milestones are eligible for sharing — and only when you turn it on.
      </div>

      {store && <>
        <SectionHeader label={tr('settings.developer')} hint={tr('settings.developerHint')}/>
        <DeveloperTools store={store}/>
      </>}

      <div style={{height:24}}/>
      <Button variant="danger" size="sm" icon="log-out" onClick={onSignOut} style={{width:'100%'}}>{tr('profile.signOut')}</Button>
    </ModalShell>
  );
};

Object.assign(window, { AuthScreen, ProfileModal, ProfilePage, SettingsModal });
