/* shell.jsx — Persom 2.1 原型：侧边栏、账号菜单、Ask、Connections / Settings / Account 弹窗 */
/* global React */
window.P21 = window.P21 || {};
(() => {
  const { C, SERIF, useP, Label, Btn, Av, Toggle, Modal, ModalHead, Seg, Ico, D } = window.P21;
  const PAGES = ['Home', 'You', 'Timeline', 'Playbook', 'Check-ins'];
  /* 菜单图标颜色，照 Persom 2.5 */
  const NAVC = { Home: '#787774', You: '#9065B0', Timeline: '#337EA9', Playbook: '#D9730D', 'Check-ins': '#CB912F' };

  /* ───────── （1）侧边栏 ───────── */
  function Sidebar() {
    const { s, set, go } = useP();
    const paused = s.paused;
    return (
      <aside style={{ width: 232, flexShrink: 0, background: C.side, borderRight: `1px solid ${C.line2}`, display: 'flex', flexDirection: 'column', padding: '16px 12px 14px', position: 'relative' }}>
        <div style={{ display: 'flex', gap: 8, padding: '0 6px 18px' }}>
          {['#FF5F57', '#FEBC2E', '#28C840'].map(c => <span key={c} style={{ width: 12, height: 12, borderRadius: '50%', background: c }} />)}
        </div>
        {/* 品牌 logo：深色圆角方块 + 衬线斜体 P，照 Persom 2.5 */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '2px 10px 16px' }}>
          <span style={{ width: 24, height: 24, borderRadius: 7, background: C.ink, display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: SERIF, fontStyle: 'italic', fontSize: 17, color: '#fff', lineHeight: 1, paddingRight: 1 }}>P</span>
          <span style={{ fontSize: 14.5, fontWeight: 600, letterSpacing: '-.01em' }}>Persom</span>
        </div>
        <nav style={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
          {PAGES.map(p => {
            const on = s.page === p;
            return (
              <div key={p} onClick={() => go(p)} className="p21-h-side"
                style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '7px 10px', borderRadius: 8, cursor: 'pointer', background: on ? C.active : 'transparent', color: on ? C.ink : C.ink2, fontWeight: on ? 600 : 400 }}>
                <Ico name={p} sw={1.8} style={{ stroke: NAVC[p] }} />
                <span>{p}</span>
              </div>
            );
          })}
        </nav>

        <div style={{ marginTop: 'auto', display: 'flex', flexDirection: 'column', gap: 4, position: 'relative' }}>
          {/* 更新提示：新版本下载完成待重启时出现，点击后静默重启并消失 */}
          {s.restartHint && (
            <div onClick={() => set({ restartHint: false, toast: 'Restarted · Persom is up to date' })} className="p21-h-side"
              style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '6px 12px', borderRadius: 6, fontSize: 13.5, color: C.green, cursor: 'pointer', fontWeight: 500 }}>
              <Ico name="restart" sw={1.8} />Restart to update
            </div>
          )}
          {/* 运行状态 */}
          {/* 运行状态：整行可点，向上弹出暂停菜单；暂停时显示恢复时间 */}
          <div onClick={(e) => { e.stopPropagation(); set({ pauseMenu: !s.pauseMenu, acct: false }); }} className="p21-h-side"
            style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '6px 12px', marginBottom: 4, borderRadius: 6, cursor: 'pointer', fontSize: 13.5, fontWeight: 500, color: paused ? C.muted : C.ink, background: s.pauseMenu ? C.active : 'transparent' }}>
            <span style={{ width: 8, height: 8, borderRadius: '50%', flexShrink: 0, background: paused ? 'transparent' : C.greenDot, border: `1.5px solid ${paused ? C.faint : C.greenDot}` }} />
            <span style={{ flex: 1, minWidth: 0, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
              {paused ? 'Paused' : 'Active'}
              {paused && paused.until && <span style={{ fontWeight: 400, fontSize: 12.5, color: C.faint }}> · until {paused.until}</span>}
            </span>
          </div>
          {s.pauseMenu && <PauseMenu />}
          {/* 账号入口 */}
          <div onClick={(e) => { e.stopPropagation(); set({ acct: !s.acct }); }} className="p21-h-side"
            style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '6px 10px', borderRadius: 6, cursor: 'pointer', background: s.acct ? C.active : 'transparent' }}>
            <Av size={26} uploaded={s.avatar} />
            <span style={{ flex: 1, fontWeight: 500 }}>{D.user.name}</span>
          </div>
          {s.acct && <AccountMenu />}
        </div>
      </aside>
    );
  }

  /* 暂停：paused 为 false 或 { until }，until 是恢复时间文字；手动恢复时 until 为 null，只显示 Paused */
  const hhmm = (d) => `${d.getHours()}:${String(d.getMinutes()).padStart(2, '0')}`;

  /* 暂停菜单：点 Active 向上展开，样式与账号菜单一致；四档参考 2.0 菜单栏 */
  function PauseMenu() {
    const { s, set } = useP();
    const now = Date.now();
    const opts = [
      ['For 30 minutes', hhmm(new Date(now + 30 * 60e3))],
      ['For 1 hour', hhmm(new Date(now + 60 * 60e3))],
      ['Until tomorrow', 'tomorrow'],
      ['Until I resume', null],
    ];
    const pause = (until) => set({ paused: { until }, pauseMenu: false, toast: until ? `Paused until ${until}` : 'Paused until you resume' });
    const rowStyle = { display: 'flex', alignItems: 'center', gap: 10, padding: '7px 10px', borderRadius: 6, cursor: 'pointer', fontSize: 13.5 };
    return (
      <div onClick={(e) => e.stopPropagation()}
        style={{ position: 'absolute', left: 0, right: -40, bottom: 88, background: '#fff', border: `1px solid ${C.border}`, borderRadius: 10, padding: 6, boxShadow: '0 16px 40px rgba(15,15,15,.18)', zIndex: 25, animation: 'p21pop .15s ease-out' }}>
        {s.paused && (<>
          <div onClick={() => set({ paused: false, pauseMenu: false, toast: 'Persom is active again' })} className="p21-h-soft" style={{ ...rowStyle, color: C.green, fontWeight: 500 }}>
            <Ico name="play" size={15} />
            <span style={{ flex: 1 }}>Resume now</span>
          </div>
          <div style={{ borderTop: `1px solid ${C.line2}`, margin: '4px 0' }} />
        </>)}
        <div style={{ padding: '6px 10px 4px', fontSize: 11.5, fontWeight: 500, color: C.faint, letterSpacing: '.02em' }}>Pause Persom</div>
        {opts.map(([label, until]) => (
          <div key={label} onClick={() => pause(until)} className="p21-h-soft" style={rowStyle}>
            <Ico name="pause" size={15} style={{ color: C.muted }} />
            <span style={{ flex: 1 }}>{label}</span>
            {until && <span style={{ fontSize: 12, color: C.faint }}>{until === 'tomorrow' ? 'Tomorrow' : until}</span>}
          </div>
        ))}
      </div>
    );
  }

  /* 账号菜单：向上展开，参考 ChatGPT 桌面端 */
  function AccountMenu() {
    const { s, set, openModal } = useP();
    const items = [
      ['connections', 'Connections', '', () => openModal({ type: 'connections' })],
      ['settings', 'Settings', '⌘,', () => openModal({ type: 'settings' })],
      ['account', 'Account', '', () => openModal({ type: 'account' })],
      ['logout', 'Log out', '', () => set({ acct: false, toast: 'Logged out (prototype)' })],
    ];
    return (
      <div onClick={(e) => e.stopPropagation()}
        style={{ position: 'absolute', left: 0, right: -40, bottom: 44, background: '#fff', border: `1px solid ${C.border}`, borderRadius: 10, padding: 6, boxShadow: '0 16px 40px rgba(15,15,15,.18)', zIndex: 25, animation: 'p21pop .15s ease-out' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 10px 10px' }}>
          <Av size={30} uploaded={s.avatar} />
          <div style={{ minWidth: 0 }}>
            <div style={{ fontWeight: 500, lineHeight: 1.3 }}>{D.user.name}</div>
            <div style={{ fontSize: 12, color: C.muted }}>{D.user.email}</div>
          </div>
        </div>
        <div style={{ borderTop: `1px solid ${C.line2}`, margin: '2px 0 4px' }} />
        {items.map(([ic, label, key, fn]) => (
          <div key={label} onClick={fn} className="p21-h-soft"
            style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '7px 10px', borderRadius: 6, cursor: 'pointer', fontSize: 13.5 }}>
            <Ico name={ic} size={15} style={{ color: C.muted }} />
            <span style={{ flex: 1 }}>{label}</span>
            <span style={{ fontSize: 12, color: C.faint }}>{key}</span>
          </div>
        ))}
      </div>
    );
  }

  /* ───────── （7）Ask ───────── */
  function AskFab() {
    const { set } = useP();
    return (
      <span onClick={() => set({ ask: true })} className="p21-h-dark"
        style={{ position: 'absolute', right: 24, bottom: 24, zIndex: 30, display: 'inline-flex', alignItems: 'center', gap: 8, padding: '11px 18px', borderRadius: 999, background: C.ink, color: '#F3F4F1', fontSize: 14, fontWeight: 500, cursor: 'pointer', boxShadow: '0 14px 34px rgba(15,15,15,.3)' }}>
        ✦ Ask Persom
      </span>
    );
  }

  /* ───────── （8）Connections / Settings / Account 弹窗 ───────── */
  /* 内容取自现在 persome-app 的对应页面，精简展示 */
  function Row({ k, v, children, sub }) {
    return (
      <div style={{ display: 'flex', alignItems: 'center', gap: 16, padding: '11px 0', borderTop: `1px solid ${C.line2}` }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div>{k}</div>
          {sub && <div style={{ fontSize: 12.5, color: C.muted, marginTop: 2 }}>{sub}</div>}
        </div>
        {v !== undefined && <span style={{ color: C.muted, fontSize: 13.5 }}>{v}</span>}
        {children}
      </div>
    );
  }

  function ConnectionsModal({ onClose }) {
    const [tab, setTab] = React.useState('use');
    const cn = D.conn;
    return (
      <Modal width={600} onClose={onClose}>
        <ModalHead title="Connections" onClose={onClose} />
        <div style={{ marginTop: 14 }}><Seg items={[['learn', 'What it learns'], ['use', 'Who can use it']]} value={tab} onChange={setTab} /></div>
        {tab === 'learn' ? (
          <div style={{ marginTop: 18 }}>
            <div style={{ color: C.muted }}>Everything Persom knows about you comes from here.</div>
            <div style={{ marginTop: 16, display: 'flex', alignItems: 'center', gap: 22 }}>
              <div style={{ fontFamily: SERIF, fontSize: 40, lineHeight: 1 }}>{cn.learned}<span style={{ fontSize: 15, color: C.muted, marginLeft: 6, fontFamily: 'inherit' }}>learned</span></div>
              <div style={{ flex: 1, display: 'flex', height: 8, borderRadius: 999, overflow: 'hidden', background: C.soft }}>
                {cn.sourcesMix.map(([n, p], i) => <span key={n} style={{ width: p + '%', background: [C.green, C.leaf, '#B9D3B5', '#E3D5B3'][i] }} />)}
              </div>
            </div>
            <div style={{ marginTop: 10, display: 'flex', gap: 16, fontSize: 12.5, color: C.muted, flexWrap: 'wrap' }}>
              {cn.sourcesMix.map(([n, p]) => <span key={n}>{n} {p}%</span>)}
              <span style={{ marginLeft: 'auto' }}>Learning since {cn.since} · {cn.days} days</span>
            </div>
            <Label style={{ marginTop: 24, marginBottom: 4 }}>Watching</Label>
            <Row k="All apps · none excluded" sub="Learns from your screen, without you writing it down."><span style={{ fontSize: 13, color: C.green }}>On</span><Btn small>Manage</Btn></Row>
            <Label style={{ marginTop: 20, marginBottom: 4 }}>Imports</Label>
            <Row k="Claude memory" sub="imported Aug 18"><Btn small>Import memory</Btn></Row>
          </div>
        ) : (
          <div style={{ marginTop: 18 }}>
            <div style={{ color: C.muted }}>Connect once. No agent asks who you are again.</div>
            <div style={{ marginTop: 14, padding: '14px 16px', background: C.side, borderRadius: 10, lineHeight: 1.6 }}>
              <div>Persom introduced you <b style={{ fontWeight: 600 }}>{cn.introduced}</b> times in the last 30 days.</div>
              <div style={{ color: C.muted, fontSize: 13.5 }}>{cn.chars} characters of context you never typed. Typing that out would take about {cn.hours} hours, at 300 characters a minute.</div>
            </div>
            <Label style={{ marginTop: 22, marginBottom: 4 }}>Connected</Label>
            {D.agents.filter(a => a.connected).map(a => (
              <Row key={a.id} k={a.name} sub={`full access · introduced ${a.reads}×`}><Btn small kind="danger">Disconnect</Btn></Row>
            ))}
            <Label style={{ marginTop: 20, marginBottom: 4 }}>On this Mac · not connected</Label>
            {D.agents.filter(a => !a.connected).map(a => (
              <Row key={a.id} k={<span style={{ color: C.muted }}>{a.name}</span>}><Btn small kind="primary">Connect</Btn></Row>
            ))}
            <Label style={{ marginTop: 20, marginBottom: 4 }}>Access log</Label>
            {cn.access.map(([t, n], i) => <Row key={i} k={n} v={t} />)}
            <div style={{ marginTop: 16, display: 'flex', justifyContent: 'space-between' }}>
              <Btn small>Manual MCP setup</Btn>
              <span style={{ fontSize: 13, color: C.muted, cursor: 'pointer' }}>See all ›</span>
            </div>
          </div>
        )}
      </Modal>
    );
  }

  function SettingsModal({ onClose }) {
    const [tab, setTab] = React.useState('General');
    const [t, setT] = React.useState({ login: true, ropt: true });
    const tabs = ['General', 'Permissions', 'Model', 'Privacy', 'About'];
    return (
      <Modal width={620} onClose={onClose}>
        <ModalHead title="Settings" onClose={onClose} />
        <div style={{ marginTop: 14 }}><Seg items={tabs.map(x => [x, x])} value={tab} onChange={setTab} /></div>
        <div style={{ marginTop: 16, minHeight: 300 }}>
          {tab === 'General' && (<>
            <Row k="Language" sub="Persom uses the language you choose after this window refreshes."><span style={{ fontSize: 13, border: `1px solid ${C.border}`, borderRadius: 6, padding: '4px 10px' }}>System default ▾</span></Row>
            <Row k="Launch at login"><Toggle on={t.login} onClick={() => setT({ ...t, login: !t.login })} /></Row>
            <Row k="Right Option actions" sub="Polish a draft, run an explicit /do command, or predict your next line in an empty editor."><Toggle on={t.ropt} onClick={() => setT({ ...t, ropt: !t.ropt })} /></Row>
            <Row k="Watching" sub="All apps · none excluded"><Btn small>Manage</Btn></Row>
          </>)}
          {tab === 'Permissions' && (<>
            {['Accessibility', 'Screen & System Audio Recording', 'Microphone', 'Full Disk Access', 'Notifications'].map(p => (
              <Row key={p} k={p}><span style={{ fontSize: 13, color: C.green }}>● Granted</span></Row>
            ))}
            <div style={{ marginTop: 12, fontSize: 12.5, color: C.muted }}>Revoking any of these stops the matching source. Nothing already recorded is deleted.</div>
          </>)}
          {tab === 'Model' && (<>
            <Row k="Build status" v="Up to date" />
            <Row k="Runtime model" v="Persom managed" />
            <Row k="Model memories" v={String(D.memories)} />
            <div style={{ marginTop: 12, fontSize: 12.5, color: C.muted }}>Persom manages its model provider. API keys and provider selection are not settings in this version.</div>
          </>)}
          {tab === 'Privacy' && (<>
            <Label style={{ marginBottom: 4 }}>Where your data goes</Label>
            <Row k="Screenshots and audio" v="Never leave this Mac" />
            <Row k="Text used to build your model" v="Sent through Persom's relay" />
            <Row k="AI tools you connect" v="Only what you connect them to" />
            <Label style={{ marginTop: 18, marginBottom: 4 }}>Storage</Label>
            <Row k="Keep history" v="30 days ▾" />
            <Row k="Storage limit" v="5 GB ▾" />
            <div style={{ marginTop: 14, display: 'flex', gap: 8 }}><Btn small>Export everything</Btn><Btn small kind="danger">Delete all capture history…</Btn></div>
          </>)}
          {tab === 'About' && (<>
            <div style={{ fontFamily: SERIF, fontSize: 26 }}>Persom 2.1</div>
            <div style={{ marginTop: 2, color: C.muted }}>{D.user.name} · {D.user.email}</div>
            <div style={{ marginTop: 16, display: 'flex', alignItems: 'center', gap: 12 }}><Btn small>Check for updates</Btn><span style={{ fontSize: 12.5, color: C.muted }}>Checks automatically when Persom opens</span></div>
            <div style={{ marginTop: 16, display: 'flex', gap: 16, fontSize: 13.5, color: C.green }}><span>Docs ›</span><span>Send feedback ›</span></div>
          </>)}
        </div>
      </Modal>
    );
  }

  function AccountModal({ onClose }) {
    const { s, set } = useP();
    return (
      <Modal width={520} onClose={onClose}>
        <ModalHead title="Account" onClose={onClose} />
        <div style={{ marginTop: 20, display: 'flex', alignItems: 'center', gap: 16 }}>
          <Av size={56} uploaded={s.avatar} />
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            <span style={{ fontSize: 13, color: C.muted }}>Shown at the top of Home.</span>
            <span style={{ display: 'flex', gap: 8 }}>
              <Btn small onClick={() => set({ avatar: true })}>Upload photo</Btn>
              {s.avatar && <Btn small kind="danger" onClick={() => set({ avatar: false })}>Remove</Btn>}
            </span>
          </div>
        </div>
        <div style={{ marginTop: 20, fontSize: 12.5, color: C.muted }}>Your name</div>
        <div style={{ marginTop: 6, display: 'flex', gap: 8 }}>
          <input defaultValue={D.user.name} placeholder="How Persom should address you"
            style={{ flex: 1, border: `1px solid ${C.border}`, borderRadius: 6, padding: '8px 10px', font: 'inherit', outline: 0 }} />
          <Btn kind="primary" onClick={() => set({ toast: 'Name saved' })}>Save name</Btn>
        </div>
        <div style={{ marginTop: 22 }}>
          <Row k="Email" v={D.user.email} />
          <Row k="Google" v="Connected" />
          <Row k="Apple" v="Not connected"><Btn small>Link Apple</Btn></Row>
        </div>
        <div style={{ marginTop: 18, display: 'flex', justifyContent: 'flex-end' }}><Btn kind="danger">Sign out</Btn></div>
      </Modal>
    );
  }

  Object.assign(window.P21, { PAGES, Sidebar, AskFab, Row, ConnectionsModal, SettingsModal, AccountModal });
})();
