/* ============================================================================
   MATRIA, screens, part 1: Splash, Onboarding ×5, Today, Ask, Searching.
   Each screen: ({ctx}) where ctx = {nav, openNode, openSource, ask, question, tweaks}
   ============================================================================ */

/* ── splash: sanctuary archive, book emblem over a quiet portrait field ── */
function SplashReferenceGlyph({kind}){
  const g={
    crystal:<><path d="M8 3.5l7.5 3.2 2.3 8.9-5.8 4.9-7.5-3.2-2.3-8.9z"/><path d="M8 3.5l-3.5 13.8M15.5 6.7L12 20.5M2.2 8.4l9.8 12.1M17.8 15.6L8 3.5M4.5 17.3l13.3-1.7"/></>,
    flower:<><path d="M12 20V9.8"/><path d="M12 9.8c-3.8-4-7.3-3.2-7.3-.3 0 2.5 2.8 4.2 7.3.3z"/><path d="M12 9.8c3.8-4 7.3-3.2 7.3-.3 0 2.5-2.8 4.2-7.3.3z"/><path d="M12 10.5c-2.2 1.7-3.1 3.9-2.3 6.7"/><path d="M12 10.5c2.2 1.7 3.1 3.9 2.3 6.7"/><circle cx="12" cy="9.8" r="1.1"/></>,
    stars:<><circle cx="12" cy="12" r="7.2"/><circle cx="12" cy="12" r="2.2"/><path d="M12 4.8v2.1M12 17.1v2.1M4.8 12h2.1M17.1 12h2.1"/><path d="M16.4 7.6l-1.5 1.5M9.1 14.9l-1.5 1.5M7.6 7.6l1.5 1.5M14.9 14.9l1.5 1.5"/><circle cx="16.6" cy="12" r=".7"/><circle cx="12" cy="7.4" r=".7"/></>,
    shell:<><path d="M3.5 18.5c2.2-8.5 5.1-13 8.5-13s6.3 4.5 8.5 13z"/><path d="M12 5.5v13M7.8 18.5c.5-6 1.9-10.3 4.2-13M16.2 18.5c-.5-6-1.9-10.3-4.2-13"/><path d="M5.6 18.5c2.4-2.3 10.4-2.3 12.8 0"/><path d="M4.7 15.5c3.8-2.8 10.8-2.8 14.6 0"/></>,
  };
  return <svg width="27" height="27" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth=".85" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">{g[kind]}</svg>;
}

function Splash({ctx}){
  const pillars=[
    {key:'crystal', label:'Ancient stories'},
    {key:'flower', label:'Radical women'},
    {key:'stars', label:'Embodied knowledge'},
    {key:'shell', label:'Real sources'},
  ];
  return (
    <div className="screen dark splash-v2">
      <img className="splash-v2__bg" src="uploads/matria-splash-bg.png" alt="" aria-hidden="true"/>
      <span className="splash-v2__veil" aria-hidden="true"/>
      <StatusBar/>
      <div className="s-body splash-v2__scroll">
        <div className="splash-v2__center">
          <div className="splash-v2__emblem-wrap" aria-hidden="true">
            <img className="splash-v2__emblem" src="uploads/matria-splash-emblem-blend.png" alt=""/>
          </div>
          <h1 className="splash-v2__wordmark" aria-label="Matria">MaTRI<span className="splash-v2__wordmark-a">a</span></h1>
          <div className="splash-v2__divider" aria-hidden="true"><span/><Icon name="explore" size={10}/><span/></div>
          <p className="splash-v2__claim">A sourced archive<br/>for questions<br/>women carry.</p>
          <div className="splash-v2__pillars">
            {pillars.map(p=>(
              <div key={p.key} className="splash-v2__pillar">
                <span className="splash-v2__pillar-icon"><SplashReferenceGlyph kind={p.key}/></span>
                <span className="splash-v2__pillar-label">{p.label}</span>
              </div>
            ))}
          </div>
          <p className="splash-v2__privacy">Real sources · Private on your phone</p>
        </div>
      </div>
      <div className="matria-dock-foot splash-v2__foot">
          <button type="button" className="btn btn-tan splash-v2__begin" onClick={()=>ctx.nav('Onboarding1')}>Begin</button>
          <p className="splash-v2__sanctuary">Your sanctuary. Your archive.</p>
          <span className="splash-v2__moon" aria-hidden="true">
            <svg width="18" height="10" viewBox="0 0 18 10" fill="none"><path d="M11 2.2a4.2 4.2 0 1 0 0 5.6A5.2 5.2 0 1 1 11 2.2z" stroke="currentColor" strokeWidth="1"/><path d="M3 8.5h12" stroke="currentColor" strokeWidth=".8" opacity=".45"/></svg>
          </span>
      </div>
    </div>
  );
}

