// Notebooks.jsx — 新建本子（建空本子 / 建子本子）· 浅色道林纸体系
// 保存三态：idle「创建」→ saving（转圈·禁用）→ done（「已创建」后关闭）→ err（红字·保留输入）
const { useState: useStateNb, useEffect: useEffectNb, useRef: useRefNb } = React;

function NewNotebookModal({ parent, notebooks, onCreate, onClose, onDeleted }) {
  const tops = (notebooks || []).filter(nb => !nb.parent);
  const [name, setName] = useStateNb('');
  const [par, setPar] = useStateNb(parent || '');
  const [status, setStatus] = useStateNb('idle');   // idle | saving | done | err
  const [msg, setMsg] = useStateNb('');
  const inputRef = useRefNb(null);

  useEffectNb(() => { if (inputRef.current) inputRef.current.focus(); }, []);
  useEffectNb(() => {
    const onKey = e => { if (e.key === 'Escape' && status !== 'saving') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [status, onClose]);

  const parNb = tops.find(t => t.id === par);

  function submit() {
    const nm = name.trim();
    if (!nm || status === 'saving') return;
    setStatus('saving'); setMsg('');
    onCreate(nm, par || null).then(res => {
      if (res && res.existed) {
        setStatus('done'); setMsg('已有同名本子，已为你选中');
        setTimeout(onClose, 900);
      } else {
        setStatus('done'); setMsg('已创建');
        setTimeout(onClose, 650);
      }
    }).catch(() => {
      setStatus('err'); setMsg('没创建成功，检查网络再试');
    });
  }

  const saving = status === 'saving';
  const done = status === 'done';

  return (
    <div className="nbm-backdrop" onClick={e => { if (e.target === e.currentTarget && !saving) onClose(); }}>
      <div className="nbm" role="dialog" aria-modal="true" style={parNb ? { '--h': parNb.hue } : null}>
        <div className="nbm-head">
          <div className="nbm-title">{parNb ? '新建子本子' : '新建本子'}</div>
          <div className="nbm-sub">{parNb ? <span>住在「<b>{parNb.name}</b>」下面的一格</span> : '一格新的本子，住进你的本子树'}</div>
          <button className="nbm-x" onClick={() => !saving && onClose()} aria-label="关闭"><Icon name="x" size={16} /></button>
        </div>

        <div className="nbm-body">
          <label className="nbm-field">
            <span className="nbm-lab">名称</span>
            <input ref={inputRef} className="nbm-input" value={name}
              placeholder="本子名，如 学习 / 数理化"
              onChange={e => { setName(e.target.value); if (status === 'err') setStatus('idle'); }}
              onKeyDown={e => { if (e.key === 'Enter') submit(); }} />
          </label>

          <label className="nbm-field">
            <span className="nbm-lab">归属</span>
            <div className="nbm-selwrap">
              <select className="nbm-sel" value={par} onChange={e => setPar(e.target.value)} disabled={saving}>
                <option value="">顶级本子</option>
                {tops.map(t => <option key={t.id} value={t.id}>{t.name} 的子本子</option>)}
              </select>
              <Icon name="chevDown" size={14} />
            </div>
          </label>

          <div className="nbm-hint">
            {parNb
              ? <span><span className="nbm-dot" /> 子本子继承「{parNb.name}」的色系，更浅一档</span>
              : <span>颜色与图标会按名字自动落定，先不用挑</span>}
          </div>
        </div>

        <div className="nbm-foot">
          {status === 'err'
            ? <span className="nbm-msg err">{msg}</span>
            : done ? <span className="nbm-msg ok"><Icon name="check" size={13} /> {msg}</span>
            : <span className="nbm-msg" />}
          <div className="nbm-actions">
            <button className="nbm-btn ghost" onClick={() => !saving && onClose()} disabled={saving}>取消</button>
            <button className={'nbm-btn solid' + (saving ? ' busy' : '')} onClick={submit} disabled={saving || !name.trim()}>
              {saving ? <span className="nbm-spin" /> : null}
              {saving ? '创建中' : done ? '已创建' : '创建'}
            </button>
          </div>
        </div>
          {!parNb && (
            <div className="nbm-manage">
              <div className="nbm-manage-h">管理已有本子（分享整本 = 生成目录链接，随本子更新；删除后，里面的页会移到「生活」）</div>
              {(() => {
                const all = notebooks || [];
                const tops = all.filter(n => !n.parent && n.name !== '生活');
                const rows = [];
                tops.forEach(t2 => { rows.push(t2); all.filter(c => c.parent === t2.id).forEach(c => rows.push(c)); });
                return rows.map(n => (
                  <div key={n.id} className="nbm-manage-row">
                    <span style={n.parent ? { paddingLeft: 16, opacity: 0.85 } : null}>{n.parent ? '› ' : ''}{n.name}{n.count ? ' · ' + n.count + ' 页' : ''}</span>
                    <button title="寄给好友：这本出现在对方通讯录「分享给我的」里" style={{ marginLeft: 'auto', marginRight: 6, fontSize: 11, color: '#8B2020', background: 'none', border: '1px solid rgba(139,32,32,.4)', borderRadius: 99, padding: '1px 9px', cursor: 'pointer' }}
                      onClick={() => {
                        fetch((window.POPOR_API_BASE || '') + '/api/social/contacts').then(r => r.json()).then(d => {
                          const fs = (d && d.friends) || [];
                          if (!fs.length) { alert('通讯录里还没有好友。先在通讯录邀请对方。'); return; }
                          const pick = window.prompt('把《' + n.name + '》整本寄给谁？输入序号：\n' + fs.map((f, i) => (i + 1) + '. ' + f.name).join('\n'));
                          const idx2 = parseInt(pick, 10) - 1;
                          if (!(idx2 >= 0 && idx2 < fs.length)) return;
                          fetch((window.POPOR_API_BASE || '') + '/api/notebooks/' + n.id + '/share_to', {
                            method: 'POST', headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify({ friend_uid: fs[idx2].uid }),
                          }).then(r => r.json()).then(dd => alert(dd && dd.status === 'ok' ? '已寄给 ' + fs[idx2].name + '：这本会出现在对方通讯录「分享给我的」里，随本子更新。' : ((dd && dd.detail) || '失败')))
                            .catch(() => alert('失败'));
                        }).catch(() => alert('拿不到好友名单'));
                      }}>给好友</button>
                    <button title="分享整本：生成目录链接（学生看题免费）" style={{ marginRight: 6, fontSize: 11, color: '#8B2020', background: 'none', border: '1px solid rgba(139,32,32,.4)', borderRadius: 99, padding: '1px 9px', cursor: 'pointer' }}
                      onClick={() => {
                        fetch((window.POPOR_API_BASE || '') + '/api/notebooks/share', {
                          method: 'POST', headers: { 'Content-Type': 'application/json' },
                          body: JSON.stringify({ notebook_id: n.id }),
                        }).then(r => r.json()).then(d => {
                          if (!d || d.status !== 'ok') { alert((d && d.detail) || '生成失败'); return; }
                          const url = window.location.origin + d.url;
                          const copy = () => window.prompt('整本目录链接（本子有更新，这页自动更新）：', url);
                          if (navigator.clipboard && navigator.clipboard.writeText) navigator.clipboard.writeText(url).then(() => alert('目录链接已复制：\n' + url)).catch(copy);
                          else copy();
                        }).catch(() => alert('生成失败'));
                      }}>分享整本</button>
                    {!n.parent && (
                      <button onClick={() => {
                        if (!window.confirm('删除本子「' + n.name + '」？' + (n.count ? '其中 ' + n.count + ' 页会移到「生活」。' : ''))) return;
                        fetch((window.POPOR_API_BASE || '') + '/api/notebooks/' + n.id + '/delete', { method: 'POST' })
                          .then(r => r.json()).then(() => { if (typeof onDeleted === 'function') onDeleted(); })
                          .catch(() => alert('删除失败'));
                      }}><Icon name="x" size={12} /></button>
                    )}
                  </div>
                ));
              })()}
            </div>
          )}
      </div>
    </div>
  );
}

Object.assign(window, { NewNotebookModal });
