/* ============================================================================
   MATRIA, screens, part 3: Journal, SanctuaryList, NoSources.
   ============================================================================ */

function fmtDate(ts){
  return new Date(ts).toLocaleDateString('en-GB',{day:'numeric',month:'short',year:'numeric'});
}

/* Journal, write a reflection linked to the current question */
const J_PROMPTS=[
  'Begin with the sentence you have been avoiding.',
  'Describe where this question lives in your body.',
  'Write to the woman you were five years ago. She is listening.',
  'What would you say if no one could correct you?',
  'Name the thing. Then name what it costs you.',
  'Write the smallest true sentence you know today.',
];
function Journal({ctx}){
  const S=useMStore();
  const [text,setText]=useState(()=>{ try{return localStorage.getItem('matria_draft')||'';}catch(e){return '';} });
  const [tags,setTags]=useState([]);
  const [pi,setPi]=useState(0);
  const [justSaved,setJustSaved]=useState(false);
  const entries=S.get().journal;
  const themeTags=(ctx.q.ideas||[]).slice(0,4).map(id=>window.MATRIA.get(id)).filter(Boolean).map(n=>n.title);
  const words=text.trim()? text.trim().split(/\s+/).length : 0;
  useEffect(()=>{ try{localStorage.setItem('matria_draft',text);}catch(e){} },[text]);
  function save(){
    if(!text.trim()) return;
    S.addJournal(ctx.q.id, ctx.q.text, text.trim(), tags);
    setText(''); setTags([]); try{localStorage.removeItem('matria_draft');}catch(e){}
    setJustSaved(true); setTimeout(()=>setJustSaved(false),6000);
  }
  return (
    <div className="screen matria-cream">
      <StatusBar/>
      <TopBar onBack={()=>ctx.back()} title="Journal"/>
      <div className="s-body pad journal-screen" style={{paddingTop:6}}>
        <h1 className="title">Journal</h1>
        <p className="journal-lead">Private notes on this device, linked to the question you asked. Save here, or send a passage as a letter when you are ready.</p>
        <div className="journal-linked card">
          <div className="label" style={{marginBottom:6}}>Linked question</div>
          <p className="journal-linked__q">{ctx.q.text}</p>
        </div>
        <div className="journal-prompt">
          <span style={{color:'var(--gold-line)',marginTop:1}}><Icon name="pen" size={16}/></span>
          <div className="journal-prompt__body">
            <div className="label" style={{fontSize:9,marginBottom:4}}>If you don't know where to begin</div>
            <p className="journal-prompt__text quote-text">{J_PROMPTS[pi%J_PROMPTS.length]}</p>
          </div>
          <button type="button" className="journal-prompt__shuffle" onClick={()=>setPi(p=>p+1)}>Another</button>
        </div>
        <div className="journal-field">
          <textarea value={text} onChange={e=>setText(e.target.value)} name="journal-reflection" aria-label="Journal reflection" autoComplete="off" placeholder="Write your reflection…"/>
          <span className="journal-field__meta">{words>0?words+' words · draft kept':'draft kept automatically'}</span>
        </div>
        {/* theme tags */}
        <div style={{display:'flex',flexWrap:'wrap',gap:7,marginTop:10}}>
          {themeTags.map(t=>{
            const on=tags.includes(t);
            return <button key={t} className={'chip'+(on?' on':'')} style={{height:26,fontSize:11}} onClick={()=>setTags(s=>on?s.filter(x=>x!==t):[...s,t])}>{t}</button>;
          })}
        </div>
        <button className="btn btn-navy" style={{marginTop:13,height:48}} onClick={save}>Save Entry</button>
        {justSaved && (
          <div className="anim-up journal-saved">
            <span className="journal-saved__icon"><Icon name="check" size={13} stroke={2.4}/></span>
            <div className="journal-saved__body">
              <div className="journal-saved__title">Kept in your Sanctuary</div>
              <div className="journal-saved__meta">Send as a letter, if you wish</div>
            </div>
            <button type="button" className="btn-cream btn-cream--ghost journal-saved__btn" onClick={()=>window.openLetterSend?window.openLetterSend(ctx):ctx.nav('MembershipUnlock')}>Send</button>
          </div>
        )}
        {entries.length>0 && <>
          <div className="label" style={{margin:'20px 0 10px'}}>Past reflections · {entries.length}</div>
          <div style={{display:'flex',flexDirection:'column',gap:9,paddingBottom:10}}>
            {entries.map(j=>(
              <div key={j.id} className="card" style={{padding:'12px 14px'}}>
                <div style={{display:'flex',justifyContent:'space-between',alignItems:'baseline',gap:8}}>
                  <span style={{fontSize:10.5,color:'var(--ink-faint)'}}>{fmtDate(j.date)} · {j.qtext}</span>
                  <button onClick={()=>S.deleteJournal(j.id)} style={{background:'none',border:'none',cursor:'pointer',color:'#b35b48',fontSize:10.5,padding:0,fontFamily:'var(--font-body)'}}>Delete</button>
                </div>
                <p style={{fontSize:13,color:'#46433d',lineHeight:1.5,margin:'7px 0 0',whiteSpace:'pre-wrap'}}>{j.text}</p>
                {j.tags&&j.tags.length>0 && <div style={{display:'flex',flexWrap:'wrap',gap:6,marginTop:8}}>{j.tags.map(t=><span key={t} className="tag" style={{height:20,fontSize:9}}>{t}</span>)}</div>}
              </div>
            ))}
          </div>
        </>}
        <p style={{textAlign:'center',fontSize:11,color:'var(--ink-faint)',fontStyle:'italic',margin:'12px 0 6px'}}>Your private writing is yours. You can delete it anytime.</p>
      </div>
    </div>
  );
}