const ONBOARD_BEAT2_PILLARS=[
  {key:'sources', label:'Real sources', subtitle:'Every answer names the archive entries behind it.'},
  {key:'knowledge', label:'Lineage map', subtitle:'See how women connect across time.'},
  {key:'women', label:'Radical women', subtitle:'Poets, scientists, organisers, philosophers.'},
];
const ONBOARD_BEAT3_PILLARS=[
  {key:'sources', label:'On your phone', subtitle:'Questions, journal and saves stay here.'},
  {key:'stories', label:'Reading free', subtitle:'Archive and sample letters. No account.'},
  {key:'women', label:'Paid to send', subtitle:'Sign-in, pen name, and membership.'},
];

function OnboardPanelGlyph({kind}){
  const map={stories:'crystal', women:'flower', knowledge:'stars', sources:'crystal'};
  if(kind==='map') return <Icon name="explore" size={22}/>;
  if(kind==='phone') return <Icon name="lock" size={21}/>;
  if(kind==='letters') return <Envelope size={21} sealed/>;
  return <SplashReferenceGlyph kind={map[kind]||'crystal'}/>;
}

function OnboardPillarPanel({items}){
  return (
    <div className="onboard-v2__pillars">
      {items.map((p,i)=>(
        <div key={p.key} className={'onboard-v2__pillar'+(i===items.length-1?' onboard-v2__pillar--last':'')}>
          <span className="onboard-v2__pillar-icon"><OnboardPanelGlyph kind={p.key}/></span>
          <div className="onboard-v2__pillar-copy">
            <span className="onboard-v2__pillar-title">{p.label}</span>
            <span className="onboard-v2__pillar-sub">{p.subtitle}</span>
          </div>
        </div>
      ))}
    </div>
  );
}

function OnboardPrivacyNote(){
  return (
    <p className="onboard-v2__privacy">
      <span className="onboard-v2__privacy-line"/>
      <Icon name="lock" size={11}/>
      <span>Private on your phone</span>
      <span className="onboard-v2__privacy-line"/>
    </p>
  );
}

function OnboardBeat({title, artSrc, body, highlight, pillars, cta, onNext, dotIndex}){
  return (
    <div className="screen dark onboard-v2">
      <StatusBar/>
      <div className="s-body onboard-v2__scroll">
        <div className="onboard-v2__hero">
          <div className="onboard-v2__rail" aria-hidden="true">
            <Icon name="explore" size={16}/>
            <span/>
          </div>
          <div className="onboard-v2__title-wrap">
            <h1 className="onboard-v2__title">{title}</h1>
          </div>
          <div className="onboard-v2__art" aria-hidden="true">
            <img src={artSrc} alt=""/>
          </div>
        </div>
        <div className="onboard-v2__rule" aria-hidden="true"><Icon name="explore" size={9}/></div>
        <div className="onboard-v2__copy">
          <p className="onboard-v2__prose">{body}</p>
          {highlight && <p className="onboard-v2__highlight">{highlight}</p>}
        </div>
        {pillars && <OnboardPillarPanel items={pillars}/>}
      </div>
      <div className="matria-dock-foot onboard-v2__foot">
        <button type="button" className="btn btn-tan onboard-v2__cta" onClick={onNext}>{cta}</button>
        <OnboardPrivacyNote/>
        <OnbDots i={dotIndex} n={5} dark/>
      </div>
    </div>
  );
}

/* shared onboarding footer: button + N dots */
function OnbDots({i, n=4, dark}){
  return (
    <div className="dots" style={{color:dark?'var(--ctext)':'var(--ink)'}}>
      {Array.from({length:n}).map((_,k)=><i key={k} className={k===i?'on':''}/>)}
    </div>
  );
}

function Onboarding1({ctx}){
  return (
    <OnboardBeat
      title={<>Your questions<br/>have ancestors.</>}
      artSrc="uploads/matria-onboarding-lineage.png"
      body="Whatever you are carrying, women have sat with it before you. Matria is a sourced archive: hymns, myths, and traditions beside poets, scientists, and organisers. Too many of their names were never kept."
      highlight="Matria draws their voices into conversation with your question, and shows you every source."
      pillars={MATRIA_PILLARS}
      cta="Begin"
      onNext={()=>ctx.nav('Onboarding2')}
      dotIndex={0}
    />
  );
}

