// Pages — part 4: Echoes (notifications), Settings (privacy/consent), Capture.
(function () {
const { useState, useEffect, useRef } = React;
const { cx, wash } = LMTXUtil;
const I = window.LMTIcons;
const D = LMTData, D2 = LMTX2;
const Page = window.LMTXPage, EchoIcon = window.LMTXEchoIcon;

// ── ECHOES (notifications inbox) ─────────────────────────────────────────────
function PageEchoes({ go }) {
  const [tab, setTab] = useState('all');
  const extra = [
    { id:'ec5', kind:'anniversary', text:'Two years ago: "The comet from the roof"', meta:'Nights · 730d', t:'today' },
    { id:'ec6', kind:'pattern', text:'You capture most on Sunday evenings — want a gentle reminder?', meta:'Pattern', t:'1d' },
    { id:'ec7', kind:'recurring', text:'"Aidan" mentioned again — promote to a Person?', meta:'Work · 2026', t:'2d' },
    { id:'ec8', kind:'gap', text:'No memories from "Body" in 3 weeks', meta:'Body', t:'3d' },
  ];
  const all = D.echoes.map((e,i) => ({ ...e, t:['just now','2h','today','yesterday'][i] || 'today' })).concat(extra);
  return (
    <Page max={820}>
      <PageHead kicker="Notifications" icon={<I.Bell/>} title="Echoes"
        sub="Gentle returns from your own life — anniversaries, patterns, and quiet nudges the Weaver noticed. Never noisy."
        right={<button className="btn btn-out press"><I.Check style={{ fontSize:15 }}/>Mark all read</button>}/>
      <SegTabs value={tab} onChange={setTab} tabs={[{id:'all',label:'All'},{id:'anniversary',label:'Anniversaries'},{id:'pattern',label:'Patterns'},{id:'recurring',label:'Suggestions'}]}/>
      <div className="card-r stagger" style={{ padding:6 }}>
        {all.filter(e => tab==='all' || e.kind===tab).map((e,i,arr) => (
          <div key={e.id} className="press" style={{ display:'flex', gap:14, alignItems:'flex-start', padding:'14px 12px', borderBottom: i<arr.length-1?'1px solid var(--hair)':'none', cursor:'pointer', borderRadius:10, '--i':i, transition:'background .14s' }}
            onMouseEnter={ev => ev.currentTarget.style.background='var(--sunken)'} onMouseLeave={ev => ev.currentTarget.style.background='none'}>
            <span style={{ flex:'0 0 auto', width:40, height:40, borderRadius:12, background:'var(--accent-wash)', display:'grid', placeItems:'center', color:'var(--accent)', fontSize:18 }}><EchoIcon kind={e.kind}/></span>
            <div style={{ flex:1, minWidth:0 }}>
              <div style={{ fontSize:14, color:'var(--ink)', lineHeight:1.45, fontWeight:500, textWrap:'pretty' }}>{e.text}</div>
              <div className="mono" style={{ fontSize:10.5, color:'var(--faint)', marginTop:4 }}>{e.meta}</div>
            </div>
            <div style={{ display:'flex', flexDirection:'column', alignItems:'flex-end', gap:8, flex:'0 0 auto' }}>
              <span className="mono" style={{ fontSize:10.5, color:'var(--faint)' }}>{e.t}</span>
              <span style={{ width:8, height:8, borderRadius:'50%', background: i<3?'var(--accent)':'transparent' }}/>
            </div>
          </div>
        ))}
      </div>
    </Page>
  );
}

// ── SETTINGS ─────────────────────────────────────────────────────────────────
function PageSettings({ go, dark, setDark }) {
  const [sec, setSec] = useState('account');
  const sections = [
    { id:'account', label:'Account', icon:I.Person },
    { id:'privacy', label:'Privacy & consent', icon:I.Lock },
    { id:'appearance', label:'Appearance', icon:I.Eye },
    { id:'weaver', label:'The Weaver (AI)', icon:I.Sparkles },
    { id:'data', label:'Data & export', icon:I.Layers },
  ];
  return (
    <Page max={1080}>
      <PageHead kicker="Settings" icon={<I.Settings/>} title="Settings"
        sub="Your memories, your rules. Tune privacy defaults, how the Weaver helps, and how the app looks."/>
      <div className="lx-cols-settings">
        <nav className="card-r" style={{ padding:8, height:'fit-content', position:'sticky', top:0 }}>
          {sections.map(s => (
            <button key={s.id} onClick={() => setSec(s.id)} className="nav-item" data-active={sec===s.id} style={{ marginBottom:2 }}>
              <span className="ni-ic"><s.icon/></span><span>{s.label}</span>
            </button>
          ))}
          <div style={{ height:1, background:'var(--hair)', margin:'8px 6px' }}/>
          <button onClick={() => go('auth')} className="nav-item" style={{ color:'var(--muted)' }}><span className="ni-ic"><I.Undo/></span>Sign out</button>
        </nav>
        <div className="card-r" style={{ padding:'22px 24px', minWidth:0 }}>
          {sec === 'account' && <SettingsAccount/>}
          {sec === 'privacy' && <SettingsPrivacy/>}
          {sec === 'appearance' && <SettingsAppearance dark={dark} setDark={setDark}/>}
          {sec === 'weaver' && <SettingsWeaver/>}
          {sec === 'data' && <SettingsData go={go}/>}
        </div>
      </div>
    </Page>
  );
}
function Field({ title, sub, children }) {
  return (
    <div style={{ display:'flex', alignItems:'center', gap:16, padding:'15px 0', borderBottom:'1px solid var(--hair)' }}>
      <div style={{ flex:1, minWidth:0 }}>
        <div style={{ fontSize:14, fontWeight:600, color:'var(--ink)' }}>{title}</div>
        {sub && <div style={{ fontSize:12.5, color:'var(--muted)', marginTop:3, lineHeight:1.45, maxWidth:420 }}>{sub}</div>}
      </div>
      <div style={{ flex:'0 0 auto' }}>{children}</div>
    </div>
  );
}
function SetHead({ title, sub }) { return <div style={{ marginBottom:8 }}><h2 className="disp" style={{ fontSize:19, fontWeight:600, margin:0 }}>{title}</h2>{sub && <p style={{ fontSize:13, color:'var(--muted)', margin:'5px 0 0' }}>{sub}</p>}</div>; }

function SettingsAccount() {
  return <div>
    <SetHead title="Account"/>
    <div style={{ display:'flex', alignItems:'center', gap:16, padding:'8px 0 18px' }}>
      <Avatar name="Prabhat" color="var(--accent)" size={64} glow/>
      <div style={{ flex:1 }}><div className="disp" style={{ fontSize:19, fontWeight:600 }}>Prabhat</div><div style={{ fontSize:13, color:'var(--muted)' }}>prabhat@weaver.life · Senior Software Engineer · 7.7 yrs</div></div>
      <button className="btn btn-out press"><I.Image style={{ fontSize:15 }}/>Change</button>
    </div>
    <Field title="Display name" sub="Shown to people you share scenes with."><input className="input" defaultValue="Prabhat" style={{ width:200 }}/></Field>
    <Field title="Plan" sub="Free — up to 500 memories. 312 used."><span className="pill pill-accent">Free</span></Field>
    <Field title="Two-factor auth" sub="Protect your memories with an extra step."><Toggle on={true} onChange={()=>{}}/></Field>
  </div>;
}
function SettingsPrivacy() {
  return <div>
    <SetHead title="Privacy & consent" sub="Memories are private by default. You decide what leaves the tree."/>
    <Field title="Default visibility" sub="The privacy level new memories start with."><SegTabs size="sm" value="private" onChange={()=>{}} tabs={[{id:'private',label:'Private'},{id:'scene',label:'Scene'},{id:'public',label:'Public'}]}/></Field>
    <Field title="Require consent to share" sub="Collaborators must approve before a memory becomes shared."><Toggle on={true} onChange={()=>{}}/></Field>
    <Field title="Fragile memory lock" sub="Memories you mark fragile stay private even in shared scenes."><Toggle on={true} onChange={()=>{}}/></Field>
    <Field title="On-device only mode" sub="Keep new captures local until you choose to sync."><Toggle on={false} onChange={()=>{}}/></Field>
    <div style={{ marginTop:16, padding:'14px 16px', borderRadius:12, background:'var(--accent-wash)', border:'1px solid var(--accent-line)', display:'flex', gap:11, alignItems:'flex-start' }}>
      <I.Lock style={{ fontSize:17, color:'var(--accent)', flex:'0 0 auto', marginTop:1 }}/>
      <div style={{ fontSize:12.5, color:'var(--muted)', lineHeight:1.5 }}>Your memories are end-to-end encrypted. Not even the Weaver reads a private memory unless you ask it a question that touches one.</div>
    </div>
  </div>;
}
function SettingsAppearance({ dark, setDark }) {
  return <div>
    <SetHead title="Appearance"/>
    <Field title="Theme" sub="Light paper, or a night garden."><SegTabs size="sm" value={dark?'dark':'light'} onChange={v => setDark(v==='dark')} tabs={[{id:'light',label:'Light'},{id:'dark',label:'Dark'}]}/></Field>
    <Field title="Reduce motion" sub="Calm the breathing tree and page transitions."><Toggle on={false} onChange={()=>{}}/></Field>
    <Field title="Serif for stories" sub="Use Newsreader for woven narratives."><Toggle on={true} onChange={()=>{}}/></Field>
    <div style={{ marginTop:14, fontSize:12.5, color:'var(--faint)', display:'flex', alignItems:'center', gap:7 }}><I.Sparkles style={{ fontSize:14, color:'var(--accent)' }}/>More appearance controls live in the Tweaks panel — accent, density, sidebar style, and viewport.</div>
  </div>;
}
function SettingsWeaver() {
  return <div>
    <SetHead title="The Weaver" sub="How much the AI helps — always with citations, never inventing."/>
    <Field title="Suggest links" sub="Propose connections between related memories."><Toggle on={true} onChange={()=>{}}/></Field>
    <Field title="Surface echoes" sub="Anniversaries, patterns, and gentle nudges."><Toggle on={true} onChange={()=>{}}/></Field>
    <Field title="Auto-draft stories" sub="Offer a narrative when you select 3+ memories."><Toggle on={true} onChange={()=>{}}/></Field>
    <Field title="Promote people & places" sub="Recurring names and spots become entities."><Toggle on={false} onChange={()=>{}}/></Field>
    <Field title="Daily surfacing limit" sub="How many Today items the Weaver may raise."><SegTabs size="sm" value="4" onChange={()=>{}} tabs={[{id:'2',label:'2'},{id:'4',label:'4'},{id:'6',label:'6'}]}/></Field>
  </div>;
}
function SettingsData({ go }) {
  return <div>
    <SetHead title="Data & export" sub="It's your life. Take it anywhere."/>
    <Field title="Export everything" sub="Download all memories as Markdown + media."><button className="btn btn-out press"><I.Layers style={{ fontSize:15 }}/>Export</button></Field>
    <Field title="Export a keepsake" sub="A printable book of your Year in Review."><button className="btn btn-out press" onClick={() => go('recap')}><I.Image style={{ fontSize:15 }}/>Make book</button></Field>
    <Field title="Delete a scene's data" sub="Permanently remove a scene and its memories."><button className="btn press" style={{ color:'#dc2626', border:'1px solid #dc262644', background:'transparent' }}>Delete…</button></Field>
  </div>;
}

// ── CAPTURE composer ─────────────────────────────────────────────────────────
function PageCapture({ go }) {
  const [mode, setMode] = useState('voice');
  const [recording, setRecording] = useState(true);
  const [mood, setMood] = useState(4);
  const [vis, setVis] = useState('private');
  const [text, setText] = useState('');
  return (
    <Page max={760}>
      <button className="btn btn-ghost press" onClick={() => go('today')} style={{ alignSelf:'flex-start', padding:'5px 10px', fontSize:12.5 }}><I.ArrowLeft style={{ fontSize:15 }}/>Cancel</button>
      <div style={{ textAlign:'center' }}>
        <h1 className="disp" style={{ fontSize:30, fontWeight:600, margin:0, letterSpacing:'-0.03em' }}>Capture a memory</h1>
        <p style={{ color:'var(--muted)', fontSize:14.5, margin:'9px auto 0', maxWidth:400, lineHeight:1.5 }}>Speak it or write it. The Weaver will suggest a scene, people, and links.</p>
      </div>
      <div style={{ display:'flex', justifyContent:'center' }}><SegTabs value={mode} onChange={setMode} tabs={[{id:'voice',label:'Voice',icon:<I.Mic style={{fontSize:15}}/>},{id:'text',label:'Write',icon:<I.Pen style={{fontSize:15}}/>}]}/></div>

      {mode === 'voice' ? (
        <div className="card-r" style={{ padding:'30px 24px', display:'flex', flexDirection:'column', alignItems:'center', gap:20 }}>
          <button onClick={() => setRecording(!recording)} className="press" style={{ position:'relative', width:96, height:96, borderRadius:'50%', border:'none', cursor:'pointer', background: recording?'var(--accent)':'var(--sunken)', color: recording?'var(--accent-fg)':'var(--muted)', display:'grid', placeItems:'center', boxShadow: recording?'0 10px 34px -8px var(--accent)':'none' }}>
            {recording && <span className="live" style={{ position:'absolute', inset:0, borderRadius:'50%', background:'var(--accent)', opacity:0.4 }}/>}
            <I.Mic style={{ fontSize:38, position:'relative' }}/>
          </button>
          <div style={{ display:'flex', alignItems:'flex-end', gap:4, height:46 }}>
            {Array.from({length:32}).map((_,i) => <span key={i} style={{ width:4, borderRadius:2, background: recording?'var(--accent)':'var(--edge-strong)', height: recording? `${20+Math.abs(Math.sin(i*0.9))*100}%` : '14%', animation: recording?`lmtx-breathe ${0.6+ (i%5)*0.12}s ease-in-out infinite`:'none', animationDelay:`${i*0.04}s`, opacity:0.5+ (i%4)*0.16 }}/>)}
          </div>
          <div className="mono tnum" style={{ fontSize:13, color: recording?'var(--accent)':'var(--faint)' }}>{recording ? '● 00:24 · listening' : 'tap to record'}</div>
          <div className="serif" style={{ fontSize:16, lineHeight:1.6, color:'var(--ink)', textAlign:'center', maxWidth:460 }}>
            "Lin called from Kyoto this morning — the first snow had just started…<span className="mono" style={{ color:'var(--accent)' }}>{recording && '▍'}</span>"
          </div>
        </div>
      ) : (
        <div className="card-r" style={{ padding:'18px 20px' }}>
          <textarea value={text} onChange={e => setText(e.target.value)} placeholder="What happened? Write as much or as little as you like…" rows={6} style={{ width:'100%', border:'none', outline:'none', background:'transparent', resize:'vertical', fontFamily:'Newsreader, Georgia, serif', fontSize:17, lineHeight:1.65, color:'var(--ink)' }}/>
        </div>
      )}

      {/* metadata */}
      <div className="card-r" style={{ padding:'16px 18px', display:'flex', flexDirection:'column', gap:16 }}>
        <div style={{ display:'flex', alignItems:'center', gap:14, flexWrap:'wrap' }}>
          <span style={{ fontSize:12.5, fontWeight:600, color:'var(--muted)', width:64 }}>Mood</span>
          <div style={{ display:'flex', gap:8 }}>
            {[1,2,3,4,5].map(l => { const m = LMT.mood[l]; return <button key={l} onClick={() => setMood(l)} className="press" style={{ width:38, height:38, borderRadius:12, border:`1.5px solid ${mood===l?m.color:'var(--edge)'}`, background: mood===l?wash(m.color,0.14):'transparent', cursor:'pointer', display:'grid', placeItems:'center' }}><span style={{ width:16, height:16, borderRadius:'50%', background:m.color }}/></button>; })}
          </div>
        </div>
        <div style={{ display:'flex', alignItems:'center', gap:14, flexWrap:'wrap' }}>
          <span style={{ fontSize:12.5, fontWeight:600, color:'var(--muted)', width:64 }}>Privacy</span>
          <SegTabs size="sm" value={vis} onChange={setVis} tabs={[{id:'private',label:'Private'},{id:'scene',label:'Scene'},{id:'public',label:'Public'}]}/>
        </div>
        <div style={{ display:'flex', alignItems:'flex-start', gap:14, flexWrap:'wrap' }}>
          <span style={{ fontSize:12.5, fontWeight:600, color:'var(--muted)', width:64, paddingTop:5 }}>Weaver</span>
          <div style={{ flex:1, minWidth:200, display:'flex', flexWrap:'wrap', gap:7 }}>
            <span className="pill pill-accent"><I.Layers style={{ fontSize:11 }}/>Lin &amp; me <I.Plus style={{ fontSize:11 }}/></span>
            <span className="pill"><I.Person style={{ fontSize:11 }}/>Lin Park</span>
            <span className="pill"><I.Pin style={{ fontSize:11 }}/>Kyoto</span>
            <span className="pill" style={{ color:'var(--accent)' }}>#snow</span>
            <span className="pill" style={{ color:'var(--accent)' }}>#phone-call</span>
          </div>
        </div>
      </div>
      <div style={{ display:'flex', gap:10, justifyContent:'flex-end' }}>
        <button className="btn btn-ghost press" onClick={() => go('today')}>Save draft</button>
        <button className="btn btn-pri press" onClick={() => go('tree')} style={{ padding:'11px 22px' }}><I.Leaf style={{ fontSize:16 }}/>Grow this leaf</button>
      </div>
    </Page>
  );
}

Object.assign(window, { PageEchoes, PageSettings, PageCapture });
})();
