// Life Memory Tree — app chrome (redesigned).
// Nav model + three sidebar styles (rail / rich / minimal), top bar, mobile tab
// bar + drawer, and a ⌘K command palette. All theme-aware and animated.

(function () {
const { useState, useEffect, useRef } = React;
const { cx } = LMTXUtil;
const I = window.LMTIcons;

// ── Navigation model ────────────────────────────────────────────────────────
const NAV = [
  { group:'Cultivate', items:[
    { id:'today',    label:'Today',    icon:I.Sun },
    { id:'tree',     label:'Life Tree',icon:I.Tree },
    { id:'graph',    label:'Life Graph',icon:I.Graph },
    { id:'timeline', label:'Timeline', icon:I.Cal },
  ]},
  { group:'Library', items:[
    { id:'scenes',   label:'Scenes',   icon:I.Layers },
    { id:'people',   label:'People',   icon:I.People },
    { id:'places',   label:'Places',   icon:I.Pin },
  ]},
  { group:'Create', items:[
    { id:'weaver',   label:'Story Weaver', icon:I.Branch },
    { id:'ask',      label:'Ask',      icon:I.Sparkles },
  ]},
  { group:'Together', items:[
    { id:'collab',   label:'Collaborate', icon:I.Compass },
    { id:'recap',    label:'Year in Review', icon:I.TreeFull },
  ]},
];
const NAV_FLAT = NAV.flatMap(g => g.items);
const TITLES = Object.fromEntries(NAV_FLAT.map(n => [n.id, n.label]).concat([['echoes','Echoes'],['settings','Settings'],['scene','Scene'],['person','Person'],['place','Place'],['capture','Capture']]));
const MOBILE_TABS = ['today','tree','scenes','ask'];

// ── Brand mark ───────────────────────────────────────────────────────────────
function Brand({ collapsed = false, onClick }) {
  return (
    <button onClick={onClick} className="press" style={{ display:'flex', alignItems:'center', gap:10, background:'none', border:'none', cursor:'pointer', padding:0, color:'var(--ink)' }}>
      <span style={{ position:'relative', width:34, height:34, flex:'0 0 auto', display:'grid', placeItems:'center', borderRadius:11, background:'linear-gradient(150deg, var(--accent), color-mix(in oklab, var(--accent) 60%, #000))', boxShadow:'0 4px 14px -4px var(--accent)' }}>
        <I.Tree style={{ fontSize:20, color:'var(--accent-fg)' }}/>
        <span className="floaty" style={{ position:'absolute', top:-3, right:-3, width:9, height:9 }}><LeafShape color="#84cc16" size={9} vein={false}/></span>
      </span>
      {!collapsed && <span style={{ textAlign:'left', lineHeight:1.05 }}>
        <span className="disp" style={{ display:'block', fontSize:15.5, fontWeight:650, letterSpacing:'-0.02em' }}>Life Memory Tree</span>
        <span className="mono" style={{ display:'block', fontSize:9.5, color:'var(--faint)', letterSpacing:'0.12em', marginTop:1 }}>THE COLLABORATIVE WEAVER</span>
      </span>}
    </button>
  );
}

// ── Nav item ─────────────────────────────────────────────────────────────────
function NavItem({ item, active, collapsed, onClick, badge }) {
  const Icon = item.icon;
  return (
    <button className="nav-item" data-active={active} onClick={onClick} title={collapsed ? item.label : undefined}
      style={{ justifyContent: collapsed ? 'center' : 'flex-start', padding: collapsed ? '11px' : undefined }}>
      <span className="ni-ic"><Icon/></span>
      {!collapsed && <span style={{ flex:1, minWidth:0, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{item.label}</span>}
      {!collapsed && badge != null && <span className="mono tnum" style={{ fontSize:10.5, fontWeight:700, color: active ? 'var(--accent)' : 'var(--faint)', background: active ? 'var(--accent-wash)' : 'var(--sunken)', padding:'1px 7px', borderRadius:999 }}>{badge}</span>}
      {collapsed && badge != null && <span style={{ position:'absolute', top:6, right:8, width:6, height:6, borderRadius:'50%', background:'var(--accent)' }}/>}
    </button>
  );
}

function CaptureBtn({ collapsed, onClick }) {
  return (
    <button className="btn btn-pri press" onClick={onClick} style={{ width:'100%', padding: collapsed ? '11px' : '11px 14px', justifyContent:'center', fontSize:13.5 }}>
      <I.Plus style={{ fontSize:17 }}/>{!collapsed && 'Capture a memory'}
    </button>
  );
}

// ── Sidebar (variant-aware) ──────────────────────────────────────────────────
function Sidebar({ variant = 'rich', route, go, onCapture, onCmd, accentName, echoCount = 3 }) {
  const [hover, setHover] = useState(false);
  const collapsed = variant === 'rail' && !hover;
  const W = collapsed ? 74 : (variant === 'minimal' ? 232 : 268);

  const badgeFor = (id) => {
    if (id === 'today') return LMTData.todayItems.length;
    if (id === 'collab') return LMTX2.collaborators.filter(c => c.here).length;
    return null;
  };

  return (
    <aside onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{ width:W, flex:`0 0 ${W}px`, height:'100%', display:'flex', flexDirection:'column',
        borderRight:'1px solid var(--hair)', background: variant === 'minimal' ? 'transparent' : 'var(--bg2)',
        position: collapsed ? 'relative' : 'relative', zIndex: hover ? 40 : 1,
        boxShadow: (variant === 'rail' && hover) ? 'var(--shadow-float)' : 'none',
        transition:'width .28s cubic-bezier(.2,.8,.2,1), box-shadow .28s ease', overflow:'hidden' }}>

      {/* header */}
      <div style={{ padding: collapsed ? '18px 0 14px' : '18px 18px 14px', display:'flex', justifyContent: collapsed ? 'center' : 'flex-start' }}>
        <Brand collapsed={collapsed} onClick={() => go('today')} />
      </div>

      {/* search (rich only) */}
      {variant === 'rich' && !collapsed && (
        <div style={{ padding:'0 16px 12px' }}>
          <button onClick={onCmd} className="press" style={{ width:'100%', display:'flex', alignItems:'center', gap:9, padding:'9px 12px', borderRadius:11, background:'var(--sunken)', border:'1px solid var(--hair)', color:'var(--faint)', cursor:'pointer', fontSize:13, fontFamily:'inherit' }}>
            <I.Search style={{ fontSize:15 }}/><span style={{ flex:1, textAlign:'left' }}>Search memories…</span>
            <span className="mono" style={{ fontSize:10, padding:'2px 6px', borderRadius:6, background:'var(--raised)', border:'1px solid var(--edge)' }}>⌘K</span>
          </button>
        </div>
      )}

      {/* capture */}
      <div style={{ padding: collapsed ? '0 12px 10px' : '0 16px 12px' }}>
        <CaptureBtn collapsed={collapsed} onClick={onCapture} />
      </div>

      {/* nav */}
      <nav className="scroll" style={{ flex:1, overflowY:'auto', padding: collapsed ? '4px 12px' : '4px 12px 12px', display:'flex', flexDirection:'column', gap: variant === 'minimal' ? 3 : 2 }}>
        {NAV.map((grp, gi) => {
          const showLabel = !collapsed && variant !== 'minimal';
          return (
            <div key={grp.group} style={{ marginTop: gi === 0 ? 2 : 12 }}>
              {showLabel && <div className="mono" style={{ fontSize:9.5, letterSpacing:'0.12em', textTransform:'uppercase', color:'var(--ghost)', padding:'4px 10px 7px' }}>{grp.group}</div>}
              {collapsed && gi > 0 && <div style={{ height:1, background:'var(--hair)', margin:'8px 8px' }}/>}
              {variant === 'minimal' && gi > 0 && <div style={{ height:1, background:'var(--hair)', margin:'8px 8px 9px' }}/>}
              <div style={{ display:'flex', flexDirection:'column', gap:2 }}>
                {grp.items.map(it => <NavItem key={it.id} item={it} active={route === it.id} collapsed={collapsed} onClick={() => go(it.id)} badge={badgeFor(it.id)} />)}
              </div>
            </div>
          );
        })}

        {/* scene quick-list (rich, expanded) */}
        {variant === 'rich' && !collapsed && (
          <div style={{ marginTop:14 }}>
            <div className="mono" style={{ fontSize:9.5, letterSpacing:'0.12em', textTransform:'uppercase', color:'var(--ghost)', padding:'4px 10px 7px', display:'flex', justifyContent:'space-between' }}><span>Pinned scenes</span></div>
            <div style={{ display:'flex', flexDirection:'column', gap:1 }}>
              {LMTData.scenes.slice(0,4).map(s => (
                <button key={s.id} className="nav-item" onClick={() => go('scene')} style={{ padding:'7px 11px', fontSize:13 }}>
                  <span style={{ width:9, height:9, borderRadius:3, background:s.color, flex:'0 0 auto', boxShadow:`0 0 8px ${s.color}66` }}/>
                  <span style={{ flex:1, minWidth:0, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{s.title}</span>
                  <span className="mono tnum" style={{ fontSize:10.5, color:'var(--faint)' }}>{s.count}</span>
                </button>
              ))}
            </div>
          </div>
        )}
      </nav>

      {/* footer: secondary + account */}
      <div style={{ borderTop:'1px solid var(--hair)', padding: collapsed ? '10px 12px' : '10px 12px', display:'flex', flexDirection:'column', gap:2 }}>
        <NavItem item={{ id:'echoes', label:'Echoes', icon:I.Bell }} active={route === 'echoes'} collapsed={collapsed} onClick={() => go('echoes')} badge={echoCount} />
        <NavItem item={{ id:'settings', label:'Settings', icon:I.Settings }} active={route === 'settings'} collapsed={collapsed} onClick={() => go('settings')} />
        {!collapsed ? (
          <button className="nav-item press" onClick={() => go('settings')} style={{ marginTop:6, padding:'8px 9px' }}>
            <Avatar name="Prabhat" color="var(--accent)" size={30} here />
            <span style={{ flex:1, minWidth:0, textAlign:'left' }}>
              <span style={{ display:'block', fontSize:13, fontWeight:600, color:'var(--ink)', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>Prabhat</span>
              <span style={{ display:'block', fontSize:10.5, color:'var(--faint)' }}>Software Engineer · 7.7 yrs</span>
            </span>
            <I.ChevronRight style={{ fontSize:15, color:'var(--faint)' }}/>
          </button>
        ) : (
          <div style={{ display:'grid', placeItems:'center', paddingTop:6 }}><Avatar name="Prabhat" color="var(--accent)" size={30} here /></div>
        )}
      </div>
    </aside>
  );
}

// ── Top bar ──────────────────────────────────────────────────────────────────
function TopBar({ route, go, onCmd, dark, setDark, onCapture, compact = false, onMenu }) {
  const here = LMTX2.collaborators.filter(c => c.here);
  return (
    <header style={{ height:60, flex:'0 0 60px', display:'flex', alignItems:'center', gap:12, padding:'0 clamp(14px, 2.4vw, 26px)',
      borderBottom:'1px solid var(--hair)', background:'var(--glass)', backdropFilter:'blur(14px)', WebkitBackdropFilter:'blur(14px)', position:'relative', zIndex:20 }}>
      {compact && <button className="icon-btn" onClick={onMenu}><I.Layers/></button>}
      <div style={{ minWidth:140, flex:'1 1 0' }}>
        <div style={{ display:'flex', alignItems:'center', gap:8 }}>
          <h1 className="disp" style={{ fontSize:17, fontWeight:600, margin:0, letterSpacing:'-0.02em', whiteSpace:'nowrap' }}>{TITLES[route] || 'Today'}</h1>
        </div>
        {!compact && <div className="mono" style={{ fontSize:10.5, color:'var(--faint)', marginTop:1, letterSpacing:'0.04em' }}>Tuesday · June 2 · a quiet week, mostly green</div>}
      </div>

      {/* command trigger (desktop) */}
      {!compact && (
        <button onClick={onCmd} className="press" style={{ display:'flex', alignItems:'center', gap:8, padding:'8px 12px', borderRadius:10, background:'var(--sunken)', border:'1px solid var(--hair)', color:'var(--faint)', cursor:'pointer', fontSize:12.5, fontFamily:'inherit', flex:'0 1 240px', minWidth:0 }}>
          <I.Search style={{ fontSize:15 }}/><span style={{ flex:1, textAlign:'left' }}>Ask or search…</span>
          <span className="mono" style={{ fontSize:10, padding:'2px 6px', borderRadius:6, background:'var(--raised)', border:'1px solid var(--edge)' }}>⌘K</span>
        </button>
      )}
      {compact && <button className="icon-btn" onClick={onCmd}><I.Search/></button>}

      {/* presence stack */}
      {!compact && (
        <button onClick={() => go('collab')} className="press" style={{ display:'flex', alignItems:'center', background:'none', border:'none', cursor:'pointer', paddingLeft:6 }}>
          {here.slice(0,3).map((c, i) => <span key={c.id} style={{ marginLeft: i === 0 ? 0 : -9 }}><Avatar name={c.name} color={c.color} size={28} ring here={false} /></span>)}
          <span style={{ marginLeft:7, fontSize:11.5, color:'var(--muted)', fontWeight:600 }}><span style={{ display:'inline-block', width:7, height:7, borderRadius:'50%', background:'#22c55e', marginRight:5 }} className="breathe"/>{here.length} here</span>
        </button>
      )}

      <button className="icon-btn" onClick={() => setDark(!dark)} title="Toggle theme">{dark ? <I.Sun/> : <MoonIcon/>}</button>
      <button className="icon-btn" onClick={() => go('echoes')} style={{ position:'relative' }}><I.Bell/><span style={{ position:'absolute', top:7, right:8, width:7, height:7, borderRadius:'50%', background:'var(--accent)', border:'2px solid var(--bg2)' }}/></button>
      {!compact && <button className="btn btn-out press" onClick={onCapture}><I.Mic style={{ fontSize:15 }}/>Capture</button>}
    </header>
  );
}
function MoonIcon(props) {
  return <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" width="1em" height="1em" strokeLinecap="round" strokeLinejoin="round" {...props}><path d="M21 12.8A9 9 0 1 1 11.2 3 7 7 0 0 0 21 12.8Z"/></svg>;
}

// ── Mobile bottom tab bar ────────────────────────────────────────────────────
function MobileBar({ route, go, onCapture }) {
  const tabs = MOBILE_TABS.map(id => NAV_FLAT.find(n => n.id === id));
  return (
    <nav style={{ flex:'0 0 auto', display:'flex', alignItems:'center', justifyContent:'space-around', height:64, paddingBottom:'env(safe-area-inset-bottom)',
      borderTop:'1px solid var(--hair)', background:'var(--glass)', backdropFilter:'blur(16px)', WebkitBackdropFilter:'blur(16px)', position:'relative', zIndex:20 }}>
      {tabs.slice(0,2).map(t => <MobTab key={t.id} t={t} active={route===t.id} onClick={() => go(t.id)} />)}
      <button onClick={onCapture} className="press" style={{ position:'relative', top:-14, width:56, height:56, borderRadius:18, border:'4px solid var(--bg)', background:'var(--accent)', color:'var(--accent-fg)', display:'grid', placeItems:'center', cursor:'pointer', boxShadow:'0 8px 22px -6px var(--accent)', flex:'0 0 auto' }}>
        <I.Plus style={{ fontSize:24 }}/>
      </button>
      {tabs.slice(2).map(t => <MobTab key={t.id} t={t} active={route===t.id} onClick={() => go(t.id)} />)}
    </nav>
  );
}
function MobTab({ t, active, onClick }) {
  const Icon = t.icon;
  return (
    <button onClick={onClick} className="press" style={{ display:'flex', flexDirection:'column', alignItems:'center', gap:3, background:'none', border:'none', cursor:'pointer', color: active ? 'var(--accent)' : 'var(--faint)', padding:'6px 14px', flex:'0 0 auto', transition:'color .16s' }}>
      <Icon style={{ fontSize:22, transform: active ? 'scale(1.08)' : 'none', transition:'transform .2s cubic-bezier(.2,.8,.2,1)' }}/>
      <span style={{ fontSize:9.5, fontWeight:600 }}>{t.label.replace('Life ','')}</span>
    </button>
  );
}

// ── Mobile drawer (full nav) ─────────────────────────────────────────────────
function MobileDrawer({ open, route, go, onClose, dark, setDark }) {
  if (!open) return null;
  return (
    <div onClick={onClose} style={{ position:'absolute', inset:0, zIndex:60, background:'rgba(0,0,0,.4)', backdropFilter:'blur(3px)', animation:'lmtx-fade .2s ease' }}>
      <div onClick={e => e.stopPropagation()} className="scroll" style={{ position:'absolute', top:0, bottom:0, left:0, width:'80%', maxWidth:320, background:'var(--bg2)', borderRight:'1px solid var(--edge)', boxShadow:'var(--shadow-float)', display:'flex', flexDirection:'column', animation:'lmtx-slidein .26s cubic-bezier(.2,.8,.2,1)', overflowY:'auto' }}>
        <div style={{ padding:'20px 18px 14px', display:'flex', alignItems:'center', justifyContent:'space-between' }}>
          <Brand onClick={() => { go('today'); onClose(); }} />
          <button className="icon-btn" onClick={onClose}><I.Close/></button>
        </div>
        <nav style={{ flex:1, padding:'4px 12px', display:'flex', flexDirection:'column', gap:2 }}>
          {NAV.map((grp, gi) => (
            <div key={grp.group} style={{ marginTop: gi === 0 ? 0 : 12 }}>
              <div className="mono" style={{ fontSize:9.5, letterSpacing:'0.12em', textTransform:'uppercase', color:'var(--ghost)', padding:'4px 10px 7px' }}>{grp.group}</div>
              {grp.items.map(it => <NavItem key={it.id} item={it} active={route===it.id} onClick={() => { go(it.id); onClose(); }} />)}
            </div>
          ))}
          <div style={{ height:1, background:'var(--hair)', margin:'12px 8px' }}/>
          <NavItem item={{ id:'echoes', label:'Echoes', icon:I.Bell }} active={route==='echoes'} onClick={() => { go('echoes'); onClose(); }} badge={3} />
          <NavItem item={{ id:'settings', label:'Settings', icon:I.Settings }} active={route==='settings'} onClick={() => { go('settings'); onClose(); }} />
        </nav>
        <div style={{ borderTop:'1px solid var(--hair)', padding:14, display:'flex', alignItems:'center', gap:10 }}>
          <Avatar name="Prabhat" color="var(--accent)" size={34} here />
          <div style={{ flex:1 }}><div style={{ fontSize:13.5, fontWeight:600 }}>Prabhat</div><div style={{ fontSize:11, color:'var(--faint)' }}>Software Engineer · 7.7 yrs</div></div>
          <button className="icon-btn" onClick={() => setDark(!dark)}>{dark ? <I.Sun/> : <MoonIcon/>}</button>
        </div>
      </div>
    </div>
  );
}

// ── Command palette ──────────────────────────────────────────────────────────
function CommandPalette({ open, onClose, go }) {
  const [q, setQ] = useState('');
  const inputRef = useRef(null);
  useEffect(() => { if (open) { setQ(''); setTimeout(() => inputRef.current?.focus(), 40); } }, [open]);
  if (!open) return null;
  const ql = q.toLowerCase();
  const navMatches = NAV_FLAT.concat([{ id:'echoes', label:'Echoes', icon:I.Bell }, { id:'settings', label:'Settings', icon:I.Settings }]).filter(n => n.label.toLowerCase().includes(ql));
  const eventMatches = q ? LMTData.events.filter(e => e.title.toLowerCase().includes(ql) || e.scene.toLowerCase().includes(ql)).slice(0,4) : LMTData.events.slice(0,3);
  const actions = [
    { label:'Capture a new memory', icon:I.Plus, go:'capture' },
    { label:'Ask the Weaver a question', icon:I.Sparkles, go:'ask' },
    { label:'Weave a story', icon:I.Branch, go:'weaver' },
  ].filter(a => !q || a.label.toLowerCase().includes(ql));

  return (
    <div onClick={onClose} style={{ position:'absolute', inset:0, zIndex:80, background:'rgba(0,0,0,.4)', backdropFilter:'blur(4px)', display:'flex', alignItems:'flex-start', justifyContent:'center', paddingTop:'9vh', animation:'lmtx-fade .16s ease' }}>
      <div onClick={e => e.stopPropagation()} className="card-r" style={{ width:'min(620px, 92vw)', maxHeight:'72vh', display:'flex', flexDirection:'column', overflow:'hidden', boxShadow:'var(--shadow-float)', animation:'lmtx-rise .26s cubic-bezier(.2,.8,.2,1)' }}>
        <div style={{ display:'flex', alignItems:'center', gap:11, padding:'15px 18px', borderBottom:'1px solid var(--hair)' }}>
          <I.Search style={{ fontSize:19, color:'var(--accent)' }}/>
          <input ref={inputRef} value={q} onChange={e => setQ(e.target.value)} placeholder="Search memories, jump to a page, or ask…" style={{ flex:1, border:'none', outline:'none', background:'transparent', fontFamily:'inherit', fontSize:15.5, color:'var(--ink)' }}/>
          <span className="mono" style={{ fontSize:10, padding:'3px 7px', borderRadius:6, background:'var(--sunken)', border:'1px solid var(--edge)', color:'var(--faint)' }}>ESC</span>
        </div>
        <div className="scroll" style={{ overflowY:'auto', padding:'10px 10px 14px' }}>
          {actions.length > 0 && <PaletteGroup label="Actions">{actions.map(a => <PaletteRow key={a.label} icon={<a.icon/>} label={a.label} onClick={() => { go(a.go); onClose(); }} accent />)}</PaletteGroup>}
          {navMatches.length > 0 && <PaletteGroup label="Go to">{navMatches.map(n => <PaletteRow key={n.id} icon={<n.icon/>} label={n.label} onClick={() => { go(n.id); onClose(); }} />)}</PaletteGroup>}
          {eventMatches.length > 0 && <PaletteGroup label={q ? 'Memories' : 'Recent'}>{eventMatches.map(e => (
            <PaletteRow key={e.id} icon={<LeafShape color={LMT.leafFor(e.daysSince)} size={16}/>} label={e.title} meta={`${e.t} · ${e.scene}`} onClick={() => { go('scene'); onClose(); }} />
          ))}</PaletteGroup>}
        </div>
      </div>
    </div>
  );
}
function PaletteGroup({ label, children }) {
  return <div style={{ marginBottom:6 }}><div className="mono" style={{ fontSize:9.5, letterSpacing:'0.12em', textTransform:'uppercase', color:'var(--ghost)', padding:'8px 12px 5px' }}>{label}</div>{children}</div>;
}
function PaletteRow({ icon, label, meta, onClick, accent }) {
  return (
    <button onClick={onClick} className="press" style={{ display:'flex', alignItems:'center', gap:12, width:'100%', padding:'9px 12px', borderRadius:10, border:'none', background:'transparent', cursor:'pointer', textAlign:'left', color:'var(--ink)', transition:'background .14s' }}
      onMouseEnter={e => e.currentTarget.style.background = 'var(--sunken)'} onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
      <span style={{ fontSize:17, color: accent ? 'var(--accent)' : 'var(--muted)', display:'grid', placeItems:'center', width:22 }}>{icon}</span>
      <span style={{ flex:1, minWidth:0, fontSize:14, fontWeight:500, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{label}</span>
      {meta && <span className="mono" style={{ fontSize:11, color:'var(--faint)' }}>{meta}</span>}
      <I.ChevronRight style={{ fontSize:14, color:'var(--ghost)' }}/>
    </button>
  );
}

Object.assign(window, { NAV, NAV_FLAT, TITLES, Sidebar, TopBar, MobileBar, MobileDrawer, CommandPalette, Brand });
})();