function Onboarding2({ctx}){
  return (
    <OnboardBeat
      title={<>Follow the<br/>lineage.</>}
      artSrc="uploads/matria-onboarding-archive.png"
      body="Ask Matria anything you are sitting with. It answers only from a sourced archive of women, poets, scientists, organisers, philosophers, myths, and traditions,"
      highlight="and it shows you every source."
      pillars={ONBOARD_BEAT2_PILLARS}
      cta="Begin"
      onNext={()=>ctx.nav('Onboarding3')}
      dotIndex={1}
    />
  );
}

function Onboarding3({ctx}){
  return (
    <OnboardBeat
      title={<>What you carry<br/>stays yours.</>}
      artSrc="uploads/matria-onboarding-sanctuary.png"
      body="Your questions, journal, and saved answers stay on this phone. Reading the archive and sample letters needs no account. No tracking. No audience."
      highlight="Sending letters uses a paid membership with sign-in: your email and a pen name you choose. Sample letters in this build are read-only."
      pillars={ONBOARD_BEAT3_PILLARS}
      cta="Begin"
      onNext={()=>ctx.nav('OnboardingPreview')}
      dotIndex={2}
    />
  );
}

/* Beat 4, read-only sample answer (nothing saved to Sanctuary) */
function OnboardingPreview({ctx}){
  const D=window.MATRIA;
  const q=D.QUESTIONS.care_02;
  const Card=window.AnswerEditorialCard;
  return (
    <div className="screen dark onboard-v2 onboard-preview">
      <StatusBar/>
      <div className="s-body onboard-v2__scroll onboard-preview__scroll">
        <div className="onboard-preview__head">
          <div className="onboard-v2__rail" aria-hidden="true">
            <Icon name="explore" size={16}/>
            <span/>
          </div>
          <div className="onboard-v2__title-wrap onboard-preview__title-wrap">
            <h1 className="onboard-v2__title">This is what<br/>an answer<br/>looks like.</h1>
          </div>
        </div>
        <div className="onboard-v2__rule" aria-hidden="true"><Icon name="explore" size={9}/></div>
        <p className="onboard-v2__prose onboard-preview__intro">Matria matches your question to sourced archive entries and names every source. When you ask for real, your Sanctuary starts empty.</p>
        <div className="onboard-preview__answer">
          <div className="label answer-screen__eyebrow">Your question</div>
          <p className="answer-question onboard-preview__question">{q.text}</p>
          <div className="label answer-screen__eyebrow" style={{marginTop:14}}>From Matria</div>
          <p className="answer-screen__editorial-note">Editorial reading of the archive. Open any woman below for sources.</p>
          {Card ? <Card q={q} readOnly compact/> : <p className="bodytext">{q.reflection}</p>}
        </div>
      </div>
      <div className="matria-dock-foot onboard-v2__foot">
        <button type="button" className="btn btn-tan onboard-v2__cta" onClick={()=>ctx.nav('Onboarding4')}>Continue</button>
        <OnboardPrivacyNote/>
        <OnbDots i={3} n={5} dark/>
      </div>
    </div>
  );
}

/* Beat 5, attune (seeds personalization) */
function CarryingList({carrying, onSelect}){
  const D=window.MATRIA;
  const items=D.CARRY_META||D.CARRY.map((label,i)=>({label,glyph:['idea','person','science','history','idea','political','myth','power','person','history'][i]}));
  const skipOn=!carrying;
  return (
    <div className="carrying-list">
      {items.map(({label,glyph})=>{
        const on=carrying===label;
        return (
          <button key={label} type="button" className={'lrow carrying-row'+(on?' carrying-row--on':'')} onClick={()=>onSelect(on?null:label)}>
            <span className="lrow__slot"><TypeGlyph type={glyph} size={18}/></span>
            <span className="carrying-row__label">{label}</span>
            {on && <span className="carrying-row__check" aria-hidden="true"><Icon name="check" size={15} stroke={2}/></span>}
          </button>
        );
      })}
      <button type="button" className={'lrow carrying-row carrying-row--skip'+(skipOn?' carrying-row--on':'')} onClick={()=>onSelect(null)}>
        <span className="lrow__slot carrying-row__slot--skip" aria-hidden="true">—</span>
        <span className="carrying-row__label">None of these right now</span>
        {skipOn && <span className="carrying-row__check" aria-hidden="true"><Icon name="check" size={15} stroke={2}/></span>}
      </button>
    </div>
  );
}