/* Sanctuary list, saved answers / journal / follows / practices */
function SanctuaryList({ctx}){
  const S=useMStore(); const D=window.MATRIA;
  const kind=ctx.listKind||'saved';
  const st=S.get();
  const titles={saved:'Saved Answers', fragments:'Saved Fragments', journal:'Journal Reflections', follows:'Followed Lineages', practices:'Completed Practices'};
  let body=null;
  if(kind==='saved'){
    body = st.saved.length===0 ? <Empty msg="Your Sanctuary stays empty until you save an answer. Ask a question on Today, read the response, then tap Save." cta="Ask your first question" onCta={()=>ctx.nav('Ask')}/> :
      <div style={{display:'flex',flexDirection:'column',gap:11}}>
        {st.saved.map(s=>{const q=D.QUESTIONS[s.qid];const women=q?q.women:[];return (
          <div key={s.qid} className="saved-answer-card" onClick={()=>{ctx.setQuestion(s.qid); ctx.nav('FromMatria');}}>
            <div className="womb-field womb-field--card">
              <div className="womb-field__photo" style={{backgroundImage:'url(uploads/matria-onboarding-sanctuary.png)'}}/>
              <div className="womb-field__veil"/>
              <span className="womb-field__signal"/>
              <div className="womb-field__grain"/>
              <div className="womb-field__inner">
                <LineageCollage ids={women}/>
              </div>
            </div>
            <div className="saved-answer-card__body">
              <h2 className="saved-answer-card__title">{q?q.text:s.text}</h2>
              <div className="saved-answer-card__meta">Saved {fmtDate(s.date)}{women.length?' · '+women.length+' voices' : ''}</div>
              <div className="saved-answer-card__foot">
                <span className="saved-answer-card__cta">Open answer <Icon name="arrow" size={15}/></span>
                <button className="btn-cream btn-cream--ghost" style={{height:36,minHeight:36,padding:'0 12px',fontSize:11}} onClick={e=>{e.stopPropagation();ctx.setQuestion(s.qid);ctx.openQuestionMap();}}>View map</button>
              </div>
            </div>
          </div>);})}
      </div>;
  }
  if(kind==='fragments'){
    const FR=window.MATRIA_FRAGMENTS;
    body = st.fragments.length===0 ? <Empty msg="No fragments saved yet. When one stays with you, keep it here." cta="See today's fragment" onCta={()=>ctx.openFragment(FR.daily().id)}/> :
      <div style={{display:'flex',flexDirection:'column',gap:9}}>
        {st.fragments.map(s=>{const f=FR.items[s.id]; if(!f) return null; return (
          <div key={s.id} className="card" style={{padding:'13px 14px',cursor:'pointer'}} onClick={()=>ctx.openFragment(f.id)}>
            <FragmentQuote f={f} size={14.5}/>
            <div style={{display:'flex',alignItems:'center',flexWrap:'wrap',gap:8,marginTop:9}}>
              <span style={{fontSize:11,color:'#5a5246',fontWeight:700}}>{f.speaker_or_source}</span>
              <span style={{fontSize:9.5,color:'var(--ink-faint)'}}>{f.themes.join(' · ')}</span>
              <span style={{fontSize:9.5,color:'var(--ink-faint)',marginLeft:'auto'}}>Saved {fmtDate(s.date)}</span>
            </div>
            <button onClick={e=>{e.stopPropagation();ctx.nav('Journal');}} className="btn-cream" style={{marginTop:10,height:38,minHeight:38,fontSize:11}}>Write with this fragment</button>
          </div>);})}
      </div>;
  }
  if(kind==='journal'){
    body = st.journal.length===0 ? <Empty msg="Private notes live here after you write from an answer. Nothing is saved until you tap Save Entry." cta="Ask a question" onCta={()=>ctx.nav('Ask')}/> :
      <div style={{display:'flex',flexDirection:'column',gap:9}}>
        {st.journal.map(j=>(
          <div key={j.id} className="card" style={{padding:'12px 14px'}}>
            <div style={{fontSize:10.5,color:'var(--ink-faint)'}}>{fmtDate(j.date)} · {j.qtext}</div>
            <p style={{fontSize:13,color:'#46433d',lineHeight:1.5,margin:'7px 0 0',whiteSpace:'pre-wrap'}}>{j.text}</p>
          </div>))}
      </div>;
  }
  if(kind==='follows'){
    body = st.follows.length===0 ? <Empty msg="Women you follow appear here and in your constellation. Open any source and tap Follow Lineage." cta="Explore the archive" onCta={()=>ctx.nav('Explore')}/> :
      <div style={{display:'flex',flexDirection:'column',gap:9}}>
        {st.follows.map(id=>{const n=D.get(id); if(!n) return null; return (
          <div key={id} className="lrow" style={{padding:10}} onClick={()=>ctx.openSource(id)}>
            <Portrait pic={n.pic} id={n.id} name={n.title} size={46} round={false} radius={9}/>
            <div style={{flex:1}}>
              <div style={{fontFamily:'var(--font-display)',fontSize:14.5,color:'var(--ink)',fontWeight:600}}>{n.title}</div>
              <div style={{fontSize:11,color:'var(--ink-soft)',marginTop:1}}>{n.role}</div>
            </div>
            <span style={{color:'var(--ink-faint)'}}><Icon name="chevron" size={15}/></span>
          </div>);})}
      </div>;
  }
  if(kind==='practices'){
    body = st.practices.length===0 ? <Empty msg="Mark a practice complete from any answer and it will be recorded here." cta="Ask Matria" onCta={()=>ctx.nav('Ask')}/> :
      <div style={{display:'flex',flexDirection:'column',gap:9}}>
        {st.practices.map(qid=>{const q=D.QUESTIONS[qid]; if(!q) return null; return (
          <div key={qid} className="card" style={{padding:'12px 14px',display:'flex',gap:11,alignItems:'flex-start'}}>
            <span style={{width:22,height:22,borderRadius:'50%',background:'#4ca8a0',display:'flex',alignItems:'center',justifyContent:'center',flex:'none',color:'#fff',marginTop:2}}><Icon name="check" size={12} stroke={2.4}/></span>
            <div>
              <div style={{fontSize:12.5,color:'var(--ink)',fontWeight:700,lineHeight:1.3}}>{q.text}</div>
              <p style={{fontSize:12,color:'#5a5246',lineHeight:1.5,margin:'5px 0 0'}}>{practiceText(q)}</p>
            </div>
          </div>);})}
      </div>;
  }
  return (
    <div className="screen matria-cream has-womb-sky">
      <StatusBar/>
      <TopBar onBack={()=>ctx.back()} title="Sanctuary"/>
      <div className="s-body pad" style={{paddingTop:6}}>
        <div className="cream-page-head">
          <h1 className="title">{titles[kind]}</h1>
          {kind==='saved' && <p className="lead">Tap any answer to return to its lineage.</p>}
        </div>
        {kind==='saved' && <WombField variant="strip"/>}
        {body}
      </div>
    </div>
  );
}

