// Pages — part 2: Scenes (index+detail), People (index+detail), Places (index+detail).
(function () {
const { useState } = React;
const { cx, wash } = LMTXUtil;
const I = window.LMTIcons;
const D = LMTData, D2 = LMTX2;
const Page = window.LMTXPage, Mini = window.LMTXMini, VizWindow = window.LMTXVizWindow;

// ── SCENES INDEX ────────────────────────────────────────────────────────────
function PageScenes({ go }) {
  const [view, setView] = useState('grid');
  return (
    <Page>
      <PageHead kicker="Library" icon={<I.Layers/>} title="Scenes"
        sub="Scenes are how memories gather — by relationship, project, or theme. Each carries its own privacy and the people you share it with."
        right={<>
          <SegTabs value={view} onChange={setView} tabs={[{id:'grid',label:'Grid',icon:<I.Grid style={{fontSize:14}}/>},{id:'list',label:'List'}]}/>
          <button className="btn btn-pri press"><I.Plus style={{ fontSize:16 }}/>New scene</button>
        </>}/>
      <div className={view === 'grid' ? 'lx-grid-cards stagger' : 'stagger'} style={view==='list'?{ display:'flex', flexDirection:'column', gap:10 }:undefined}>
        {D.scenes.map((s,i) => view === 'grid'
          ? <SceneCard key={s.id} s={s} i={i} onClick={() => go('scene')}/>
          : <SceneRow key={s.id} s={s} i={i} onClick={() => go('scene')}/>)}
      </div>
    </Page>
  );
}
function SceneCard({ s, i, onClick }) {
  const sceneEvents = D.events.filter(e => e.scene === s.title).slice(0,3);
  return (
    <button onClick={onClick} className="card-r lift press" style={{ padding:0, overflow:'hidden', cursor:'pointer', textAlign:'left', '--i':i, border:'1px solid var(--edge)' }}>
      <div style={{ height:78, position:'relative', background:`linear-gradient(135deg, ${wash(s.color,0.22)}, ${wash(s.color,0.05)})`, borderBottom:`1px solid var(--hair)`, overflow:'hidden' }}>
        <div style={{ position:'absolute', inset:0, backgroundImage:`radial-gradient(circle at 1px 1px, ${wash(s.color,0.18)} 1px, transparent 0)`, backgroundSize:'14px 14px' }}/>
        {sceneEvents.map((e,j) => <span key={e.id} className="floaty" style={{ position:'absolute', top:14+j*12, left:`${22+j*26}%`, animationDelay:`${j*0.7}s` }}><LeafShape color={LMT.leafFor(e.daysSince)} size={20+j*4}/></span>)}
        <span style={{ position:'absolute', top:12, right:12 }}><Vis v={s.privacy} size="xs"/></span>
      </div>
      <div style={{ padding:'13px 15px' }}>
        <div style={{ display:'flex', alignItems:'center', gap:9 }}>
          <span style={{ width:11, height:11, borderRadius:4, background:s.color, flex:'0 0 auto', boxShadow:`0 0 10px ${s.color}66` }}/>
          <span className="disp" style={{ fontSize:16, fontWeight:600, flex:1, minWidth:0, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{s.title}</span>
        </div>
        <div style={{ display:'flex', alignItems:'center', gap:10, marginTop:10, color:'var(--faint)', fontSize:11.5 }}>
          <span className="mono"><I.Leaf style={{ fontSize:12, verticalAlign:-2 }}/> {s.count}</span>
          {s.collaborators > 0 ? <span style={{ display:'inline-flex', alignItems:'center', gap:-3 }}>{Array.from({length:Math.min(s.collaborators,3)}).map((_,k) => <span key={k} style={{ marginLeft:k?-6:0 }}><Avatar name={['Vera','Lin','Anna'][k]} color={['#d97706','#15803d','#9333ea'][k]} size={18} ring/></span>)}</span> : <span className="mono">solo</span>}
        </div>
      </div>
    </button>
  );
}
function SceneRow({ s, i, onClick }) {
  return (
    <button onClick={onClick} className="card lift press" style={{ display:'flex', alignItems:'center', gap:14, padding:'13px 16px', cursor:'pointer', textAlign:'left', '--i':i, width:'100%' }}>
      <span style={{ width:38, height:38, borderRadius:11, background:`linear-gradient(135deg, ${wash(s.color,0.3)}, ${wash(s.color,0.08)})`, display:'grid', placeItems:'center', flex:'0 0 auto' }}><span style={{ width:11, height:11, borderRadius:4, background:s.color }}/></span>
      <div style={{ flex:1, minWidth:0 }}>
        <div className="disp" style={{ fontSize:15.5, fontWeight:600 }}>{s.title}</div>
        <div className="mono" style={{ fontSize:11, color:'var(--faint)', marginTop:2 }}>{s.count} memories · {s.collaborators > 0 ? `${s.collaborators} sharing` : 'private'}</div>
      </div>
      <Vis v={s.privacy} size="xs"/>
      <I.ChevronRight style={{ fontSize:17, color:'var(--ghost)' }}/>
    </button>
  );
}

// ── SCENE DETAIL ────────────────────────────────────────────────────────────
function PageScene({ go }) {
  const s = D.scenes[0]; // Family
  const events = D.events.filter(e => e.scene === 'Family').concat(D.events.slice(0,4));
  return (
    <Page max={1240}>
      <button className="btn btn-ghost press" onClick={() => go('scenes')} style={{ alignSelf:'flex-start', padding:'5px 10px', fontSize:12.5 }}><I.ArrowLeft style={{ fontSize:15 }}/>All scenes</button>
      {/* hero */}
      <div className="card-r" style={{ overflow:'hidden' }}>
        <div style={{ height:130, position:'relative', background:`linear-gradient(120deg, ${wash(s.color,0.28)}, ${wash(s.color,0.06)})`, borderBottom:'1px solid var(--hair)' }}>
          <div style={{ position:'absolute', inset:0, backgroundImage:`radial-gradient(circle at 1px 1px, ${wash(s.color,0.16)} 1px, transparent 0)`, backgroundSize:'16px 16px' }}/>
          {[0,1,2,3,4].map(j => <span key={j} className="floaty" style={{ position:'absolute', top:18+ (j%2)*30, left:`${12+j*17}%`, animationDelay:`${j*0.6}s` }}><LeafShape color={LMT.leafFor(D.events[j].daysSince)} size={22+ (j%3)*8}/></span>)}
        </div>
        <div style={{ padding:'18px 22px', display:'flex', alignItems:'flex-start', gap:16, flexWrap:'wrap' }}>
          <div style={{ flex:1, minWidth:240 }}>
            <div style={{ display:'flex', alignItems:'center', gap:10 }}>
              <span style={{ width:13, height:13, borderRadius:4, background:s.color, boxShadow:`0 0 12px ${s.color}88` }}/>
              <h1 className="disp" style={{ fontSize:28, fontWeight:600, margin:0, letterSpacing:'-0.03em' }}>{s.title}</h1>
              <Vis v={s.privacy}/>
            </div>
            <p style={{ margin:'10px 0 0', color:'var(--muted)', fontSize:14, maxWidth:520, lineHeight:1.5 }}>The people I came from and keep choosing. Birthdays, hospitals, the lake. Shared with three.</p>
            <div style={{ display:'flex', gap:18, marginTop:14, flexWrap:'wrap' }}>
              {[['47','memories'],['3','sharing'],['41d','since last'],['6','links']].map(([n,l]) => <div key={l}><div className="disp tnum" style={{ fontSize:19, fontWeight:600 }}>{n}</div><div style={{ fontSize:11, color:'var(--faint)' }}>{l}</div></div>)}
            </div>
          </div>
          <div style={{ display:'flex', gap:9, alignItems:'center' }}>
            <div style={{ display:'flex' }}>{['Vera','Marcus','Lin'].map((n,k) => <span key={n} style={{ marginLeft:k?-9:0 }}><Avatar name={n} color={['#d97706','#2563eb','#15803d'][k]} size={32} ring here={k<2}/></span>)}</div>
            <button className="btn btn-out press"><I.People style={{ fontSize:15 }}/>Share</button>
            <button className="btn btn-pri press"><I.Plus style={{ fontSize:16 }}/>Add</button>
          </div>
        </div>
      </div>
      <div className="lx-cols-main">
        <div style={{ minWidth:0 }}>
          <SectionHead title="Memories" count={events.length} right={<SegTabs size="sm" value="recent" onChange={()=>{}} tabs={[{id:'recent',label:'Recent'},{id:'mood',label:'By mood'}]}/>}/>
          <div className="stagger" style={{ display:'flex', flexDirection:'column', gap:11 }}>
            {events.slice(0,7).map((e,i) => <LeafCard key={e.id+i} event={e} i={i}/>)}
          </div>
        </div>
        <div style={{ display:'flex', flexDirection:'column', gap:16, minWidth:0 }}>
          <VizWindow height={220} glow title="This scene's cluster"><LifeGraph height={220} width={360} dense showLabels={false}/></VizWindow>
          <div className="card-r" style={{ padding:16 }}>
            <SectionHead title="People here"/>
            <div style={{ display:'flex', flexDirection:'column', gap:3 }}>
              {D2.people.slice(0,4).map(p => <PersonRow key={p.id} p={p} onClick={() => go('person')} compact/>)}
            </div>
          </div>
          <Hint><b style={{ color:'var(--ink)' }}>Weaver:</b> "Mom's biopsy" and "Dad's 70th" are 41 days apart in this scene — want to weave them into one thread?</Hint>
        </div>
      </div>
    </Page>
  );
}

// ── PEOPLE INDEX ────────────────────────────────────────────────────────────
function PagePeople({ go }) {
  return (
    <Page>
      <PageHead kicker="Library" icon={<I.People/>} title="People"
        sub="Everyone woven through your memories. The Weaver promotes recurring names into people you can follow across scenes."
        right={<button className="btn btn-pri press"><I.Plus style={{ fontSize:16 }}/>Add person</button>}/>
      <div className="lx-grid-cards stagger">
        {D2.people.map((p,i) => <PersonCard key={p.id} p={p} i={i} onClick={() => go('person')}/>)}
      </div>
    </Page>
  );
}
function PersonCard({ p, i, onClick }) {
  return (
    <button onClick={onClick} className="card-r lift press" style={{ padding:16, cursor:'pointer', textAlign:'left', '--i':i, display:'flex', flexDirection:'column', gap:12, position:'relative' }}>
      {p.pending && <span className="pill pill-accent" style={{ position:'absolute', top:12, right:12, fontSize:10 }}>pending</span>}
      <div style={{ display:'flex', alignItems:'center', gap:12 }}>
        <Avatar name={p.name} color={p.color} size={46} glow here={p.here}/>
        <div style={{ minWidth:0 }}>
          <div className="disp" style={{ fontSize:16.5, fontWeight:600 }}>{p.name}</div>
          <div className="mono" style={{ fontSize:11, color:'var(--faint)', textTransform:'uppercase', letterSpacing:'0.06em' }}>{p.rel}</div>
        </div>
      </div>
      <p style={{ margin:0, fontSize:12.5, color:'var(--muted)', lineHeight:1.5, minHeight:36 }}>{p.blurb}</p>
      <div style={{ display:'flex', alignItems:'center', gap:14, paddingTop:11, borderTop:'1px solid var(--hair)', fontSize:11.5, color:'var(--faint)' }}>
        <span className="mono"><I.Leaf style={{ fontSize:12, verticalAlign:-2 }}/> {p.events}</span>
        <span className="mono"><I.Layers style={{ fontSize:12, verticalAlign:-2 }}/> {p.scenes.length}</span>
        <span style={{ marginLeft:'auto' }}>last · {p.lastSeen}</span>
      </div>
    </button>
  );
}
function PersonRow({ p, onClick, compact }) {
  return (
    <button onClick={onClick} className="press" style={{ display:'flex', alignItems:'center', gap:11, padding:'8px 9px', borderRadius:11, background:'none', border:'none', cursor:'pointer', textAlign:'left', width:'100%' }}
      onMouseEnter={e => e.currentTarget.style.background='var(--sunken)'} onMouseLeave={e => e.currentTarget.style.background='none'}>
      <Avatar name={p.name} color={p.color} size={compact?32:38} here={p.here}/>
      <div style={{ flex:1, minWidth:0 }}>
        <div style={{ fontSize:13.5, fontWeight:600, color:'var(--ink)' }}>{p.name}</div>
        <div className="mono" style={{ fontSize:10.5, color:'var(--faint)' }}>{p.rel} · {p.events} memories</div>
      </div>
      <I.ChevronRight style={{ fontSize:16, color:'var(--ghost)' }}/>
    </button>
  );
}
window.LMTXPersonRow = PersonRow;

// ── PERSON DETAIL ───────────────────────────────────────────────────────────
function PagePerson({ go }) {
  const p = D2.people[0]; // Lin
  const events = D.events.filter(e => e.people.some(x => x.includes('Lin'))).concat(D.events.slice(2,6));
  return (
    <Page max={1180}>
      <button className="btn btn-ghost press" onClick={() => go('people')} style={{ alignSelf:'flex-start', padding:'5px 10px', fontSize:12.5 }}><I.ArrowLeft style={{ fontSize:15 }}/>All people</button>
      <div className="card-r" style={{ padding:'24px', display:'flex', gap:20, alignItems:'flex-start', flexWrap:'wrap' }}>
        <Avatar name={p.name} color={p.color} size={84} glow here={p.here}/>
        <div style={{ flex:1, minWidth:240 }}>
          <h1 className="disp" style={{ fontSize:30, fontWeight:600, margin:0, letterSpacing:'-0.03em' }}>{p.name}</h1>
          <div className="mono" style={{ fontSize:12, color:'var(--faint)', textTransform:'uppercase', letterSpacing:'0.06em', marginTop:5 }}>{p.rel} {p.here && '· here now'}</div>
          <p style={{ margin:'12px 0 0', color:'var(--muted)', fontSize:14, maxWidth:480, lineHeight:1.55 }}>{p.blurb}</p>
          <div style={{ display:'flex', gap:8, marginTop:16, flexWrap:'wrap' }}>
            {p.scenes.map(sc => { const sd = D.scenes.find(x => x.title === sc); return <span key={sc} className="pill" style={{ color: sd?.color }}><span style={{ width:7, height:7, borderRadius:2, background:sd?.color }}/>{sc}</span>; })}
          </div>
        </div>
        <div style={{ display:'flex', flexDirection:'column', gap:9, alignItems:'flex-end' }}>
          <div style={{ display:'flex', gap:8 }}>
            <button className="btn btn-out press"><I.Sparkles style={{ fontSize:15 }}/>Ask about {p.name.split(' ')[0]}</button>
            <button className="btn btn-pri press"><I.Plus style={{ fontSize:16 }}/>Add memory</button>
          </div>
          <div style={{ display:'flex', gap:16 }}>
            {[[p.events,'memories'],[p.scenes.length,'scenes'],[p.shared,'shared']].map(([n,l]) => <div key={l} style={{ textAlign:'right' }}><div className="disp tnum" style={{ fontSize:18, fontWeight:600 }}>{n}</div><div style={{ fontSize:10.5, color:'var(--faint)' }}>{l}</div></div>)}
          </div>
        </div>
      </div>
      <div className="lx-cols-main">
        <div style={{ minWidth:0 }}>
          <SectionHead title={`Memories with ${p.name.split(' ')[0]}`} count={events.length}/>
          <div className="stagger" style={{ display:'flex', flexDirection:'column', gap:11 }}>
            {events.slice(0,6).map((e,i) => <LeafCard key={e.id+i} event={e} i={i}/>)}
          </div>
        </div>
        <div style={{ display:'flex', flexDirection:'column', gap:16, minWidth:0 }}>
          <div className="card-r" style={{ padding:16 }}>
            <SectionHead title="Tone over time"/>
            <Bars data={[3,4,2,4,5,3,4,5]} height={64} labels={['','','','','','','','']} color={p.color}/>
            <div style={{ fontSize:12, color:'var(--muted)', marginTop:10, lineHeight:1.5 }}>Mostly warm, with one dip 18 days ago. Trending up since the Kyoto calls began.</div>
          </div>
          <div className="card-r" style={{ padding:16 }}>
            <SectionHead title="Shared scenes"/>
            <div style={{ display:'flex', flexDirection:'column', gap:3 }}>
              {p.scenes.map(sc => { const sd = D.scenes.find(x => x.title === sc) || D.scenes[0]; return (
                <button key={sc} onClick={() => go('scene')} className="press" style={{ display:'flex', alignItems:'center', gap:10, padding:'9px 10px', borderRadius:10, background:'none', border:'none', cursor:'pointer', textAlign:'left' }} onMouseEnter={e=>e.currentTarget.style.background='var(--sunken)'} onMouseLeave={e=>e.currentTarget.style.background='none'}>
                  <span style={{ width:10, height:10, borderRadius:3, background:sd.color }}/><span style={{ flex:1, fontSize:13.5, color:'var(--ink)' }}>{sc}</span><I.ChevronRight style={{ fontSize:15, color:'var(--ghost)' }}/>
                </button>); })}
            </div>
          </div>
        </div>
      </div>
    </Page>
  );
}

// ── PLACES INDEX ────────────────────────────────────────────────────────────
function PagePlaces({ go }) {
  return (
    <Page>
      <PageHead kicker="Library" icon={<I.Pin/>} title="Places"
        sub="Where your memories happened. Recurring spots get promoted to places you can revisit and map."
        right={<button className="btn btn-pri press"><I.Plus style={{ fontSize:16 }}/>Add place</button>}/>
      {/* map strip */}
      <div className="card-r" style={{ height:170, position:'relative', overflow:'hidden', background:'linear-gradient(160deg, var(--sunken), var(--bg2))' }}>
        <div style={{ position:'absolute', inset:0, backgroundImage:'radial-gradient(circle at 1px 1px, var(--edge) 1px, transparent 0)', backgroundSize:'22px 22px', opacity:0.6 }}/>
        <svg width="100%" height="100%" style={{ position:'absolute', inset:0 }}><path d="M0 120 Q 200 60 400 110 T 900 80" stroke="var(--accent-line)" strokeWidth="2" fill="none" strokeDasharray="3 6"/></svg>
        {D2.places.map((pl,i) => <button key={pl.id} onClick={() => go('place')} className="press" style={{ position:'absolute', left:`${12+i*15}%`, top:`${30+(i%3)*22}%`, display:'flex', flexDirection:'column', alignItems:'center', gap:3, background:'none', border:'none', cursor:'pointer', color:pl.color }}>
          <span className="floaty" style={{ animationDelay:`${i*0.4}s`, filter:`drop-shadow(0 4px 6px ${pl.color}66)` }}><I.Pin style={{ fontSize:26 }}/></span>
          <span style={{ fontSize:9.5, fontWeight:600, color:'var(--ink)', background:'var(--glass)', padding:'1px 6px', borderRadius:6, whiteSpace:'nowrap', backdropFilter:'blur(6px)' }}>{pl.name.split(' · ')[0]}</span>
        </button>)}
      </div>
      <div className="lx-grid-cards stagger">
        {D2.places.map((pl,i) => <PlaceCard key={pl.id} pl={pl} i={i} onClick={() => go('place')}/>)}
      </div>
    </Page>
  );
}
function PlaceCard({ pl, i, onClick }) {
  return (
    <button onClick={onClick} className="card-r lift press" style={{ padding:0, overflow:'hidden', cursor:'pointer', textAlign:'left', '--i':i }}>
      <div style={{ height:64, position:'relative', background:`linear-gradient(135deg, ${wash(pl.color,0.24)}, ${wash(pl.color,0.05)})`, display:'flex', alignItems:'center', justifyContent:'center' }}>
        <I.Pin style={{ fontSize:30, color:pl.color, filter:`drop-shadow(0 4px 8px ${pl.color}55)` }}/>
        {pl.promote && <span className="pill pill-accent" style={{ position:'absolute', top:10, right:10, fontSize:10 }}>promote?</span>}
      </div>
      <div style={{ padding:'13px 15px' }}>
        <div className="disp" style={{ fontSize:15.5, fontWeight:600 }}>{pl.name}</div>
        <div className="mono" style={{ fontSize:11, color:'var(--faint)', marginTop:2 }}>{pl.region}</div>
        <p style={{ margin:'9px 0 0', fontSize:12, color:'var(--muted)', lineHeight:1.45, minHeight:34 }}>{pl.note}</p>
        <div style={{ display:'flex', alignItems:'center', gap:12, marginTop:10, paddingTop:10, borderTop:'1px solid var(--hair)', fontSize:11.5, color:'var(--faint)' }}>
          <span className="mono"><I.Leaf style={{ fontSize:12, verticalAlign:-2 }}/> {pl.events}</span><span style={{ marginLeft:'auto' }}>last · {pl.last}</span>
        </div>
      </div>
    </button>
  );
}

// ── PLACE DETAIL ────────────────────────────────────────────────────────────
function PagePlace({ go }) {
  const pl = D2.places[1]; // Buena Vista Park
  const events = D.events.slice(0,5);
  return (
    <Page max={1180}>
      <button className="btn btn-ghost press" onClick={() => go('places')} style={{ alignSelf:'flex-start', padding:'5px 10px', fontSize:12.5 }}><I.ArrowLeft style={{ fontSize:15 }}/>All places</button>
      <div className="card-r" style={{ overflow:'hidden' }}>
        <div style={{ height:150, position:'relative', background:`linear-gradient(135deg, ${wash(pl.color,0.3)}, ${wash(pl.color,0.06)})` }}>
          <div style={{ position:'absolute', inset:0, backgroundImage:'radial-gradient(circle at 1px 1px, var(--edge) 1px, transparent 0)', backgroundSize:'20px 20px', opacity:0.5 }}/>
          <span className="floaty" style={{ position:'absolute', left:'50%', top:'40%', transform:'translate(-50%,-50%)' }}><I.Pin style={{ fontSize:54, color:pl.color, filter:`drop-shadow(0 8px 14px ${pl.color}66)` }}/></span>
        </div>
        <div style={{ padding:'18px 22px', display:'flex', gap:16, alignItems:'flex-start', flexWrap:'wrap' }}>
          <div style={{ flex:1, minWidth:240 }}>
            <h1 className="disp" style={{ fontSize:27, fontWeight:600, margin:0, letterSpacing:'-0.03em' }}>{pl.name}</h1>
            <div className="mono" style={{ fontSize:12, color:'var(--faint)', marginTop:5 }}>{pl.region} · {pl.events} memories</div>
            <p style={{ margin:'11px 0 0', color:'var(--muted)', fontSize:14, maxWidth:480, lineHeight:1.5 }}>{pl.note}</p>
          </div>
          <button className="btn btn-pri press"><I.Plus style={{ fontSize:16 }}/>Add memory here</button>
        </div>
      </div>
      <SectionHead title="Memories here" count={events.length}/>
      <div className="lx-grid-cards stagger">
        {events.map((e,i) => <LeafCard key={e.id} event={e} i={i} surface="card"/>)}
      </div>
    </Page>
  );
}

Object.assign(window, { PageScenes, PageScene, PagePeople, PagePerson, PagePlaces, PagePlace });
})();