function ChangeCarrying({ctx}){
  const S=useMStore();
  const carrying=S.get().carrying;
  return (
    <div className="screen matria-cream">
      <StatusBar/>
      <div className="carrying-toolbar pad">
        <button type="button" className="carrying-toolbar__back" onClick={()=>ctx.back()} aria-label="Back">
          <Icon name="back" size={22}/>
        </button>
        <span className="label carrying-toolbar__title">What you carry</span>
        <span className="carrying-toolbar__spacer" aria-hidden="true"/>
      </div>
      <div className="s-body pad onboard-screen__scroll carrying-screen">
        <p className="lead" style={{margin:'4px 0 14px'}}>Optional. Choose what is closest, or skip for now.</p>
        <CarryingList carrying={carrying} onSelect={c=>S.setCarrying(c)}/>
      </div>
      <div className="matria-dock-foot onboard-screen__foot">
        <button type="button" className="btn btn-navy cream-editorial-cta" onClick={()=>ctx.back()}>Done</button>
      </div>
    </div>
  );
}

function Onboarding4({ctx}){
  const S=useMStore();
  const carrying=S.get().carrying;
  return (
    <div className="screen matria-cream">
      <StatusBar/>
      <div className="s-body pad onboard-screen onboard-screen__scroll carrying-screen">
        <div className="matria-head matria-head--rail">
          <h1 className="title display-title" style={{color:'var(--ink)',marginTop:8}}>What are you<br/>carrying lately?</h1>
        </div>
        <p className="lead" style={{margin:'9px 0 14px'}}>Optional. Choose what is closest, or skip for now. You can change this anytime.</p>
        <CarryingList carrying={carrying} onSelect={c=>S.setCarrying(c)}/>
      </div>
      <div className="matria-dock-foot onboard-screen__foot">
        <button className="btn btn-navy cream-editorial-cta" onClick={()=>{
          S.setOnboarded(true);
          ctx.setQuestion('care_02');
          ctx.nav('Today');
        }}>Enter Matria</button>
        <OnbDots i={4} n={5}/>
      </div>
    </div>
  );
}

function TodaySectionHead({label, action, onAction}){
  return (
    <div className="today-section-head">
      <span className="today-section-head__label">{label}</span>
      {action && (
        <button type="button" className="today-section-head__action" onClick={onAction}>{action}</button>
      )}
    </div>
  );
}

function TodayAccentArt({kind}){
  if(kind==='map') return (
    <span className="today-card__art" aria-hidden="true">
      <svg width="78" height="78" viewBox="0 0 78 78" fill="none">
        <circle cx="52" cy="28" r="1.2" fill="#dcba84" opacity=".55"/>
        <circle cx="44" cy="36" r="1" fill="#dcba84" opacity=".4"/>
        <circle cx="58" cy="40" r="1.4" fill="#dcba84" opacity=".5"/>
        <circle cx="48" cy="48" r="1" fill="#dcba84" opacity=".35"/>
        <circle cx="62" cy="32" r="1" fill="#dcba84" opacity=".45"/>
        <circle cx="40" cy="42" r="1.2" fill="#dcba84" opacity=".38"/>
        <circle cx="54" cy="52" r="22" stroke="rgba(200,160,100,.22)" strokeWidth="1"/>
        <circle cx="54" cy="52" r="14" stroke="rgba(200,160,100,.16)" strokeWidth=".8"/>
        <circle cx="54" cy="52" r="5" fill="#c98f6a" opacity=".95"/>
        <circle cx="54" cy="52" r="9" fill="rgba(201,143,106,.18)"/>
        <circle cx="54" cy="52" r="16" fill="rgba(201,143,106,.08)"/>
      </svg>
    </span>
  );
  if(kind==='letters') return (
    <span className="today-card__art" aria-hidden="true">
      <svg width="72" height="72" viewBox="0 0 72 72" fill="none">
        <ellipse cx="36" cy="38" rx="26" ry="20" fill="rgba(201,143,106,.12)"/>
        <rect x="18" y="22" width="36" height="26" rx="2" stroke="rgba(212,168,108,.7)" strokeWidth="1.1" fill="rgba(255,255,255,.03)"/>
        <path d="M18.5 23.5L36 36.5l17.5-13" stroke="rgba(212,168,108,.55)" strokeWidth="1"/>
        <path d="M18 48l11-9.5 7 5.5 16-12.5v8.5H18V48z" fill="rgba(201,143,106,.08)" stroke="rgba(212,168,108,.35)" strokeWidth=".8"/>
        <circle cx="36" cy="38" r="5.5" fill="rgba(201,143,106,.75)" stroke="rgba(220,186,132,.5)" strokeWidth=".8"/>
        <circle cx="36" cy="38" r="2.2" fill="rgba(255,255,255,.25)"/>
      </svg>
    </span>
  );
  return (
    <span className="today-card__art" aria-hidden="true">
      <svg width="80" height="80" viewBox="0 0 80 80" fill="none">
        <ellipse cx="40" cy="58" rx="28" ry="10" fill="rgba(201,143,106,.1)"/>
        <path d="M16 58 Q40 18 64 58" stroke="rgba(212,168,108,.55)" strokeWidth="1.2" fill="none"/>
        <path d="M20 58 Q40 26 60 58" stroke="rgba(212,168,108,.28)" strokeWidth=".8" fill="none"/>
        <rect x="18" y="56" width="44" height="3" rx="1" fill="rgba(201,143,106,.2)"/>
        <circle cx="32" cy="42" r="1" fill="#dcba84" opacity=".7"/>
        <circle cx="44" cy="36" r="1.2" fill="#dcba84" opacity=".85"/>
        <circle cx="50" cy="44" r=".9" fill="#dcba84" opacity=".55"/>
        <circle cx="38" cy="34" r=".8" fill="#dcba84" opacity=".5"/>
        <path d="M40 32l2.2 4.5 5 .7-3.6 3.5.9 5-4.5-2.3-4.5 2.3.9-5-3.6-3.5 5-.7L40 32z" fill="rgba(201,143,106,.55)" opacity=".75"/>
      </svg>
    </span>
  );
}

