/* 念念 Web — 后台外壳：侧边导航 + 顶部栏 + 主题 */
(function () {
  const { useState, useEffect } = React;
  const h = React.createElement;
  const I = window.NNIcon;

  // —— 主题应用（同步到 <html> 与 localStorage）——
  window.NNApplyTheme = function ({ preset, mode, accentH }) {
    const el = document.documentElement;
    if (preset !== undefined) { el.dataset.preset = preset; try { localStorage.setItem('nn-preset', preset); } catch (e) {} }
    if (mode !== undefined) { el.dataset.mode = mode; try { localStorage.setItem('nn-mode', mode); } catch (e) {} }
    if (accentH !== undefined) { el.style.setProperty('--accent-h', accentH); try { localStorage.setItem('nn-accent-h', accentH); } catch (e) {} }
  };
  window.NNReadTheme = function () {
    let preset = 'fresh', mode = 'light', accentH = '192';
    try {
      preset = localStorage.getItem('nn-preset') || preset;
      mode = localStorage.getItem('nn-mode') || mode;
      accentH = localStorage.getItem('nn-accent-h') || accentH;
    } catch (e) {}
    return { preset, mode, accentH };
  };

  // —— 导航结构 ——
  const NAV = [
    { group: '主要', items: [
      { id: 'dashboard', name: '工作台', icon: 'dashboard' },
      { id: 'calendar', name: '日历', icon: 'calendar' },
      { id: 'records', name: '活动记录', icon: 'records' },
      { id: 'diary', name: '日记', icon: 'diary' },
      { id: 'articles', name: '文章', icon: 'articles' },
    ]},
    { group: '管理', items: [
      { id: 'content', name: '内容管理', icon: 'content' },
      { id: 'knowledge', name: '知识库', icon: 'knowledge' },
      { id: 'media', name: '媒体资源', icon: 'media' },
      { id: 'favorites', name: '收藏', icon: 'star' },
      { id: 'trash', name: '垃圾箱', icon: 'trash' },
    ]},
    { group: '系统', items: [
      { id: 'stats', name: '统计', icon: 'stats' },
      { id: 'settings', name: '设置', icon: 'settings' },
    ]},
  ];
  const ALL = NAV.flatMap(g => g.items);
  const titleOf = (id) => (ALL.find(i => i.id === id) || { name: '' }).name;

  function Sidebar({ route, go, mode }) {
    const [menu, setMenu] = useState(() => window.NNStorage.get('menu-settings', { hidden: [], spacing: '标准' }));
    useEffect(() => {
      const on = () => setMenu(window.NNStorage.get('menu-settings', { hidden: [], spacing: '标准' }));
      window.addEventListener('nn-menu-settings', on);
      return () => window.removeEventListener('nn-menu-settings', on);
    }, []);
    const hidden = new Set(menu.hidden || []);
    const pad = { '紧凑': '7px 10px', '标准': '9px 10px', '宽松': '12px 10px' }[menu.spacing] || '9px 10px';
    return h('aside', { className: 'nn-sidebar' },
      h('div', { className: 'nn-side-brand' }, h(window.NNLogo, { size: 32, textSize: 18 })),
      h('nav', { className: 'nn-nav' },
        NAV.map(grp => h('div', { key: grp.group, className: 'nn-nav-group' },
          h('div', { className: 'nn-nav-label' }, grp.group),
          grp.items.filter(it => !hidden.has(it.id)).map(it => h('a', {
            key: it.id,
            href: '#/' + it.id,
            className: 'nn-nav-item' + (route === it.id ? ' active' : ''),
            style: { padding: pad },
          },
            h('span', { className: 'nn-nav-ic' }, I(it.icon, { size: 19 })),
            h('span', null, it.name),
            it.id === 'trash' ? h('span', { className: 'nn-nav-count' }, '4') : null
          ))
        ))
      ),
      h('div', { className: 'nn-side-foot' },
        h('a', { className: 'nn-side-public', href: 'site.html' },
          I('globe', { size: 18 }), h('span', null, '查看公开站点'), I('arrowR', { size: 15, style: { marginLeft: 'auto', opacity: .6 } })
        )
      )
    );
  }

  function Topbar({ route, mode, toggleMode, onNew }) {
    const [open, setOpen] = useState(false);
    const [notif, setNotif] = useState(false);
    const openCmdK = () => window.dispatchEvent(new CustomEvent('nn-cmdk-open'));
    const NOTIFS = [
      { id: 'x1', ic: 'import', t: '数据迁移完成：成功导入 8,002 项，14 项待处理。', tm: '刚刚', unread: true },
      { id: 'x2', ic: 'download', t: '每周自动备份已生成（18.4 MB）。', tm: '今天 03:00', unread: true },
      { id: 'x3', ic: 'lock', t: '检测到来自「北京」的异地登录，请确认是否本人。', tm: '5 天前', unread: false },
      { id: 'x4', ic: 'articles', t: '文章《为什么我坚持每天写日记》已发布到公开站点。', tm: '5月28日', unread: false },
    ];
    const t = window.NN.TODAY;
    return h('header', { className: 'nn-topbar' },
      h('div', { className: 'nn-tb-left' },
        h('h2', { className: 'nn-tb-title' }, titleOf(route)),
        route === 'dashboard' ? h('span', { className: 'nn-tb-sub tnum' }, `${t.date} · ${t.weekday} · ${t.lunar}`) : null
      ),
      h('div', { className: 'nn-tb-right' },
        h('button', { className: 'nn-search', onClick: openCmdK, style: { textAlign: 'left' } },
          I('search', { size: 17, style: { color: 'var(--text-faint)' } }),
          h('span', { style: { flex: 1, color: 'var(--text-faint)', fontSize: 14 } }, '搜索日记、文章、记事…'),
          h('kbd', null, '⌘K')
        ),
        h('div', { className: 'nn-new', onClick: () => setOpen(o => !o) },
          h('button', { className: 'nn-btn nn-btn-primary nn-btn-sm', style: { height: 38, paddingLeft: 12 } },
            I('plus', { size: 17 }), '新建', I('chevronD', { size: 14, style: { opacity: .8 } })
          ),
          open ? h('div', { className: 'nn-menu' },
            [['diary', 'diary', '写日记'], ['articles', 'articles', '写文章'], ['records', 'records', '记一笔'], ['knowledge', 'knowledge', '新知识条目']]
              .map(([ic, r, label]) => h('a', { key: r, href: '#/' + r, className: 'nn-menu-item', onClick: () => setOpen(false) }, I(ic, { size: 17, style: { color: 'var(--text-3)' } }), label))
          ) : null
        ),
        h('div', { className: 'topbar-bell-wrap' },
          h('button', { className: 'nn-btn nn-btn-ghost nn-btn-icon', title: '通知', onClick: () => setNotif(v => !v), style: { position: 'relative' } },
            I('bell', { size: 18 }), h('span', { className: 'notif-dot' })),
          notif ? h(React.Fragment, null,
            h('div', { style: { position: 'fixed', inset: 0, zIndex: 55 }, onClick: () => setNotif(false) }),
            h('div', { className: 'notif-pop' },
              h('div', { className: 'notif-h' }, h('span', null, '通知'), h('button', { onClick: () => setNotif(false) }, '全部标为已读')),
              h('div', { className: 'notif-list' }, NOTIFS.map(n => h('div', { key: n.id, className: 'notif-item' + (n.unread ? ' unread' : '') },
                h('span', { className: 'nic' }, I(n.ic, { size: 16 })),
                h('div', { className: 'nbody' }, h('div', { className: 't' }, n.t), h('div', { className: 'tm' }, n.tm))))))) : null),
        h('button', { className: 'nn-btn nn-btn-ghost nn-btn-icon', onClick: toggleMode, title: '切换明暗' }, I(mode === 'dark' ? 'sun' : 'moon', { size: 18 })),
        h('button', { className: 'nn-avatar', title: '退出登录', onClick: async () => {
          if (!confirm('确定退出后台？')) return;
          try { await fetch('/api/logout', { method: 'POST', credentials: 'same-origin' }); } catch (e) {}
          location.href = '/';
        } }, '念')
      )
    );
  }

  function Shell({ route, go, mode, toggleMode, children }) {
    return h('div', { className: 'nn-shell' },
      h(Sidebar, { route, go, mode }),
      h('div', { className: 'nn-main' },
        h(Topbar, { route, mode, toggleMode }),
        h('div', { className: 'nn-content', key: route }, children)
      )
    );
  }

  // —— 通用小组件 ——
  function Badge({ status }) {
    const map = {
      published: ['已发布', 'var(--success)'], draft: ['草稿', 'var(--text-3)'],
      private: ['私密', 'var(--a-med)'], archived: ['已归档', 'var(--warn)'], public: ['公开', 'var(--accent)'],
    };
    const [label, color] = map[status] || [status, 'var(--text-3)'];
    return h('span', { className: 'nn-badge', style: { background: `color-mix(in oklch, ${color} 14%, transparent)`, color } },
      h('span', { className: 'dot', style: { background: color, width: 6, height: 6 } }), label);
  }

  function Tag({ name, color }) {
    return h('span', { className: 'nn-tag-pill', style: { '--tc': color || 'var(--text-3)' } }, name);
  }

  function SectionTitle({ children, action }) {
    return h('div', { className: 'nn-sec-title' }, h('h3', null, children), action || null);
  }

  function PageHead({ title, desc, children }) {
    return h('div', { className: 'nn-page-head' },
      h('div', null, h('h1', null, title), desc ? h('p', null, desc) : null),
      children ? h('div', { className: 'nn-page-actions' }, children) : null
    );
  }

  Object.assign(window, { NN_NAV: NAV, NN_titleOf: titleOf, NNSidebar: Sidebar, NNTopbar: Topbar, NNShell: Shell, NNBadge: Badge, NNTag: Tag, NNSectionTitle: SectionTitle, NNPageHead: PageHead });
})();
