// Pages — part 1: Today, Life Tree, Life Graph, Timeline.
(function () {
const { useState, useEffect, useRef } = React;
const { cx, wash } = LMTXUtil;
const I = window.LMTIcons;
const D = LMTData, D2 = LMTX2;

function Page({ children, max = 1240 }) {
  return <div className="lx-page" style={{ maxWidth:max, margin:'0 auto', width:'100%', display:'flex', flexDirection:'column', gap:22 }}>{children}</div>;
}
window.LMTXPage = Page;

// Framed viz "window" — keeps the luminous tree canvas, frames it for dark mode.
function VizWindow({ children, height = 360, title, right, glow }) {
  return (
    <div className="card-r" style={{ overflow:'hidden', position:'relative' }}>
      {title && <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', padding:'12px 15px', borderBottom:'1px solid var(--hair)' }}>
        <span className="disp" style={{ fontSize:14.5, fontWeight:600 }}>{title}</span>{right}
      </div>}
      <div style={{ position:'relative', height, background:'var(--tree-bg)' }}>
        {glow && <div style={{ position:'absolute', inset:0, background:'radial-gradient(60% 50% at 50% 42%, var(--accent-wash), transparent 70%)', pointerEvents:'none' }}/>}
        {children}
      </div>
    </div>
  );
}
window.LMTXVizWindow = VizWindow;

// ── TODAY ─────────────────────────────────────────────────────────────────
function PageToday({ go, onCapture }) {
  const [bucket, setBucket] = useState('all');
  const items = bucket === 'all' ? D.todayItems : D.todayItems.filter(t => t.bucket === bucket);
  const counts = D.todayItems.reduce((a,t) => (a[t.bucket]=(a[t.bucket]||0)+1, a), {});
  return (
    <Page>
      <PageHead kicker="Tuesday · June 2, 2026" icon={<I.Sun/>} title="Good morning, Prabhat"
        sub="Mostly shipping this week — two deploys and a late-night rollback, but the promo finally landed. Four things still want your attention."
        right={<>
          <button className="btn btn-out press" onClick={() => go('ask')}><I.Sparkles style={{ fontSize:15 }}/>Ask</button>
          <button className="btn btn-pri press" onClick={onCapture}><I.Plus style={{ fontSize:16 }}/>Capture</button>
        </>}/>

      {/* recency band */}
      <div className="card-r" style={{ padding:'14px 16px', display:'flex', alignItems:'center', gap:14, flexWrap:'wrap' }}>
        <span className="mono" style={{ fontSize:10.5, letterSpacing:'0.1em', textTransform:'uppercase', color:'var(--faint)' }}>This week's growth</span>
        <div style={{ flex:1, minWidth:160, display:'flex', gap:5, alignItems:'flex-end', height:38 }}>
          {[2,4,1,3,0,2,5,3].map((v,i) => <div key={i} className="lx-grow" style={{ flex:1, height:`${20+v*15}%`, background: i>=6?'var(--accent)':'var(--accent-soft)', opacity: i>=6?1:0.45+v*0.1, borderRadius:3, animation:`lmtx-grow calc(.7s*var(--mo)) cubic-bezier(.2,.8,.2,1) both`, animationDelay:`calc(${i}*.05s*var(--mo))` }}/>)}
        </div>
        <div style={{ display:'flex', gap:18 }}>
          {[['2','new leaves'],['3','links formed'],['1','fragile']].map(([n,l]) => <div key={l}><div className="disp tnum" style={{ fontSize:20, fontWeight:600 }}>{n}</div><div style={{ fontSize:11, color:'var(--faint)' }}>{l}</div></div>)}
        </div>
      </div>

      <div className="lx-cols-main">
        {/* left */}
        <div style={{ display:'flex', flexDirection:'column', gap:18, minWidth:0 }}>
          <div>
            <SectionHead title="Today" count={D.todayItems.length} sub="Surfaced by the Weaver — sorted by what moves things forward"
              right={<SegTabs size="sm" value={bucket} onChange={setBucket} tabs={[{id:'all',label:'All'},{id:'time-bound',label:'Time'},{id:'unblocker',label:'Unblocks'},{id:'quick-win',label:'Quick'}]}/>}/>
            <div className="stagger" style={{ display:'flex', flexDirection:'column', gap:11 }}>
              {items.map((t,i) => <TodayItem key={t.id} item={t} i={i} onCapture={onCapture}/>)}
            </div>
          </div>
          <div>
            <SectionHead title="Recent leaves" count={D.events.length} right={<button className="btn btn-ghost press" onClick={() => go('timeline')} style={{ fontSize:12 }}>Timeline <I.ArrowRight style={{ fontSize:13 }}/></button>}/>
            <div className="stagger" style={{ display:'flex', flexDirection:'column', gap:10 }}>
              {D.events.slice(0,5).map((e,i) => <LeafCard key={e.id} event={e} i={i} onClick={() => go('scene')}/>)}
            </div>
          </div>
        </div>

        {/* right */}
        <div style={{ display:'flex', flexDirection:'column', gap:18, minWidth:0 }}>
          <VizWindow height={290} glow title="Your tree" right={<button className="btn btn-ghost press" onClick={() => go('tree')} style={{ fontSize:12 }}>Open <I.ArrowRight style={{ fontSize:13 }}/></button>}>
            <LifeTree height={290} width={420} dense showLabels={false}/>
            <button onClick={() => go('tree')} style={{ position:'absolute', inset:0, background:'transparent', border:'none', cursor:'pointer' }}/>
          </VizWindow>

          <div className="card-r" style={{ padding:16 }}>
            <SectionHead title="The Weaver suggests" right={<span className="pill pill-accent"><I.Sparkles style={{ fontSize:11 }}/>AI</span>}/>
            <div className="stagger" style={{ display:'flex', flexDirection:'column', gap:10 }}>
              {D.suggestions.slice(0,3).map((s,i) => <Suggestion key={s.id} s={s} i={i}/>)}
            </div>
          </div>

          <div className="card-r" style={{ padding:16 }}>
            <SectionHead title="Echoes" right={<button className="btn btn-ghost press" onClick={() => go('echoes')} style={{ fontSize:12 }}>All</button>}/>
            <div className="stagger" style={{ display:'flex', flexDirection:'column', gap:2 }}>
              {D.echoes.slice(0,3).map((e,i) => (
                <button key={e.id} className="press" onClick={() => go('echoes')} style={{ display:'flex', gap:11, alignItems:'flex-start', padding:'9px 8px', borderRadius:10, background:'none', border:'none', cursor:'pointer', textAlign:'left', '--i':i }}
                  onMouseEnter={ev => ev.currentTarget.style.background='var(--sunken)'} onMouseLeave={ev => ev.currentTarget.style.background='none'}>
                  <span style={{ flex:'0 0 auto', width:30, height:30, borderRadius:9, background:'var(--accent-wash)', display:'grid', placeItems:'center', color:'var(--accent)', fontSize:15 }}><EchoIcon kind={e.kind}/></span>
                  <span style={{ flex:1, minWidth:0 }}><span style={{ display:'block', fontSize:12.5, color:'var(--ink)', lineHeight:1.4 }}>{e.text}</span><span className="mono" style={{ fontSize:10, color:'var(--faint)' }}>{e.meta}</span></span>
                </button>
              ))}
            </div>
          </div>
        </div>
      </div>
    </Page>
  );
}

function TodayItem({ item, i, onCapture }) {
  const b = LMT.buckets[item.bucket];
  const [done, setDone] = useState(false);
  return (
    <div className="card lift" style={{ display:'flex', gap:13, padding:'13px 15px', alignItems:'flex-start', '--i':i, opacity: done?0.5:1, transition:'opacity .3s' }}>
      <button onClick={() => setDone(!done)} className="press" style={{ flex:'0 0 auto', width:24, height:24, borderRadius:8, border:`1.5px solid ${done?'var(--accent)':'var(--edge-strong)'}`, background: done?'var(--accent)':'transparent', color:'var(--accent-fg)', display:'grid', placeItems:'center', cursor:'pointer', marginTop:1 }}>{done && <I.Check style={{ fontSize:15 }}/>}</button>
      <div style={{ flex:1, minWidth:0 }}>
        <div className="disp" style={{ fontSize:15, fontWeight:550, textDecoration: done?'line-through':'none', color:'var(--ink)', textWrap:'pretty' }}>{item.title}</div>
        <div style={{ fontSize:12, color:'var(--muted)', marginTop:4, lineHeight:1.45 }}>{item.why}</div>
        <div style={{ display:'flex', gap:8, marginTop:9, alignItems:'center', flexWrap:'wrap' }}>
          <span className="pill" style={{ color:b.tone, borderColor:wash(b.tone,0.3), background:wash(b.tone,0.1) }}>{b.glyph} {b.label}</span>
          <span className="mono" style={{ fontSize:11, color:'var(--faint)', display:'inline-flex', alignItems:'center', gap:4 }}><I.Clock style={{ fontSize:12 }}/>{item.dur}m · {item.when}</span>
        </div>
      </div>
    </div>
  );
}
function Suggestion({ s, i }) {
  const [acted, setActed] = useState(false);
  const kindIcon = { link:I.Link, media:I.Image, tag:I.Tag, emotion:I.Heart, person:I.Person }[s.kind] || I.Sparkles;
  const KI = kindIcon;
  return (
    <div style={{ display:'flex', gap:11, padding:'11px 12px', borderRadius:12, background:'var(--sunken)', border:'1px solid var(--hair)', '--i':i, opacity: acted?0.5:1, transition:'opacity .3s' }}>
      <span style={{ flex:'0 0 auto', width:30, height:30, borderRadius:9, background:'var(--raised)', border:'1px solid var(--hair)', display:'grid', placeItems:'center', color:'var(--accent)', fontSize:15 }}><KI/></span>
      <div style={{ flex:1, minWidth:0 }}>
        <div style={{ fontSize:12.5, color:'var(--ink)', lineHeight:1.45 }}>{s.text}</div>
        <div style={{ display:'flex', alignItems:'center', gap:8, marginTop:8 }}>
          <button className="btn btn-pri press" onClick={() => setActed(true)} style={{ fontSize:11.5, padding:'5px 11px' }}>{acted ? 'Done' : s.action}</button>
          <span className="mono" style={{ fontSize:10, color:'var(--faint)' }}>{Math.round(s.confidence*100)}% match</span>
        </div>
      </div>
    </div>
  );
}
function EchoIcon({ kind }) {
  const m = { anniversary:I.Cal, recurring:I.Undo, pattern:I.Heart, gap:I.Clock }[kind] || I.Bell;
  const M = m; return <M/>;
}
window.LMTXEchoIcon = EchoIcon;

// ── LIFE TREE ──────────────────────────────────────────────────────────────
function PageTree({ go }) {
  const [season, setSeason] = useState('all');
  const [sel, setSel] = useState(null);
  return (
    <Page max={1320}>
      <PageHead kicker="Visualization" icon={<I.Tree/>} title="Your Life Tree"
        sub="Every leaf is a memory. Colour is recency — fresh green this week, fading to stone over a year. Branches are your scenes."
        right={<SegTabs value={season} onChange={setSeason} tabs={[{id:'all',label:'All time'},{id:'year',label:'This year'},{id:'season',label:'Season'}]}/>}/>
      <div className="lx-cols-tree">
        <VizWindow height={560} glow>
          <LifeTree height={560} width={760} highlight={sel}/>
        </VizWindow>
        <div style={{ display:'flex', flexDirection:'column', gap:16, minWidth:0 }}>
          <div className="card-r" style={{ padding:16 }}>
            <SectionHead title="Canopy at a glance"/>
            <div className="lx-grid-stat" style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:10 }}>
              <Mini label="Leaves" value="312" sub="memories"/>
              <Mini label="Branches" value="8" sub="scenes"/>
              <Mini label="Fresh" value="6" sub="this week" accent/>
              <Mini label="Fragile" value="14" sub="need care" tone="#dc2626"/>
            </div>
          </div>
          <div className="card-r" style={{ padding:16 }}>
            <SectionHead title="Branches" count={D.scenes.length}/>
            <div className="stagger" style={{ display:'flex', flexDirection:'column', gap:3 }}>
              {D.scenes.map((s,i) => (
                <button key={s.id} className="press" onClick={() => go('scene')} style={{ display:'flex', alignItems:'center', gap:11, padding:'9px 10px', borderRadius:10, background:'none', border:'none', cursor:'pointer', '--i':i }}
                  onMouseEnter={e => e.currentTarget.style.background='var(--sunken)'} onMouseLeave={e => e.currentTarget.style.background='none'}>
                  <span style={{ width:11, height:11, borderRadius:4, background:s.color, flex:'0 0 auto', boxShadow:`0 0 10px ${s.color}66` }}/>
                  <span style={{ flex:1, textAlign:'left', fontSize:13.5, fontWeight:500, color:'var(--ink)' }}>{s.title}</span>
                  <div style={{ width:54 }}><div className="meter"><i style={{ width:`${Math.min(100,s.count*1.5)}%`, background:s.color }}/></div></div>
                  <span className="mono tnum" style={{ fontSize:11, color:'var(--faint)', width:22, textAlign:'right' }}>{s.count}</span>
                </button>
              ))}
            </div>
          </div>
          <Hint icon={<I.Sparkles/>}>The two newest leaves sit on <b style={{ color:'var(--ink)' }}>Lin&nbsp;&amp;&nbsp;me</b> and <b style={{ color:'var(--ink)' }}>Family</b>. Tap a branch to prune, rename, or share.</Hint>
        </div>
      </div>
    </Page>
  );
}
function Mini({ label, value, sub, accent, tone }) {
  return (
    <div className="well" style={{ padding:'12px 13px' }}>
      <div className="mono" style={{ fontSize:9.5, letterSpacing:'0.08em', textTransform:'uppercase', color:'var(--faint)' }}>{label}</div>
      <div className="disp tnum" style={{ fontSize:23, fontWeight:600, color: tone || (accent?'var(--accent)':'var(--ink)'), marginTop:3 }}>{value}</div>
      <div style={{ fontSize:11, color:'var(--faint)' }}>{sub}</div>
    </div>
  );
}
window.LMTXMini = Mini;