function TodayPremiumCard({icon, title, meta, onClick, accent, busy}){
  return (
    <button type="button" className={'today-card'+(accent?' today-card--'+accent:'')} onClick={onClick}>
      <span className="today-card__icon">{icon}</span>
      <div className="today-card__body">
        <span className="today-card__title">{title}</span>
        {meta && <span className="today-card__meta">{meta}</span>}
      </div>
      {accent && <TodayAccentArt kind={accent}/>}
      <span className="today-card__chevron">{!busy && <Icon name="chevron" size={14}/>}</span>
    </button>
  );
}

function TodayLowerBody({ctx, convo, mapCard}){
  return (
    <React.Fragment>
      <div className="pad today-screen__below matria-section">
        <TodaySectionHead label="In conversation with" action="View all >" onAction={()=>ctx.nav('ConnectedWomen')}/>
        <div className="matria-section__content">
          <TodayConvoRail ids={convo} onPerson={id=>ctx.openSource(id)} onMore={()=>ctx.nav('Explore')}/>
        </div>
      </div>
      <div className="pad today-screen__below today-screen__cards">
        {mapCard}
        <TodayPremiumCard
          icon={<Envelope size={22} sealed/>}
          title="Letters move slowly here"
          meta="Sample letters to read. Sending opens later."
          accent="letters"
          onClick={()=>ctx.nav('Letters')}
        />
      </div>
      <div className="pad today-screen__below">
        <TodaySectionHead label="Continue your journey"/>
        <TodayPremiumCard
          icon={<Icon name="explore" size={20}/>}
          title="Guided paths through the archive"
          meta="Choose a path when you are ready to read."
          accent="paths"
          onClick={()=>ctx.nav('Paths')}
        />
      </div>
      <div className="pad today-screen__below today-screen__quote">
        <TodayQuoteBanner/>
      </div>
    </React.Fragment>
  );
}

/* Overview + design QA: mockup crop (convo rail through quote, no hero/ask) */
function TodayDesignPreview({ctx}){
  const D=window.MATRIA;
  const convo=['lorde','rich','herschel'];
  const mapCard=(
    <TodayPremiumCard
      icon={<SplashGlyph kind="stories" size={22}/>}
      title={<React.Fragment>Find women<br/>remembered&nbsp;near&nbsp;you</React.Fragment>}
      meta={<React.Fragment>Uses your location once,<br/>on this device only.</React.Fragment>}
      accent="map"
      onClick={()=>ctx.nav('Pilgrimage')}
    />
  );
  return (
    <div className="screen dark matria-dark today-route">
      <StatusBar/>
      <div className="s-body today-screen today-screen--mockup">
        <TodayLowerBody ctx={ctx} convo={convo} mapCard={mapCard}/>
        <div className="scrollfade"/>
      </div>
      <TabBar active="Today" onNav={ctx.nav}/>
    </div>
  );
}

