// Pages — part 3: Story Weaver, Ask, Collaborate, Year in Review.
(function () {
const { useState, useEffect, useRef } = React;
const { cx, wash } = LMTXUtil;
const I = window.LMTIcons;
const D = LMTData, D2 = LMTX2;
const Page = window.LMTXPage, Mini = window.LMTXMini, VizWindow = window.LMTXVizWindow;

// NOTE: PageWeaver (Story Weaver) now lives in lib/weaver.jsx + weaver-panels.jsx
// as the full Auto-Weave behaviour emulation. It is loaded after this file and
// assigns window.PageWeaver, which the router resolves at render time.

// ── ASK (AI chat + semantic search) ──────────────────────────────────────────
function PageAsk({ go }) {
  const [msgs, setMsgs] = useState(D2.chat);
  const [q, setQ] = useState('');
  const endRef = useRef(null);
  useEffect(() => { endRef.current?.scrollIntoView?.({ block:'end' }); }, [msgs]);
  const send = (text) => {
    const t = text || q; if (!t.trim()) return;
    setMsgs(m => [...m, { who:'you', text:t }]);
    setQ('');
    setTimeout(() => setMsgs(m => [...m, { who:'ai', text:'Three low points this year: the fight 18 days ago, the BART morning 58 days ago, and quitting the agency contract. After each, something steadier followed within a week — a walk, a phone call, a decision. The pattern is real.', cites:['e05','e09','e10'] }]), 700);
  };
  const prompts = ['What made me happiest this spring?','Who have I drifted from?','Find fragile memories I never finished','Summarize my year with Lin'];
  return (
    <Page max={920}>
      <PageHead kicker="Create" icon={<I.Sparkles/>} title="Ask the Weaver"
        sub="Search your memories in plain language. Every answer cites the leaves it drew from — nothing invented."/>
      <div className="card-r scroll" style={{ flex:1, minHeight:380, maxHeight:'58vh', overflowY:'auto', padding:'20px 22px', display:'flex', flexDirection:'column', gap:18 }}>
        {msgs.map((m,i) => <Bubble key={i} m={m} go={go}/>)}
        <div ref={endRef}/>
      </div>
      {/* suggestion chips */}
      <div style={{ display:'flex', gap:8, flexWrap:'wrap' }}>
        {prompts.map(p => <button key={p} onClick={() => send(p)} className="press pill" style={{ cursor:'pointer', padding:'7px 12px', fontSize:12, background:'var(--raised)', borderColor:'var(--edge)' }}><I.Sparkles style={{ fontSize:12, color:'var(--accent)' }}/>{p}</button>)}
      </div>
      <div className="card-r" style={{ display:'flex', alignItems:'center', gap:10, padding:'8px 8px 8px 16px' }}>
        <I.Search style={{ fontSize:18, color:'var(--faint)', flex:'0 0 auto' }}/>
        <input value={q} onChange={e => setQ(e.target.value)} onKeyDown={e => e.key==='Enter' && send()} placeholder="Ask anything about your life…" style={{ flex:1, border:'none', outline:'none', background:'transparent', fontFamily:'inherit', fontSize:15, color:'var(--ink)' }}/>
        <button className="icon-btn"><I.Mic/></button>
        <button onClick={() => send()} className="btn btn-pri press" style={{ width:40, height:40, padding:0 }}><I.ArrowRight style={{ fontSize:18 }}/></button>
      </div>
    </Page>
  );
}
function Bubble({ m, go }) {
  if (m.who === 'you') return (
    <div className="rise" style={{ alignSelf:'flex-end', maxWidth:'78%', background:'var(--accent)', color:'var(--accent-fg)', padding:'11px 15px', borderRadius:'16px 16px 4px 16px', fontSize:14.5, lineHeight:1.5, boxShadow:'0 4px 14px -6px var(--accent)' }}>{m.text}</div>
  );
  return (
    <div className="rise" style={{ alignSelf:'flex-start', maxWidth:'88%', display:'flex', gap:11 }}>
      <span style={{ flex:'0 0 auto', width:34, height:34, borderRadius:11, background:'linear-gradient(150deg, var(--accent), color-mix(in oklab, var(--accent) 55%, #000))', display:'grid', placeItems:'center', color:'var(--accent-fg)', boxShadow:'0 4px 12px -4px var(--accent)' }} className="breathe"><I.Sparkles style={{ fontSize:17 }}/></span>
      <div style={{ minWidth:0 }}>
        <div style={{ background:'var(--sunken)', border:'1px solid var(--hair)', padding:'12px 15px', borderRadius:'4px 16px 16px 16px', fontSize:14.5, lineHeight:1.6, color:'var(--ink)' }}>{m.text}</div>
        {m.cites && <div style={{ display:'flex', gap:8, marginTop:9, flexWrap:'wrap' }}>
          {m.cites.map(id => { const e = D.events.find(x => x.id === id); if (!e) return null; return (
            <button key={id} onClick={() => go('scene')} className="press" style={{ display:'flex', alignItems:'center', gap:7, padding:'5px 10px', borderRadius:9, background:'var(--raised)', border:'1px solid var(--edge)', cursor:'pointer', maxWidth:240 }}>
              <LeafShape color={LMT.leafFor(e.daysSince)} size={14}/><span style={{ fontSize:11.5, color:'var(--muted)', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{e.title}</span>
            </button>); })}
        </div>}
      </div>
    </div>
  );
}

// ── COLLABORATE ──────────────────────────────────────────────────────────────
function PageCollab({ go }) {
  const here = D2.collaborators.filter(c => c.here);
  return (
    <Page max={1240}>
      <PageHead kicker="Together" icon={<I.Compass/>} title="Collaborate"
        sub="Memories are better remembered together. See who's here, what they're weaving, and where consent is shared."
        right={<button className="btn btn-pri press"><I.Plus style={{ fontSize:16 }}/>Invite</button>}/>
      <div className="lx-cols-main">
        <div style={{ minWidth:0, display:'flex', flexDirection:'column', gap:18 }}>
          {/* live canvas */}
          <div className="card-r" style={{ overflow:'hidden' }}>
            <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', padding:'12px 16px', borderBottom:'1px solid var(--hair)' }}>
              <span className="disp" style={{ fontSize:14.5, fontWeight:600 }}>Family · shared canvas</span>
              <span style={{ fontSize:11.5, color:'var(--muted)', display:'flex', alignItems:'center', gap:6 }}><span className="breathe" style={{ width:7, height:7, borderRadius:'50%', background:'#22c55e' }}/>{here.length} editing live</span>
            </div>
            <div style={{ position:'relative', height:300, background:'var(--tree-bg)' }}>
              <LifeGraph height={300} width={620} dense showLabels={false}/>
              {here.map((c,i) => c.cursor && (
                <div key={c.id} className="floaty" style={{ position:'absolute', left:`${c.cursor.x}%`, top:`${c.cursor.y}%`, animationDelay:`${i*0.5}s`, pointerEvents:'none', zIndex:5 }}>
                  <svg width="20" height="20" viewBox="0 0 20 20" style={{ filter:`drop-shadow(0 2px 4px ${c.color}88)` }}><path d="M3 3 L17 9 L10 11 L8 17 Z" fill={c.color} stroke="#fff" strokeWidth="1.2"/></svg>
                  <span style={{ position:'absolute', left:16, top:14, background:c.color, color:'#fff', fontSize:10, fontWeight:700, padding:'2px 7px', borderRadius:7, whiteSpace:'nowrap' }}>{c.name}</span>
                </div>
              ))}
            </div>
          </div>
          <div>
            <SectionHead title="Activity" sub="Live across all your shared scenes"/>
            <div className="card-r" style={{ padding:'6px 6px' }}>
              {D2.activity.map((a,i) => (
                <div key={i} className="rise" style={{ display:'flex', alignItems:'center', gap:11, padding:'11px 12px', borderBottom: i < D2.activity.length-1 ? '1px solid var(--hair)' : 'none', '--i':i }}>
                  <Avatar name={a.who} color={a.color} size={32}/>
                  <div style={{ flex:1, minWidth:0, fontSize:13.5, color:'var(--muted)', lineHeight:1.4 }}>
                    <b style={{ color:'var(--ink)', fontWeight:600 }}>{a.who}</b> {a.verb} <span style={{ color:'var(--ink)' }}>{a.obj}</span>
                  </div>
                  <span className="mono" style={{ fontSize:11, color:'var(--faint)', flex:'0 0 auto' }}>{a.t}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
        <div style={{ display:'flex', flexDirection:'column', gap:16, minWidth:0 }}>
          <div className="card-r" style={{ padding:16 }}>
            <SectionHead title="Who's here" count={here.length}/>
            <div style={{ display:'flex', flexDirection:'column', gap:3 }}>
              {D2.collaborators.map(c => (
                <div key={c.id} style={{ display:'flex', alignItems:'center', gap:11, padding:'8px 8px', borderRadius:11 }}>
                  <Avatar name={c.name} color={c.color} size={36} here={c.here}/>
                  <div style={{ flex:1, minWidth:0 }}>
                    <div style={{ fontSize:13.5, fontWeight:600 }}>{c.name}</div>
                    <div style={{ fontSize:11, color: c.here ? 'var(--accent)' : 'var(--faint)' }}>{c.doing}</div>
                  </div>
                  <span className="mono" style={{ fontSize:10, color:'var(--faint)' }}>{c.scene}</span>
                </div>
              ))}
            </div>
          </div>
          <div className="card-r" style={{ padding:16 }}>
            <SectionHead title="Consent & sharing"/>
            <div style={{ display:'flex', flexDirection:'column', gap:11 }}>
              {[['Family','scene',3],['Reading','scene',4],['Lin & me','private',0]].map(([n,v,c]) => (
                <div key={n} style={{ display:'flex', alignItems:'center', gap:10 }}>
                  <Vis v={v} size="xs"/>
                  <span style={{ flex:1, fontSize:13, color:'var(--ink)' }}>{n}</span>
                  <span className="mono" style={{ fontSize:11, color:'var(--faint)' }}>{c > 0 ? `${c} people` : 'just you'}</span>
                </div>
              ))}
            </div>
            <Hint icon={<I.Lock/>}>You control consent per scene. Collaborators can add and comment, but only you can publish or weave a public story.</Hint>
          </div>
        </div>
      </div>
    </Page>
  );
}

// ── YEAR IN REVIEW ───────────────────────────────────────────────────────────
function PageRecap({ go }) {
  const r = D2.recap;
  const months = ['J','F','M','A','M','J','J','A','S','O','N','D'];
  return (
    <Page max={1100}>
      <div className="card-r rise" style={{ overflow:'hidden', position:'relative' }}>
        <div style={{ position:'absolute', inset:0, background:'radial-gradient(70% 80% at 50% 0%, var(--accent-wash), transparent 60%)' }}/>
        <div style={{ position:'relative', padding:'34px 30px 28px', textAlign:'center' }}>
          <div className="mono" style={{ fontSize:11, letterSpacing:'0.2em', color:'var(--accent)', textTransform:'uppercase' }}>Year in Review</div>
          <h1 className="disp" style={{ fontSize:'clamp(34px,6vw,58px)', fontWeight:600, margin:'8px 0 0', letterSpacing:'-0.04em', lineHeight:0.98 }}>{r.year}, in leaves</h1>
          <p style={{ margin:'12px auto 0', color:'var(--muted)', fontSize:15, maxWidth:440, lineHeight:1.5 }}>A year of {r.captured} memories across {r.scenes} scenes. Mostly green, a little fragile, woven with {r.people} people.</p>
          <div style={{ display:'flex', justifyContent:'center', gap:6, marginTop:22, flexWrap:'wrap', maxWidth:520, marginInline:'auto' }}>
            {Array.from({length:48}).map((_,i) => <span key={i} className="floaty" style={{ animationDelay:`${(i%8)*0.3}s` }}><LeafShape color={[ '#15803d','#22c55e','#84cc16','#eab308','#a8a29e'][i%5]} size={13} vein={false}/></span>)}
          </div>
        </div>
      </div>
      <div className="lx-grid-stat-4 stagger">
        <StatTile label="Memories" value={r.captured} icon={<I.Leaf/>} accent="#15803d" i={0}/>
        <StatTile label="Words written" value={r.words} icon={<I.Pen/>} accent="#2563eb" i={1}/>
        <StatTile label="Links formed" value={r.links} icon={<I.Link/>} accent="#9333ea" i={2}/>
        <StatTile label="Longest streak" value={r.longestStreak} unit="days" icon={<I.Sun/>} accent="#d97706" i={3}/>
      </div>
      <div className="lx-cols-main">
        <div className="card-r" style={{ padding:'18px 20px', minWidth:0 }}>
          <SectionHead title="Memories by month" sub={`Busiest in ${r.topMonth}`}/>
          <Bars data={r.months} labels={months} height={120}/>
        </div>
        <div className="card-r" style={{ padding:'18px 20px', minWidth:0 }}>
          <SectionHead title="Mood through the year"/>
          <div style={{ display:'flex', alignItems:'flex-end', gap:'3%', height:120 }}>
            {r.moodByMonth.map((m,i) => <div key={i} style={{ flex:1, display:'flex', flexDirection:'column', justifyContent:'flex-end', alignItems:'center', gap:5, height:'100%' }}>
              <div className="lx-grow" style={{ width:'70%', height:`${(m/5)*100}%`, borderRadius:5, background:`linear-gradient(${(LMT.mood[Math.round(m)]||LMT.mood[3]).color}, ${wash((LMT.mood[Math.round(m)]||LMT.mood[3]).color,0.4)})`, animation:'lmtx-grow calc(.8s*var(--mo)) cubic-bezier(.2,.8,.2,1) both', animationDelay:`calc(${i}*.04s*var(--mo))` }}/>
              <span className="mono" style={{ fontSize:9, color:'var(--faint)' }}>{months[i]}</span>
            </div>)}
          </div>
        </div>
      </div>
      <div className="lx-grid-stat" style={{ display:'grid', gridTemplateColumns:'repeat(auto-fit, minmax(170px,1fr))', gap:14 }}>
        {[['Top scene',r.topScene,I.Layers],['Top place',r.topPlace,I.Pin],['Fragile, kept',`${r.fragile} memories`,I.Heart]].map(([l,v,Ic],i) => (
          <div key={l} className="card-r lift" style={{ padding:16, '--i':i }}>
            <span style={{ fontSize:18, color:'var(--accent)' }}><Ic/></span>
            <div className="mono" style={{ fontSize:10, letterSpacing:'0.08em', textTransform:'uppercase', color:'var(--faint)', marginTop:8 }}>{l}</div>
            <div className="disp" style={{ fontSize:17, fontWeight:600, marginTop:3 }}>{v}</div>
          </div>
        ))}
      </div>
      <div style={{ display:'flex', justifyContent:'center', gap:10, flexWrap:'wrap' }}>
        <button className="btn btn-pri press" style={{ padding:'12px 20px' }}><I.Branch style={{ fontSize:16 }}/>Weave the year into a story</button>
        <button className="btn btn-out press" style={{ padding:'12px 20px' }}><I.Image style={{ fontSize:16 }}/>Export as a keepsake</button>
      </div>
    </Page>
  );
}

Object.assign(window, { PageAsk, PageCollab, PageRecap });
})();
