/* ============================================================================
   MATRIA, social: Letters (slow correspondence between kindred readers)
   and Pilgrimage (places tied to archive women, surfaced when you travel).
   v1: read-only. INBOX letters are editorial samples; sending opens later.
   ============================================================================ */

/* Flip to true when moderation, backend, and StoreKit are live. */
window.MATRIA_LETTERS_SEND = false;

function openLetterSend(ctx){
  if(window.MATRIA_LETTERS_SEND) ctx.nav('LetterCompose');
  else ctx.nav('MembershipUnlock');
}

function hoursLabel(h){ return h>=24 ? Math.round(h/24)+'d '+(h%24)+'h' : h+'h'; }

/* envelope glyph */
function Envelope({size=20, sealed}){
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.2" strokeLinejoin="round">
      <rect x="3" y="5.5" width="18" height="13" rx="1.5"/>
      <path d="M3.5 6.5L12 13l8.5-6.5"/>
      {sealed && <circle cx="12" cy="12.6" r="2.5" fill="currentColor" stroke="none" opacity=".85"/>}
    </svg>
  );
}

/* ── LETTERS (tab) ───────────────────────────────────────── */
function Letters({ctx}){
  const D=window.MATRIA; const S=useMStore();
  const sent=S.get().letters;
  const now=Date.now();
  // opening Letters clears the inbox notification badge
  useEffect(()=>{ const u=S.unreadInbox(); if(u.length) S.markInboxRead(u); },[]);
  return (
    <div className="screen dark matria-dark">
      <StatusBar/>
      <div className="s-body" style={{paddingBottom:8}}>
        <div className="pad" style={{paddingTop:8}}>
          <h1 className="title display-title">Letters</h1>
          <p className="lead" style={{marginTop:6}}>Sample correspondence from kindred readers. Read-only in this build; sending opens later.</p>
          <p className="meta letters-readonly-note">Sample letters · editorial · not from other app users yet</p>
        </div>

        {/* your desk, pen name & bio */}
        <div className="pad" style={{marginTop:14}}>
          <div className="card" style={{display:'flex',alignItems:'center',gap:12,padding:'11px 13px',cursor:'pointer'}} onClick={()=>ctx.nav('LetterProfile')}>
            <span style={{width:38,height:38,flex:'none',borderRadius:'50%',border:'1px solid var(--line-gold)',display:'flex',alignItems:'center',justifyContent:'center',color:'var(--gold)',fontFamily:'var(--font-display)',fontSize:16,fontWeight:600}}>{(S.get().profile.penName||'?')[0]}</span>
            <div style={{flex:1}}>
              <div className="meta" style={{color:'var(--ctext)'}}>Writing as {S.get().profile.penName}</div>
              <div className="meta" style={{fontSize:10.5,marginTop:1}}>{S.get().profile.bio? S.get().profile.bio.slice(0,44)+(S.get().profile.bio.length>44?'…':'') : 'Your desk · pen name, bio & privacy'}</div>
            </div>
            <span style={{color:'var(--ctext-soft)'}}><Icon name="chevron" size={15}/></span>
          </div>
        </div>

        {/* compose CTA (gated until sending is live) */}
        <div className="pad" style={{marginTop:14}}>
          <div className="card letters-compose-teaser" style={{padding:'14px 15px',cursor:'pointer',border:'1px solid var(--line-dark)'}} onClick={()=>openLetterSend(ctx)}>
            <div style={{display:'flex',alignItems:'center',gap:12}}>
              <span style={{color:'var(--ctext-soft)'}}><Icon name="pen" size={20}/></span>
              <div style={{flex:1}}>
                <div className="section-title" style={{fontFamily:'var(--font-display)',fontSize:15.5,color:'var(--ctext)',fontWeight:600}}>Write a letter</div>
                <div className="meta" style={{fontSize:11,marginTop:2}}>Set up your desk now. Sending opens when moderation is ready.</div>
              </div>
              <span style={{color:'var(--ctext-faint)'}}><Icon name="chevron" size={15}/></span>
            </div>
          </div>
        </div>

        {/* inbox */}
        <div className="pad" style={{marginTop:18}}>
          <div className="label" style={{marginBottom:10}}>Sample letterbox</div>
          <div style={{display:'flex',flexDirection:'column',gap:10}}>
            {D.INBOX.map(L=>(
              <div key={L.id} className="card" style={{padding:'13px 14px',cursor:L.arrived?'pointer':'default',opacity:L.arrived?1:.85}}
                onClick={()=>L.arrived&&ctx.openLetter(L.id)}>
                <div style={{display:'flex',alignItems:'center',gap:11}}>
                  <span style={{color:L.arrived?'var(--gold)':'var(--ctext-faint)'}}><Envelope size={22} sealed={!L.arrived}/></span>
                  <div style={{flex:1}}>
                    <div style={{display:'flex',alignItems:'baseline',gap:8}}>
                      <span style={{fontFamily:'var(--font-display)',fontSize:15,color:'var(--ctext)',fontWeight:600}}>{L.from}</span>
                      <span style={{fontSize:10.5,color:'var(--ctext-faint)'}}>{L.country||L.city} · {L.km.toLocaleString()} km</span>
                    </div>
                    <div style={{fontSize:11,color:L.arrived?'var(--ctext-soft)':'var(--gold)',marginTop:2,fontStyle:L.arrived?'normal':'italic'}}>
                      {L.arrived? ('Arrived '+L.hoursAgo+'h ago') : ('Still travelling · arrives in '+hoursLabel(L.hoursLeft))}
                    </div>
                  </div>
                  {L.arrived && <span style={{color:'var(--ctext-soft)'}}><Icon name="chevron" size={15}/></span>}
                </div>
                {L.arrived && <p style={{fontSize:12,lineHeight:1.5,color:'var(--ctext-soft)',margin:'10px 0 0',display:'-webkit-box',WebkitLineClamp:2,WebkitBoxOrient:'vertical',overflow:'hidden'}}>{L.text}</p>}
                <div style={{display:'flex',gap:7,marginTop:10}}>
                  {L.themes.map(t=><span key={t} className="tag" style={{height:22,fontSize:10}}>{t}</span>)}
                </div>
              </div>
            ))}
            {window.MATRIA_LETTERS_SEND && sent.map(L=>{
              const left=Math.max(0,Math.ceil((L.arriveAt-now)/3600000));
              return (
                <div key={L.id} className="card" style={{padding:'13px 14px',opacity:.9}}>
                  <div style={{display:'flex',alignItems:'center',gap:11}}>
                    <span style={{color:'var(--ctext-faint)'}}><Icon name="share" size={19}/></span>
                    <div style={{flex:1}}>
                      <div style={{fontFamily:'var(--font-display)',fontSize:15,color:'var(--ctext)',fontWeight:600}}>To {L.to}</div>
                      <div style={{fontSize:11,color:left>0?'var(--gold)':'var(--ctext-soft)',marginTop:2,fontStyle:'italic'}}>
                        {left>0? ('On its way to '+L.toCity+' · arrives in '+hoursLabel(left)) : ('Delivered to '+L.toCity)}
                      </div>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* kindred readers */}
        <div className="pad" style={{marginTop:18}}>
          <div className="label" style={{marginBottom:10}}>Kindred readers</div>
          <p style={{fontSize:11.5,color:'var(--ctext-soft)',margin:'0 0 11px',lineHeight:1.5}}>Fictional pen names for the letters experience. When sending opens, matching will be by what you read and carry, country only, never face or legal name.</p>
          <div style={{display:'flex',flexDirection:'column',gap:9}}>
            {window.MATRIA.KINDRED.map(p=>(
              <div key={p.id} className="lrow" style={{padding:'11px 13px'}} onClick={()=>ctx.openPal(p.id)}>
                <span style={{width:38,height:38,flex:'none',borderRadius:'50%',border:'1px solid var(--line-gold)',display:'flex',alignItems:'center',justifyContent:'center',color:'var(--gold)',fontFamily:'var(--font-display)',fontSize:15,fontWeight:600}}>{p.name[0]}</span>
                <div style={{flex:1}}>
                  <div style={{display:'flex',alignItems:'baseline',gap:8}}>
                    <span style={{fontFamily:'var(--font-display)',fontSize:14.5,color:'var(--ctext)',fontWeight:600}}>{p.name}</span>
                    <span style={{fontSize:10.5,color:'var(--ctext-faint)'}}>{p.country}</span>
                  </div>
                  <div style={{fontSize:10.5,color:'var(--ctext-soft)',marginTop:2}}>Reading {p.reading} · {p.themes.join(' · ')}</div>
                </div>
                <span style={{fontSize:10,color:'var(--ctext-faint)',textAlign:'right',lineHeight:1.3}}>{hoursLabel(Math.max(1,Math.round(p.km/900)))}<br/>away</span>
              </div>
            ))}
          </div>
        </div>
        <div className="scrollfade"/>
      </div>
      <TabBar active="Letters" onNav={ctx.nav}/>
    </div>
  );
}

/* ── read a letter ───────────────────────────────────────── */
function LetterRead({ctx}){
  const D=window.MATRIA; const S=useMStore();
  const L=D.INBOX.find(x=>x.id===ctx.letterId)||D.INBOX[0];
  const [flag,setFlag]=useState('');
  return (
    <div className="screen matria-cream">
      <StatusBar/>
      <TopBar onBack={()=>ctx.back()} title="Sample letter"/>
      <div className="s-body pad" style={{paddingTop:10}}>
        <div className="label letters-readonly-note" style={{marginBottom:12}}>Sample letter · editorial · read-only</div>
        <div style={{display:'flex',alignItems:'center',gap:12}}>
          <span style={{width:44,height:44,flex:'none',borderRadius:'50%',border:'1px solid var(--gold-line)',display:'flex',alignItems:'center',justifyContent:'center',color:'var(--gold-line)',fontFamily:'var(--font-display)',fontSize:18,fontWeight:600}}>{L.from[0]}</span>
          <div>
            <div style={{fontFamily:'var(--font-display)',fontSize:18,color:'var(--ink)',fontWeight:600}}>{L.from}</div>
            <div style={{fontSize:11.5,color:'var(--ink-soft)'}}>{L.country||L.city} · travelled {L.km.toLocaleString()} km</div>
          </div>
        </div>
        <hr className="rule" style={{margin:'16px 0'}}/>
        <p style={{fontFamily:'var(--font-display)',fontSize:15.5,lineHeight:1.7,color:'#3c3730',margin:0}}>{L.text}</p>
        <p style={{fontFamily:'var(--font-display)',fontStyle:'italic',fontSize:14,color:'var(--ink-soft)',margin:'18px 0 0'}}>{L.from}</p>
        <div style={{display:'flex',gap:7,margin:'16px 0 0'}}>
          {L.themes.map(t=><span key={t} className="tag">{t}</span>)}
        </div>
        <button className="btn btn-navy" style={{width:'100%',margin:'22px 0 8px'}} onClick={()=>openLetterSend(ctx)}>Write back</button>
        <p style={{textAlign:'center',fontSize:10.5,color:'var(--ink-faint)',fontStyle:'italic',margin:'4px 0 10px'}}>Sending is not available in this build yet.</p>
        {/* App Store UGC safety: a reader can report a letter or block its sender */}
        {flag ? (
          <p style={{textAlign:'center',fontSize:11.5,color:'var(--ink-soft)',margin:'8px 0 14px'}}>{flag}</p>
        ) : (
          <div style={{display:'flex',justifyContent:'center',gap:20,margin:'8px 0 14px'}}>
            <button onClick={()=>{S.reportLetter(L.id);setFlag('Reported. Thank you, a person will review this letter.');}} style={{background:'none',border:'none',color:'var(--ink-faint)',fontSize:11.5,cursor:'pointer',fontFamily:'var(--font-body)',textDecoration:'underline',padding:0}}>Report this letter</button>
            <button onClick={()=>{S.blockSender(L.from);setFlag('Blocked. You will not receive letters from '+L.from+' again.');}} style={{background:'none',border:'none',color:'var(--ink-faint)',fontSize:11.5,cursor:'pointer',fontFamily:'var(--font-body)',textDecoration:'underline',padding:0}}>Block {L.from}</button>
          </div>
        )}
      </div>
    </div>
  );
}

/* ── compose: share a journal page ───────────────────────── */
/* Membership is kept out of the launch flow until StoreKit is wired. */
/* Future membership pricing. Hidden from the launch flow until StoreKit is wired. */
const MEMBER_TIERS=[
  {key:'free', name:'Reader', price:'Free', sub:'always', highlight:false, cta:null,
   lines:['The whole archive, sourced','Ask any question, see every source','Read the letters that reach you']},
  {key:'member', name:'Member', price:'$72', sub:'a year', highlight:true, cta:'Become a member',
   lines:['Write and reply to letters','Your private constellation, growing','The Reading Room and guided paths','Plan a pilgrimage near you']},
  {key:'patron', name:'Founding Member', price:'$120', sub:'a year', highlight:false, cta:'Become a founding member',
   lines:['Everything in Member','Your name among the archive’s supporters','Early access to new readings','You fund the women’s archive']},
];
function Membership({ctx}){
  const S=useMStore(); const member=S.isMember();
  function choose(tier){ ctx.nav('Legal'); }
  return (
    <div className="screen dark matria-dark">
      <StatusBar/>
      <TopBar onBack={()=>ctx.back()} dark title={member?'Your membership':''}/>
      <div className="s-body pad" style={{paddingTop:4}}>
        <h1 className="title">Support the archive.</h1>
        <p className="bodytext" style={{margin:'10px 0 16px',maxWidth:280,color:'var(--ctext-soft)'}}>Membership is not available in this launch build. Reading Matria stays free while StoreKit support is prepared.</p>
        <div style={{display:'flex',flexDirection:'column',gap:11}}>
          {MEMBER_TIERS.map(t=>(
            <div key={t.key} style={{borderRadius:16,padding:'15px 16px',
              border:'1px solid '+(t.highlight?'var(--gold-line)':'var(--line-dark)'),
              background:t.highlight?'rgba(200,160,100,.07)':'rgba(255,255,255,.03)'}}>
              <div style={{display:'flex',alignItems:'baseline',justifyContent:'space-between'}}>
                <span style={{fontFamily:'var(--font-display)',fontSize:17,color:'var(--ctext)',fontWeight:600}}>{t.name}</span>
                <span><span style={{fontFamily:'var(--font-display)',fontSize:20,color:'var(--gold)',fontWeight:600}}>{t.price}</span><span style={{fontSize:11,color:'var(--ctext-faint)',marginLeft:5}}>{t.sub}</span></span>
              </div>
              <div style={{margin:'11px 0 0',display:'flex',flexDirection:'column',gap:6}}>
                {t.lines.map(l=>(
                  <div key={l} style={{display:'flex',alignItems:'flex-start',gap:9}}>
                    <span style={{color:t.highlight?'var(--gold)':'var(--ctext-soft)',marginTop:1,flex:'none'}}><Icon name="check" size={13} stroke={2}/></span>
                    <span style={{fontSize:12,color:'var(--ctext)',lineHeight:1.4}}>{l}</span>
                  </div>
                ))}
              </div>
              {t.cta && <button className={'btn '+(t.highlight?'btn-tan':'btn-ghost-dark')} style={{width:'100%',marginTop:14,height:46,...(t.highlight?{}:{border:'1px solid var(--line-gold)',color:'var(--gold)'})}} onClick={()=>choose(t.key)} disabled>{t.cta} later</button>}
            </div>
          ))}
        </div>
        {/* Terms and privacy stay accessible even while membership is hidden. */}
        <div style={{display:'flex',justifyContent:'center',gap:20,margin:'16px 0 0'}}>
          {[['Terms',()=>ctx.nav('Legal')],['Privacy',()=>ctx.nav('Legal')]].map(([l,fn])=>(
            <button key={l} onClick={fn} style={{background:'none',border:'none',color:'var(--ctext-soft)',fontSize:11.5,cursor:'pointer',fontFamily:'var(--font-body)',textDecoration:'underline',padding:0}}>{l}</button>
          ))}
        </div>
        <p style={{textAlign:'center',fontSize:10.5,color:'var(--ctext-faint)',fontStyle:'italic',margin:'12px 0 calc(10px + env(safe-area-inset-bottom))',lineHeight:1.6}}>
          No purchase is offered in this build. Reading stays free. You were never the product.</p>
      </div>
    </div>
  );
}

/* Legal: privacy and terms, in-app and offline. The privacy policy URL must also
   be set in App Store Connect; this is the human-readable version. */
function Legal({ctx}){
  const S=({h,body})=>(<><div className="label" style={{margin:'18px 0 7px'}}>{h}</div><p className="bodytext" style={{fontSize:12.5,color:'#46433d'}}>{body}</p></>);
  return (
    <div className="screen matria-cream">
      <StatusBar/>
      <TopBar onBack={()=>ctx.back()} title="Privacy & terms"/>
      <div className="s-body pad" style={{paddingTop:6}}>
        <h1 className="title" style={{color:'var(--ink)'}}>Privacy and terms</h1>
        <S h="What we collect" body="Without an account, your questions, journal, saved answers, and follows stay on this device only. With a paid membership, we store your email, the pen name you choose, and membership status so you can send letters. We do not run advertising or third-party trackers." />
        <S h="What leaves the device" body="Reading the archive and sample letters needs no account. A letter you choose to send carries only the text you wrote and your pen name, never your legal identity unless you add it." />
        <S h="Letters and conduct" body="In this launch build, Letters are read-only. The letters you can read are editorial samples, not mail from other users. Sending opens later with sign-in, moderation, report, and block tools." />
        <S h="Sourced reflection" body="Matria offers sourced reflection drawn only from its archive. It is not medical, psychological, legal, or financial advice, and it does not diagnose or predict. If you are in crisis, please contact local emergency or support services." />
        <S h="Membership" body="Membership is not offered in this launch build. Reading the archive is free, and no purchase is available inside the app yet." />
        <S h="Sources and rights" body="Every answer shows its sources. Matria never invents quotes or figures. Material whose rights are not cleared, or that belongs to living or sacred traditions, is treated with care and shown only where permitted." />
        <p style={{fontSize:11,color:'var(--ink-faint)',margin:'18px 0 calc(14px + env(safe-area-inset-bottom))'}}>Questions: hello@matria.life · Matria · made by luana.systems</p>
      </div>
    </div>
  );
}

function MembershipUnlock({ctx}){
  const S=useMStore();
  return (
    <div className="screen dark matria-dark">
      <StatusBar/>
      <TopBar onBack={()=>ctx.back()} dark/>
      <div className="s-body pad" style={{display:'flex',flexDirection:'column',paddingTop:6}}>
        <span style={{color:'var(--gold)'}}><Envelope size={48} sealed/></span>
        <h1 className="title" style={{margin:'16px 0 0'}}>Sending opens<br/>later.</h1>
        <p className="bodytext" style={{margin:'16px 0 0',maxWidth:270}}>Letters are read-only in this launch build. Read the sample letters, set up your pen name, and return when moderation and membership are ready.</p>
        <p className="bodytext" style={{margin:'12px 0 0',maxWidth:270,color:'var(--ctext-soft)'}}>Nothing you write here is sent to another person yet. Reading stays free.</p>
        <div style={{margin:'20px 0 0',display:'flex',flexDirection:'column',gap:9}}>
          {['Read sample letters now','Prepare your desk and pen name','Write and reply when sending opens'].map(b=>(
            <div key={b} style={{display:'flex',alignItems:'flex-start',gap:10}}>
              <span style={{color:'var(--gold)',marginTop:1,flex:'none'}}><Icon name="check" size={15} stroke={2}/></span>
              <span style={{fontSize:12.5,color:'var(--ctext)',lineHeight:1.45}}>{b}</span>
            </div>
          ))}
        </div>
        <div style={{flex:1,minHeight:18}}/>
        <button className="btn btn-tan" style={{width:'100%',flex:'none'}} onClick={()=>ctx.nav('Letters')}>Back to Letters</button>
        <button className="btn btn-ghost-dark" style={{width:'100%',margin:'10px 0 0',border:'1px solid var(--line-gold)',color:'var(--gold)'}} onClick={()=>ctx.back()}>Maybe later</button>
        <p style={{textAlign:'center',fontSize:11,color:'var(--ctext-faint)',fontStyle:'italic',margin:'14px 0 calc(6px + env(safe-area-inset-bottom))'}}>Reading stays free. No purchase is available in this build.</p>
      </div>
    </div>
  );
}

function LetterCompose({ctx}){
  useEffect(()=>{
    if(!window.MATRIA_LETTERS_SEND) ctx.nav('MembershipUnlock');
  },[]);
  if(!window.MATRIA_LETTERS_SEND) return null;

  const D=window.MATRIA; const S=useMStore();
  const journal=S.get().journal;
  const [mode,setMode]=useState(journal.length? 'journal':'fresh');
  const [entryId,setEntryId]=useState(journal[0]?.id);
  const [text,setText]=useState('');
  const [palId,setPalId]=useState(D.KINDRED[0].id);
  const [sentHours,setSentHours]=useState(null);
  const pal=D.KINDRED.find(p=>p.id===palId);
  const body = mode==='journal' ? (journal.find(j=>j.id===entryId)?.text||'') : text;

  function send(){
    if(!body.trim()) return;
    const h=S.sendLetter(pal, body.trim(), mode==='journal');
    setSentHours(h);
  }

  if(sentHours!==null) return (
    <div className="screen dark matria-dark">
      <StatusBar/>
      <div className="s-body pad" style={{display:'flex',flexDirection:'column',alignItems:'center',textAlign:'center',paddingTop:60}}>
        <span style={{color:'var(--gold)'}}><Envelope size={56} sealed/></span>
        <h2 className="title" style={{marginTop:18}}>Sealed and sent</h2>
        <p className="lead" style={{marginTop:10,maxWidth:220}}>Your letter is travelling to {pal.city}. It will arrive in about {hoursLabel(sentHours)}.</p>
        <p style={{fontSize:11.5,color:'var(--ctext-faint)',fontStyle:'italic',marginTop:14,maxWidth:230,lineHeight:1.5}}>Nothing to refresh. Nothing to check. It is on its way, like a thought given time.</p>
        <button className="btn btn-tan" style={{width:200,marginTop:28}} onClick={()=>ctx.nav('Letters')}>Back to Letters</button>
      </div>
    </div>
  );

  return (
    <div className="screen matria-cream">
      <StatusBar/>
      <TopBar onBack={()=>ctx.back()} title="Send a letter"/>
      <div className="s-body pad" style={{paddingTop:8}}>
        <h1 className="title" style={{color:'var(--ink)'}}>Share a page</h1>
        <p className="lead" style={{margin:'8px 0 14px',color:'#5a5246'}}>One reader. One letter. No likes, no feed, just an answer, eventually.</p>

        <div className="label" style={{marginBottom:8}}>What to send</div>
        <div style={{display:'flex',gap:8,marginBottom:11}}>
          <button className={'chip'+(mode==='journal'?' on':'')} onClick={()=>setMode('journal')} disabled={!journal.length}>From my journal</button>
          <button className={'chip'+(mode==='fresh'?' on':'')} onClick={()=>setMode('fresh')}>Write fresh</button>
        </div>
        {mode==='journal' ? (
          journal.length ? (
            <div style={{display:'flex',flexDirection:'column',gap:8}}>
              {journal.slice(0,3).map(j=>(
                <div key={j.id} onClick={()=>setEntryId(j.id)} style={{border:'1px solid '+(j.id===entryId?'var(--gold-line)':'var(--line-cream)'),
                  background:j.id===entryId?'#f6edda':'var(--cream-card)',borderRadius:12,padding:'11px 13px',cursor:'pointer'}}>
                  <div style={{fontSize:10.5,color:'var(--ink-faint)',marginBottom:4}}>{j.qtext}</div>
                  <div style={{fontSize:12.5,color:'#3c3730',lineHeight:1.45,display:'-webkit-box',WebkitLineClamp:2,WebkitBoxOrient:'vertical',overflow:'hidden'}}>{j.text}</div>
                </div>
              ))}
            </div>
          ) : <p style={{fontSize:12,color:'var(--ink-faint)'}}>No journal entries yet, write fresh instead.</p>
        ) : (
          <textarea value={text} onChange={e=>setText(e.target.value)} name="fresh-letter" aria-label="Letter text" autoComplete="off" placeholder="Dear reader…"
            style={{width:'100%',border:'1px solid var(--line-cream)',borderRadius:12,background:'var(--cream-card-2)',height:110,padding:'12px 14px',fontSize:13,color:'var(--ink)',fontFamily:'var(--font-body)',resize:'none'}}/>
        )}

        <div className="label" style={{margin:'16px 0 8px'}}>To</div>
        <div style={{display:'flex',flexDirection:'column',gap:8}}>
          {D.KINDRED.slice(0,3).map(p=>(
            <div key={p.id} onClick={()=>setPalId(p.id)} className="lrow" style={{padding:'10px 12px',borderColor:p.id===palId?'var(--gold-line)':undefined,background:p.id===palId?'#f6edda':undefined}}>
              <span style={{width:32,height:32,flex:'none',borderRadius:'50%',border:'1px solid var(--gold-line)',display:'flex',alignItems:'center',justifyContent:'center',color:'var(--gold-line)',fontFamily:'var(--font-display)',fontSize:13,fontWeight:600}}>{p.name[0]}</span>
              <div style={{flex:1}}>
                <span style={{fontSize:13,color:'var(--ink)',fontWeight:700}}>{p.name}</span>
                <span style={{fontSize:10.5,color:'var(--ink-faint)',marginLeft:7}}>{p.country} · reads {p.reading}</span>
              </div>
              <span style={{fontSize:10,color:'var(--ink-faint)'}}>{hoursLabel(Math.max(1,Math.round(p.km/900)))}</span>
            </div>
          ))}
        </div>
        <button className="btn btn-navy" style={{width:'100%',margin:'18px 0 8px'}} onClick={send}>Seal &amp; send to {pal.name}</button>
        <p style={{textAlign:'center',fontSize:10.5,color:'var(--ink-faint)',fontStyle:'italic',margin:'0 0 10px'}}>Letters are private, between the two of you. You can unsend until it arrives.</p>
      </div>
    </div>
  );
}

/* ── kindred reader profile (minimal, reading-first) ─────── */
function PalDetail({ctx}){
  const D=window.MATRIA;
  const p=D.KINDRED.find(x=>x.id===ctx.palId)||D.KINDRED[0];
  return (
    <div className="screen matria-cream">
      <StatusBar/>
      <TopBar onBack={()=>ctx.back()} title="Kindred reader"/>
      <div className="s-body pad" style={{paddingTop:12}}>
        <div style={{display:'flex',alignItems:'center',gap:14}}>
          <span style={{width:58,height:58,flex:'none',borderRadius:'50%',border:'1.4px solid var(--gold-line)',display:'flex',alignItems:'center',justifyContent:'center',color:'var(--gold-line)',fontFamily:'var(--font-display)',fontSize:24,fontWeight:600}}>{p.name[0]}</span>
          <div>
            <div style={{fontFamily:'var(--font-display)',fontSize:21,color:'var(--ink)',fontWeight:600}}>{p.name}</div>
            <div style={{fontSize:12,color:'var(--ink-soft)'}}>{p.country} · {p.km.toLocaleString()} km · letters take {hoursLabel(Math.max(1,Math.round(p.km/900)))}</div>
          </div>
        </div>
        <p style={{fontFamily:'var(--font-display)',fontStyle:'italic',fontSize:14.5,color:'#4a443c',margin:'16px 0 0',lineHeight:1.5}}>“{p.note}”</p>
        <hr className="rule" style={{margin:'16px 0'}}/>
        <div className="label" style={{marginBottom:8}}>Currently reading</div>
        <p style={{fontSize:13.5,color:'var(--ink)',margin:0,fontWeight:700}}>{p.reading}</p>
        <div className="label" style={{margin:'14px 0 8px'}}>Carries questions about</div>
        <div style={{display:'flex',flexWrap:'wrap',gap:8}}>{p.themes.map(t=><span key={t} className="tag">{t}</span>)}</div>
        <button className="btn btn-navy" style={{width:'100%',margin:'22px 0 8px'}} onClick={()=>openLetterSend(ctx)}>Write to {p.name}</button>
        <p style={{textAlign:'center',fontSize:10.5,color:'var(--ink-faint)',fontStyle:'italic'}}>Sample reader · sending not available in this build</p>
      </div>
    </div>
  );
}

/* ── PILGRIMAGE, places tied to archive women ───────────── */
function Pilgrimage({ctx}){
  const D=window.MATRIA; const S=useMStore();
  const P=D.PLACES;
  const cur = (S.get().city && P.cities[S.get().city]) ? S.get().city : P.current;
  const here=P.cities[cur];
  const elsewhere=Object.entries(P.cities).filter(([k])=>k!==cur);
  return (
    <div className="screen matria-cream">
      <StatusBar/>
      <TopBar onBack={()=>ctx.back()} title="Pilgrimage"/>
      <div className="s-body pad" style={{paddingTop:8}}>
        <h1 className="title" style={{color:'var(--ink)'}}>Near you</h1>
        <p className="lead" style={{margin:'8px 0 4px',color:'#5a5246'}}>You are in <b>{here.city}</b>. Women of the archive lived, worked and are remembered here.</p>
        <div style={{display:'flex',flexDirection:'column',gap:10,marginTop:14}}>
          {here.sites.map(s=>(
            <div key={s.name} className="lrow" style={{padding:'12px 13px',alignItems:'flex-start'}} onClick={()=>s.node&&ctx.openSource(s.node)}>
              <span style={{width:38,height:38,flex:'none',borderRadius:9,background:'rgba(184,142,76,.12)',display:'flex',alignItems:'center',justifyContent:'center',color:'var(--gold-line)',marginTop:2}}><Icon name="map" size={19}/></span>
              <div style={{flex:1}}>
                <div style={{fontFamily:'var(--font-display)',fontSize:14.5,color:'var(--ink)',fontWeight:600,lineHeight:1.2}}>{s.name}</div>
                <div style={{fontSize:11,color:'var(--gold-line)',marginTop:3,fontWeight:700}}>{s.who}</div>
                <div style={{fontSize:11,color:'var(--ink-soft)',marginTop:2,lineHeight:1.4}}>{s.note}</div>
                <div style={{fontSize:10,color:'var(--ink-faint)',marginTop:4}}>{s.kind} · {s.area}</div>
              </div>
              {s.node && <span style={{color:'var(--ink-faint)',marginTop:4}}><Icon name="chevron" size={15}/></span>}
            </div>
          ))}
        </div>
        <div className="label" style={{margin:'18px 0 9px'}}>Other journeys</div>
        <div style={{display:'flex',flexWrap:'wrap',gap:8,paddingBottom:14}}>
          {elsewhere.map(([k,c])=><span key={k} className="chip">{c.city} · {c.sites.length}</span>)}
        </div>
        <p style={{fontSize:10.5,color:'var(--ink-faint)',fontStyle:'italic',lineHeight:1.5,margin:'0 0 12px'}}>Location is only ever used on this device, only when you ask. The archive never follows you; you visit it.</p>
      </div>
    </div>
  );
}

/* ── Your Desk, pen name, bio, privacy (GDPR-grade controls) ─ */
function LetterProfile({ctx}){
  const S=useMStore();
  const prof=S.get().profile;
  const [pen,setPen]=useState(prof.penName);
  const [bio,setBio]=useState(prof.bio);
  const [reading,setReading]=useState(prof.reading);
  const [country,setCountry]=useState(prof.shareCountry);
  const [confirmWipe,setConfirmWipe]=useState(false);
  const [flash,setFlash]=useState(false);
  function saveProfile(){
    S.setProfile({penName:pen.trim()||'Quiet Comet', bio:bio.trim(), reading:reading.trim(), shareCountry:country});
    setFlash(true); setTimeout(()=>setFlash(false),1500);
  }
  const inputStyle={width:'100%',border:'1px solid var(--line-cream)',borderRadius:12,background:'var(--cream-card-2)',height:44,padding:'0 14px',fontSize:13.5,color:'var(--ink)',fontFamily:'var(--font-body)',boxSizing:'border-box'};
  return (
    <div className="screen matria-cream">
      <StatusBar/>
      <TopBar onBack={()=>ctx.back()} title="Your desk"/>
      <div className="s-body pad" style={{paddingTop:8}}>
        <div style={{display:'flex',alignItems:'center',gap:14,marginBottom:4}}>
          <span style={{width:54,height:54,flex:'none',borderRadius:'50%',border:'1.4px solid var(--gold-line)',display:'flex',alignItems:'center',justifyContent:'center',color:'var(--gold-line)',fontFamily:'var(--font-display)',fontSize:22,fontWeight:600}}>{(pen||'?')[0]}</span>
          <div>
            <h1 className="title" style={{color:'var(--ink)'}}>Your desk</h1>
            <p style={{fontSize:11.5,color:'var(--ink-soft)',margin:'4px 0 0'}}>Who kindred readers meet. Never your legal name.</p>
          </div>
        </div>
        <div className="label" style={{margin:'16px 0 6px'}}>Pen name</div>
        <input value={pen} onChange={e=>setPen(e.target.value)} name="pen-name" aria-label="Pen name" autoComplete="off" style={inputStyle} maxLength={24}/>
        <div className="label" style={{margin:'13px 0 6px'}}>Bio <span style={{fontWeight:400,textTransform:'none',letterSpacing:0,color:'var(--ink-faint)'}}>what you read, carry, wonder</span></div>
        <textarea value={bio} onChange={e=>setBio(e.target.value)} name="reader-bio" aria-label="Reader bio" autoComplete="off" placeholder="Reader of slow books. Mother of two questions. Learning to rest."
          style={{...inputStyle,height:84,padding:'11px 14px',resize:'none',lineHeight:1.5}}/>
        <div className="label" style={{margin:'13px 0 6px'}}>Currently reading</div>
        <input value={reading} onChange={e=>setReading(e.target.value)} name="currently-reading" aria-label="Currently reading" autoComplete="off" placeholder="Sister Outsider" style={inputStyle}/>
        {/* disclosure */}
        <div style={{display:'flex',alignItems:'center',gap:12,background:'var(--cream-card)',border:'1px solid var(--line-cream)',borderRadius:13,padding:'12px 14px',marginTop:14,cursor:'pointer'}} onClick={()=>setCountry(c=>!c)}>
          <div style={{flex:1}}>
            <div style={{fontSize:12.5,color:'var(--ink)',fontWeight:700}}>Show my country</div>
            <div style={{fontSize:10.5,color:'var(--ink-soft)',marginTop:2}}>Never your city. Distance still works either way.</div>
          </div>
          <span style={{width:40,height:24,flex:'none',borderRadius:13,background:country?'var(--gold-line)':'#cfc6b6',position:'relative',transition:'background .2s'}}>
            <span style={{position:'absolute',top:2,left:country?18:2,width:20,height:20,borderRadius:'50%',background:'#fff',boxShadow:'0 1px 3px rgba(0,0,0,.25)',transition:'left .2s'}}/>
          </span>
        </div>
        <button className="btn btn-navy" style={{marginTop:14}} onClick={saveProfile}>{flash?'Saved ✓':'Save'}</button>
        {/* privacy card */}
        <div style={{background:'var(--cream-card-2)',border:'1px solid var(--line-cream)',borderRadius:13,padding:'13px 15px',marginTop:16}}>
          <div className="label" style={{fontSize:9,marginBottom:8}}>How Matria protects you</div>
          {['Pen names only, your identity is never required.','You decide what to disclose, and can change it anytime.','Location is country-level at most, and optional.','Letters are read-only in this build; sending opens later.','Export or erase everything, anytime. Erasure is immediate.'].map(t=>(
            <div key={t} style={{display:'flex',gap:9,alignItems:'flex-start',marginBottom:6}}>
              <span style={{color:'var(--gold-line)',marginTop:2,flex:'none'}}><Icon name="check" size={11} stroke={2.2}/></span>
              <span style={{fontSize:11.5,color:'#46433d',lineHeight:1.45}}>{t}</span>
            </div>
          ))}
        </div>
        {!confirmWipe
          ? <button className="btn" style={{background:'transparent',border:'1px solid rgba(179,91,72,.45)',color:'#a8503c',height:46,fontSize:13,margin:'12px 0 14px'}} onClick={()=>setConfirmWipe(true)}>Delete all my data</button>
          : <div style={{border:'1px solid rgba(179,91,72,.45)',borderRadius:14,padding:'13px 14px',margin:'12px 0 14px'}}>
              <p style={{fontSize:12,color:'#7a3b2c',margin:'0 0 10px',lineHeight:1.5}}>This erases your journal, letters, saves and profile from this device. There is no undo.</p>
              <div style={{display:'flex',gap:9}}>
                <button className="btn" style={{background:'#a8503c',color:'#fff',height:42,fontSize:13}} onClick={()=>{S.wipeAll();setConfirmWipe(false);}}>Erase everything</button>
                <button className="btn" style={{background:'transparent',border:'1px solid var(--line-cream)',color:'var(--ink)',height:42,fontSize:13}} onClick={()=>setConfirmWipe(false)}>Keep</button>
              </div>
            </div>}
      </div>
    </div>
  );
}

Object.assign(window,{Letters,LetterRead,LetterCompose,Membership,MembershipUnlock,Legal,PalDetail,Pilgrimage,Envelope,LetterProfile,openLetterSend});