function TodayConvoRail({ids, onPerson, onMore}){
  const D=window.MATRIA;
  return (
    <div className="matria-list today-convo-list">
      {ids.map(id=>{
        const n=D.get(id);
        if(!n) return null;
        return (
          <button key={id} type="button" className="lrow today-convo-row" onClick={()=>onPerson(id)}>
            <span className="lrow__slot" aria-hidden="true"><TypeGlyph type="person" size={18}/></span>
            <div className="today-convo-row__copy">
              <span className="today-convo-row__title">{n.title}</span>
              {n.role && <span className="today-convo-row__meta">{n.role}</span>}
            </div>
            <span className="today-convo-row__chev" aria-hidden="true"><Icon name="chevron" size={14}/></span>
          </button>
        );
      })}
      <button type="button" className="lrow today-convo-row today-convo-row--more" onClick={onMore}>
        <span className="lrow__slot" aria-hidden="true"><Icon name="explore" size={18}/></span>
        <div className="today-convo-row__copy">
          <span className="today-convo-row__title">More voices</span>
          <span className="today-convo-row__meta">Browse the archive</span>
        </div>
        <span className="today-convo-row__chev" aria-hidden="true"><Icon name="chevron" size={14}/></span>
      </button>
    </div>
  );
}

function TodayQuoteBanner(){
  return (
    <div className="today-quote">
      <span className="today-quote__star" aria-hidden="true"><Icon name="explore" size={11}/></span>
      <p className="today-quote__text">You don't need to know where to begin.<br/>The right words will find you.</p>
      <span className="today-quote__sprig" aria-hidden="true"><Sprig w={58} h={132} color="rgba(200,160,100,.28)"/></span>
    </div>
  );
}

function Today({ctx}){
  const D=window.MATRIA;
  const S=useMStore();
  const [askVal,setAskVal]=useState('');
  const TODAY_SUGGESTED=[
    {text:'Why do I feel guilty when I rest?',icon:'leaf'},
    {text:'How do I stop overthinking?',icon:'sparkle'},
    {text:'What am I avoiding?',icon:'leaf'},
  ];
  // personalized "in conversation with": the reader's own followed women +
  // the women behind answers they saved, on-device. New readers get a default.
  const st=S.get();
  const personalIds=[
    ...st.follows.filter(id=>{const n=D.get(id);return n&&n.type==='person';}),
    ...st.saved.flatMap(s=>{const q=D.QUESTIONS[s.qid];return q?q.women:[];}),
  ];
  const personal=[...new Set(personalIds)].filter(id=>D.get(id)).slice(0,3);
  const convo=personal.length? personal : ['lorde','rich','herschel'];
  // on-device location: the coordinate is used once to pick a city, never stored.
  const [locating,setLocating]=useState(false);
  const [denied,setDenied]=useState(false);
  const cityKey=st.city;
  const cityObj=cityKey && D.PLACES.cities[cityKey];
  function locate(){
    if(!navigator.geolocation){ setDenied(true); return; }
    setLocating(true);
    navigator.geolocation.getCurrentPosition(
      pos=>{ setLocating(false); const k=D.nearestCity(pos.coords.latitude,pos.coords.longitude); if(k) S.setCity(k); else setDenied(true); },
      ()=>{ setLocating(false); setDenied(true); },
      {timeout:8000, maximumAge:600000}
    );
  }
  function submitAsk(text){
    const q=(text||askVal).trim();
    if(!q) return;
    setAskVal('');
    ctx.ask(q);
  }
  const hour=new Date().getHours();
  const greet= hour<5 ? 'Still awake' : hour<12 ? 'Good morning' : hour<18 ? 'Good afternoon' : 'Good evening';
  const carrying=S.get().carrying;
  const mapCard=cityObj ? (
    <TodayPremiumCard
      icon={<SplashGlyph kind="stories" size={22}/>}
      title={'You are near '+cityObj.city}
      meta={cityObj.sites.filter(s=>s.who).slice(0,2).map(s=>s.who.split(' ').slice(-1)[0]||s.who).join(' and ')+' are remembered near you.'}
      accent="map"
      onClick={()=>ctx.nav('Pilgrimage')}
    />
  ) : denied ? (
    <TodayPremiumCard
      icon={<SplashGlyph kind="stories" size={22}/>}
      title="Places women are remembered"
      meta="Explore pilgrimage sites across the archive."
      accent="map"
      onClick={()=>ctx.nav('Pilgrimage')}
    />
  ) : (
    <TodayPremiumCard
      icon={<SplashGlyph kind="stories" size={22}/>}
      title={locating?'Finding women near you…':'Find women remembered near you'}
      meta={locating?'Reading your location on this device.':'Uses your location once, on this device only.'}
      accent="map"
      busy={locating}
      onClick={locate}
    />
  );
  return (
    <div className="screen dark today-route">
      <StatusBar/>
      <div className="s-body today-screen">
        <div className="pad today-hero">
          <div className="today-hero__row">
            <div>
              <h1 className="title today-hero__title">{greet}{S.get().name?', '+S.get().name:''}</h1>
              {carrying
                ? <p className="lead today-hero__lead today-hero__lead--link" onClick={()=>ctx.nav('ChangeCarrying')}>Carrying <span className="today-hero__carry">{carrying.toLowerCase()}</span>. Tap to change.</p>
                : <p className="lead today-hero__lead today-hero__lead--link" onClick={()=>ctx.nav('ChangeCarrying')}>Choose what you are carrying</p>}
            </div>
            <button type="button" className="today-hero__bell" aria-label="Notifications"><Icon name="bell" size={22}/></button>
          </div>
        </div>
        <div className="pad today-ask">
          <p className="today-ask__prompt"><Icon name="explore" size={14}/>What would you like to explore today?</p>
          <div className="today-ask__bar">
            <input
              type="text"
              className="today-ask__input"
              placeholder="Ask Matria a question…"
              value={askVal}
              onChange={e=>setAskVal(e.target.value)}
              onKeyDown={e=>{if(e.key==='Enter') submitAsk();}}
              aria-label="Ask Matria a question"
              autoComplete="off"
            />
            <button type="button" className="today-ask__submit" onClick={()=>submitAsk()} aria-label="Submit question">
              <Icon name="arrow" size={17} stroke={2}/>
            </button>
          </div>
        </div>
        <div className="pad today-suggested matria-section">
          <div className="today-suggested__label">Suggested</div>
          <div className="today-suggested__list matria-section__content">
            {TODAY_SUGGESTED.map(s=>(
              <button key={s.text} type="button" className="today-suggested__pill" onClick={()=>ctx.ask(s.text)}>
                <span className="today-suggested__icon" aria-hidden="true">
                  {s.icon==='sparkle' ? <Icon name="explore" size={15}/> : <Icon name="leaf" size={15}/>}
                </span>
                <span className="today-suggested__text">{s.text}</span>
              </button>
            ))}
          </div>
        </div>
        <div className="pad today-fragment-wrap">
          {(()=>{const f=window.MATRIA_FRAGMENTS.forReader(S.get().carrying);return (
          <div className="today-fragment today-fragment--editorial" onClick={()=>ctx.openFragment(f.id)}>
            <div className="today-fragment__sprig" aria-hidden="true"><Sprig w={66} h={150} color="#c8a25e"/></div>
            <div className="label today-fragment__label">Daily Fragment</div>
            <FragmentQuote f={f} size={18}/>
          </div>);})()}
        </div>
        <TodayLowerBody ctx={ctx} convo={convo} mapCard={mapCard}/>
        <div className="scrollfade"/>
      </div>
      <TabBar active="Today" onNav={ctx.nav}/>
    </div>
  );
}