// ── LIFE GRAPH ──────────────────────────────────────────────────────────────
function PageGraph({ go }) {
  const [sel, setSel] = useState('e03');
  const ev = D.events.find(e => e.id === sel);
  return (
    <Page max={1320}>
      <PageHead kicker="Visualization" icon={<I.Graph/>} title="Your Life Graph"
        sub="The same memories, rewired as a network. Edges are relations the Weaver found — what causes, follows, and echoes what."
        right={<button className="btn btn-out press"><I.Filter style={{ fontSize:15 }}/>Filter relations</button>}/>
      <div className="lx-cols-tree">
        <VizWindow height={560} glow>
          <LifeGraph height={560} width={760} highlight={sel}/>
        </VizWindow>
        <div style={{ display:'flex', flexDirection:'column', gap:16, minWidth:0 }}>
          <div className="card-r" style={{ padding:16 }}>
            <SectionHead title="Focused memory"/>
            {ev && <LeafCard event={ev} surface="sunk"/>}
            <div style={{ marginTop:12, display:'flex', flexDirection:'column', gap:8 }}>
              <div className="mono" style={{ fontSize:10, letterSpacing:'0.08em', textTransform:'uppercase', color:'var(--faint)' }}>Connected through</div>
              {[['part-of','Dad\'s 70th — dinner at the lake'],['follows','Lin called from Kyoto'],['causes','Started running again']].map(([rel,t]) => {
                const c = LMT.connections[rel];
                return <div key={rel} style={{ display:'flex', alignItems:'center', gap:9, padding:'8px 10px', borderRadius:10, background:'var(--sunken)', border:'1px solid var(--hair)' }}>
                  <span className="mono" style={{ fontSize:10.5, color:c.c, background:wash(c.c,0.12), padding:'2px 7px', borderRadius:6, flex:'0 0 auto' }}>{c.arrow} {c.label}</span>
                  <span style={{ fontSize:12.5, color:'var(--ink)', flex:1, minWidth:0, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{t}</span>
                </div>;
              })}
            </div>
          </div>
          <div className="card-r" style={{ padding:16 }}>
            <SectionHead title="Jump to a memory"/>
            <div style={{ display:'flex', flexDirection:'column', gap:2 }}>
              {D.events.slice(0,6).map(e => (
                <button key={e.id} onClick={() => setSel(e.id)} className="press" style={{ display:'flex', alignItems:'center', gap:10, padding:'8px 9px', borderRadius:9, background: sel===e.id?'var(--accent-wash)':'none', border:'none', cursor:'pointer', textAlign:'left' }}>
                  <LeafShape color={LMT.leafFor(e.daysSince)} size={16}/>
                  <span style={{ flex:1, minWidth:0, fontSize:12.5, color:'var(--ink)', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{e.title}</span>
                  <span className="mono tnum" style={{ fontSize:10.5, color:'var(--faint)' }}>{e.links}</span>
                </button>
              ))}
            </div>
          </div>
        </div>
      </div>
    </Page>
  );
}

// ── TIMELINE ────────────────────────────────────────────────────────────────
function PageTimeline({ go }) {
  const groups = [
    { label:'This week', items: D.events.filter(e => e.daysSince < 7) },
    { label:'Earlier this month', items: D.events.filter(e => e.daysSince >= 7 && e.daysSince < 30) },
    { label:'This season', items: D.events.filter(e => e.daysSince >= 30 && e.daysSince < 90) },
    { label:'Older', items: D.events.filter(e => e.daysSince >= 90) },
  ].filter(g => g.items.length);
  return (
    <Page max={920}>
      <PageHead kicker="Chronological" icon={<I.Cal/>} title="Timeline"
        sub="Your memories laid end to end. The spine fades from fresh green to stone as you scroll back through the year."
        right={<SegTabs value="all" onChange={()=>{}} tabs={[{id:'all',label:'All'},{id:'fragile',label:'Fragile'},{id:'media',label:'With media'}]}/>}/>
      <div style={{ position:'relative' }}>
        <div style={{ position:'absolute', left:'calc(7px)', top:6, bottom:6, width:2, background:'linear-gradient(var(--accent), var(--accent-soft) 30%, var(--edge) 100%)', borderRadius:2 }}/>
        <div style={{ display:'flex', flexDirection:'column', gap:26 }}>
          {groups.map((g,gi) => (
            <div key={g.label}>
              <div style={{ display:'flex', alignItems:'center', gap:12, marginBottom:14, paddingLeft:30 }}>
                <h2 className="disp" style={{ fontSize:15, fontWeight:600, margin:0 }}>{g.label}</h2>
                <span className="mono tnum" style={{ fontSize:11, color:'var(--faint)' }}>{g.items.length}</span>
                <div style={{ flex:1, height:1, background:'var(--hair)' }}/>
              </div>
              <div className="stagger" style={{ display:'flex', flexDirection:'column', gap:12 }}>
                {g.items.map((e,i) => (
                  <div key={e.id} style={{ display:'flex', gap:18, alignItems:'flex-start', '--i':i }}>
                    <div style={{ flex:'0 0 auto', position:'relative', width:16, display:'flex', justifyContent:'center', paddingTop:16 }}>
                      <span style={{ width:16, height:16, borderRadius:'50%', background:'var(--bg)', border:`3px solid ${LMT.leafFor(e.daysSince)}`, boxShadow:`0 0 0 3px var(--bg), 0 0 12px ${LMT.leafFor(e.daysSince)}66`, zIndex:1 }}/>
                    </div>
                    <div style={{ flex:1, minWidth:0 }}><LeafCard event={e} onClick={() => go('scene')}/></div>
                  </div>
                ))}
              </div>
            </div>
          ))}
        </div>
      </div>
    </Page>
  );
}

Object.assign(window, { PageToday, PageTree, PageGraph, PageTimeline });
})();
