// Contacts.jsx — 通讯录 · 人际关系（合作者 / 工作 / 朋友 / 粉丝 / 家人 + 本子分类）
const { useState: useStateCT } = React;

// 导入演示（微信 / Instagram —— 假流程，仅提示）
function ImportToast({ text, onDone }) {
  React.useEffect(() => { const t = setTimeout(onDone, 2200); return () => clearTimeout(t); }, []);
  return (
    <div className="import-toast">
      <span className="import-spin"></span>
      <span>{text}</span>
    </div>
  );
}

function ContactCard({ c, onOpenNote }) {
  const books = c.books || [];
  return (
    <div className="ct-card">
      <div className="ct-head">
        <span className="ct-av" style={{ background: c.av }}>{c.name.slice(0, 1)}</span>
        <div className="ct-id">
          <div className="ct-name">{c.name}<span className="ct-src">· {SOURCE_LABEL[c.src] || 'Popor'}</span></div>
          <div className="ct-prof">{c.prof}</div>
        </div>
      </div>

      <div className="ct-rels">
        {(c.rel || []).map(r => {
          const m = relMeta(r);
          return <span key={r} className={'ct-rel tone-' + m.tone}>{m.label}</span>;
        })}
      </div>

      {books.length > 0 && (
        <div className="ct-line"><Icon name="book" size={12} /><span>{books.join(' · ')}</span></div>
      )}

      <div className="ct-skills">
        <span className="ct-skills-k">擅长</span>
        <span className="ct-skills-row">
          {(c.skills || []).map(s => <span key={s} className="ct-skill">{s}</span>)}
        </span>
      </div>

      {c.note && (
        <button className="ct-co" onClick={() => onOpenNote && onOpenNote(c)}>
          <Icon name="route" size={13} />
          <span>最近共创 · <em>{c.note}</em></span>
        </button>
      )}

      <div className="ct-foot">
        <span className="ct-handle">{c.id}</span>
        {c.phone && <span className="ct-phone">{c.phone}</span>}
        <span className="ct-foot-sp"></span>
        <button className="ct-msg"><Icon name="send" size={12} /> 私信</button>
      </div>
    </div>
  );
}

function ContactsView({ onClose, onOpenNote }) {
  const [filter, setFilter] = useStateCT('all');
  const [toast, setToast] = useStateCT(null);

  // 本子分组（数据里出现过的）
  const books = [];
  CONTACTS.forEach(c => (c.books || []).forEach(b => { if (books.indexOf(b) < 0) books.push(b); }));

  const list = CONTACTS.filter(c => {
    if (filter === 'all') return true;
    if (filter.indexOf('book:') === 0) return (c.books || []).indexOf(filter.slice(5)) >= 0;
    return (c.rel || []).indexOf(filter) >= 0;
  });

  function count(pred) { return CONTACTS.filter(pred).length; }

  return (
    <div className="sheet" onClick={e => { if (e.target.classList.contains('sheet')) onClose(); }}>
      <div className="sheet-panel">
        <div className="sheet-bar">
          <button className="ov-back" onClick={onClose}><Icon name="arrowL" size={15} /> 返回工作台</button>
          <div className="sheet-title">通讯录<span className="sheet-sub">{CONTACTS.length} 位 · 你的人脉网络</span></div>
          <div className="sheet-actions">
            <button className="sheet-import" onClick={() => setToast('正在从微信通讯录读取联系人…（演示）')}>
              <span className="src-dot wechat">微</span> 导入微信
            </button>
            <button className="sheet-import" onClick={() => setToast('正在连接 Instagram，读取关注关系…（演示）')}>
              <span className="src-dot ins">IG</span> 导入 Instagram
            </button>
          </div>
        </div>

        <div className="ct-filter">
          <button className={'rel-chip' + (filter === 'all' ? ' on' : '')} onClick={() => setFilter('all')}>
            全部 <span className="rel-n">{CONTACTS.length}</span>
          </button>
          {RELATION_TYPES.map(r => {
            const n = count(c => (c.rel || []).indexOf(r.id) >= 0);
            if (!n) return null;
            return (
              <button key={r.id} className={'rel-chip tone-' + r.tone + (filter === r.id ? ' on' : '')} onClick={() => setFilter(r.id)}>
                {r.label} <span className="rel-n">{n}</span>
              </button>
            );
          })}
          <span className="ct-filter-div"></span>
          <span className="ct-filter-k">按本子</span>
          {books.map(b => (
            <button key={b} className={'rel-chip book' + (filter === 'book:' + b ? ' on' : '')} onClick={() => setFilter('book:' + b)}>
              <Icon name="book" size={11} /> {b}
            </button>
          ))}
        </div>

        <div className="sheet-scroll">
          <div className="contacts-grid">
            {list.map(c => <ContactCard key={c.id} c={c} onOpenNote={onOpenNote} />)}
          </div>
        </div>
      </div>
      {toast && <ImportToast text={toast} onDone={() => setToast(null)} />}
    </div>
  );
}

Object.assign(window, { ContactsView });