// moods group the Atlas's 23 emotional tones into a few felt registers
const MOODS=[
  {key:'weary',     label:'Weary',     icon:'explore', tones:['weary','hollow','heavy']},
  {key:'searching', label:'Searching', icon:'search',  tones:['searching','wondering','curious','unsettled']},
  {key:'tender',    label:'Tender',    icon:'heart',   tones:['tender','reverent','hopeful']},
  {key:'restless',  label:'Rest',      icon:'sun',     tones:['restless','anxious','ambivalent','frustrated','tentative']},
  {key:'defiant',   label:'Defiant',   icon:'explore', tones:['defiant','fierce','wry']},
  {key:'grieving',  label:'Grieving',  icon:'heart',   tones:['mournful','bittersweet','guilty','quiet','steady']},
];
function Ask({ctx}){
  const D=window.MATRIA;
  const [val,setVal]=useState('');
  const [mood,setMood]=useState(null);
  const moodQs = mood ? window.MATRIA_ATLAS.questions.filter(q=>(MOODS.find(m=>m.key===mood).tones).includes(q.tone)).slice(0,3) : [];
  const submit=()=>ctx.ask((val||'').trim()||D.SUGGESTED[0], mood);
  const moodChips=MOODS.slice(0,4);
  return (
    <div className="screen matria-cream ask-screen">
      <StatusBar/>
      <div className="s-body pad ask-screen__body matria-flow">
        <div className="ask-screen__head">
          <span className="ask-screen__glyph" aria-hidden="true"><Icon name="explore" size={72} stroke={.7}/></span>
          <h1 className="ask-screen__title">
            <span className="ask-screen__title-a">Ask a</span>{' '}
            <span className="ask-screen__title-b">Question</span>
          </h1>
          <p className="matria-lead ask-screen__lead">Bring a question. Matria will search the archive and draw connections.</p>
        </div>
        <div className="ask-compose">
          <input
            className="ask-compose__input"
            value={val}
            onChange={e=>setVal(e.target.value)}
            onKeyDown={e=>{ if(e.key==='Enter'){ e.preventDefault(); submit(); } }}
            name="matria-question"
            aria-label="Question for Matria"
            autoComplete="off"
            placeholder="Ask a question, or say how you feel"
          />
          <button type="button" className="ask-compose__submit" aria-label="Ask Matria" onClick={submit}>
            <Icon name="explore" size={18} stroke={1.4}/>
          </button>
        </div>
        <section className="matria-section">
          <div className="matria-rule ask-screen__rule" aria-hidden="true">
            <span className="matria-section-label">Or start from how you feel</span>
          </div>
          <div className="hscroll section-controls ask-screen__chips">
            {moodChips.map(m=>(
              <button key={m.key} type="button" className={'ask-chip chip'+(m.key===mood?' on':'')} onClick={()=>setMood(m.key===mood?null:m.key)}>
                <Icon name={m.icon} size={12} stroke={1.3}/>
                <span>{m.label}</span>
              </button>
            ))}
          </div>
          {mood && <div className="ask-question-list matria-section__content">
            {moodQs.map(q=>(
              <button key={q.id} type="button" className="ask-question-row" onClick={()=>setVal(q.text)}>
                <span className="ask-question-row__star" aria-hidden="true"><Icon name="explore" size={13} stroke={1.2}/></span>
                <span className="ask-question-row__text">{q.text}</span>
                <span className="ask-question-row__go" aria-hidden="true"><Icon name="arrow" size={14}/></span>
              </button>
            ))}
          </div>}
        </section>
        <div className="matria-rule ask-screen__rule ask-screen__rule--star" aria-hidden="true">
          <Icon name="explore" size={9} stroke={1.2}/>
        </div>
        <section className="matria-section">
          <div className="matria-rule ask-screen__rule" aria-hidden="true">
            <span className="matria-section-label">Suggested questions</span>
          </div>
          <div className="ask-question-list matria-section__content">
            {D.SUGGESTED.slice(0,3).map((q,i)=>(
              <button key={q} type="button" className="ask-question-row" onClick={()=>setVal(q)}>
                <span className="ask-question-row__star" aria-hidden="true"><Icon name="explore" size={13} stroke={1.2}/></span>
                <span className="ask-question-row__text">
                  {q}
                  {i===0 && <span className="ask-question-row__tag">Popular</span>}
                </span>
                <span className="ask-question-row__go" aria-hidden="true"><Icon name="arrow" size={14}/></span>
              </button>
            ))}
          </div>
        </section>
        <p className="ask-screen__disclaimer">Matria gives sourced reflection, not diagnosis or prediction.</p>
      </div>
      <TabBar active="Ask" onNav={ctx.nav}/>
    </div>
  );
}