function Empty({msg, cta, onCta}){
  return (
    <div className="empty-state">
      <div className="empty-state__art" style={{margin:'0 auto',maxWidth:240}}>
        <WombField variant="card"><LineageCollage ids={['lorde','rich','herschel']}/></WombField>
      </div>
      <p className="empty-state__copy">{msg}</p>
      <button className="btn btn-tan" style={{width:190,margin:'0 auto',height:44}} onClick={onCta}>{cta}</button>
    </div>
  );
}

/* Honest fallback, the archive cannot answer */
function NoSources({ctx}){
  const S=useMStore();
  const D=window.MATRIA;
  const hints=(D.nearQuestions||(()=>[]))(ctx.question||'', {carrying:S.get().carrying});
  return (
    <div className="screen dark matria-dark">
      <StatusBar/>
      <TopBar onBack={()=>ctx.back()} dark/>
      <div className="s-body pad" style={{display:'flex',flexDirection:'column',paddingTop:10,textAlign:'center'}}>
        <div style={{position:'relative',margin:'8px -24px 0',height:170,overflow:'hidden',
          WebkitMaskImage:'radial-gradient(120% 82% at 50% 45%, #000 50%, transparent 96%)',
          maskImage:'radial-gradient(120% 82% at 50% 45%, #000 50%, transparent 96%)'}}>
          <ConstellationBackground dim={0.58}/>
        </div>
        <h1 className="title" style={{marginTop:8}}>Insufficient sources</h1>
        <p className="bodytext" style={{margin:'14px auto 0',maxWidth:230,color:'var(--ctext-soft)'}}>Matria does not have enough grounded archive material to answer this honestly yet.</p>
        <p style={{fontSize:12,color:'var(--ctext-faint)',margin:'12px auto 0',maxWidth:250,lineHeight:1.55}}>Try a lived question, a mood chip on Ask, or one of the archive questions below. Matria never invents an answer.</p>
        {hints.length>0 && <div style={{marginTop:18,width:'100%',textAlign:'left'}}>
          <div className="label" style={{marginBottom:8}}>Questions the archive can hold</div>
          <div style={{display:'flex',flexDirection:'column',gap:8}}>
            {hints.slice(0,3).map(h=>{
              const label=h.text||(h.id&&D.QUESTIONS[h.id]&&D.QUESTIONS[h.id].text);
              if(!label) return null;
              return (
              <button key={h.id||label} type="button" className="lrow" style={{minHeight:48,textAlign:'left',width:'100%',background:'rgba(255,255,255,.03)',borderColor:'var(--line-dark)'}} onClick={()=>ctx.ask(label)}>
                <span style={{flex:1,fontSize:12.5,color:'var(--ctext)',lineHeight:1.4}}>{label}</span>
                <span style={{color:'var(--gold)'}}><Icon name="chevron" size={14}/></span>
              </button>
            );})}
          </div>
        </div>}
        <div style={{flex:1,minHeight:12}}/>
        <button className="btn btn-tan" style={{width:'100%'}} onClick={()=>ctx.nav('Explore')}>Explore related fragments</button>
        <button className="btn btn-ghost-dark" style={{width:'100%',margin:'10px 0 16px'}} onClick={()=>ctx.nav('Suggest')}>Suggest a source for the archive</button>
      </div>
    </div>
  );
}

Object.assign(window,{Journal,SanctuaryList,NoSources,fmtDate});