function Searching({ctx}){
  useEffect(()=>{
    if(ctx.static) return;
    const t=setTimeout(()=>{ (ctx.afterSearch||(()=>ctx.nav('Answer')))(); },720);
    return ()=>clearTimeout(t);
  },[]);
  return (
    <div className="screen dark matria-dark">
      <StatusBar/>
      <div className="s-body pad" style={{display:'flex',flexDirection:'column',paddingTop:24,position:'relative',overflow:'hidden'}}>
        <div style={{position:'absolute',left:0,right:0,bottom:0,height:330,pointerEvents:'none',
          WebkitMaskImage:'linear-gradient(180deg, transparent 0%, #000 60%)',
          maskImage:'linear-gradient(180deg, transparent 0%, #000 60%)'}}>
          <ConstellationBackground dim={0.5}/>
        </div>
        <h1 className="title display-title" style={{position:'relative'}}>Opening<br/>the archive…</h1>
        <div style={{display:'flex',alignItems:'center',gap:13,marginTop:28,position:'relative'}}>
          <span style={{width:30,height:30,borderRadius:'50%',border:'1px solid var(--line-gold)',display:'flex',alignItems:'center',justifyContent:'center',color:'var(--gold)',flex:'none',background:'rgba(200,160,100,.08)'}}>
            <TypeGlyph type="tradition" size={14}/>
          </span>
          <span style={{fontSize:13.5,color:'var(--ctext)',lineHeight:1.45}}>Matching your question to sourced entries already in Matria.</span>
        </div>
        <div style={{flex:1}}/>
        <p style={{textAlign:'center',fontSize:12,color:'var(--ctext-soft)',fontStyle:'italic',marginBottom:22,position:'relative'}}>Matria never invents an answer.</p>
      </div>
    </div>
  );
}

Object.assign(window,{Splash,OnbDots,Onboarding1,Onboarding2,Onboarding3,OnboardingPreview,Onboarding4,ChangeCarrying,Today,TodayDesignPreview,Ask,Searching});
