// =========================================================
// FBIF 资讯订阅 · 标签管理 (Tag manager)
// Tags are user-defined labels applied to SOURCES. Here you
// create/delete tags, toggle their visibility in the sidebar,
// and manage which sources carry each tag.
// =========================================================

const SWATCHES = ['#E8542E', '#8A5A2B', '#1F8A5B', '#3DA35D', '#2A6FDB', '#7A4FBB', '#C0392B', '#0F8B8D', '#B45F00', '#555E6B', '#1456F0', '#646A73'];

// popover: pick which sources carry this tag (checkboxes + search + count)
const SourcePickPopover = ({ tag, sources, anchorRef, onToggleSourceTag, onClose }) => {
  const [q, setQ] = React.useState('');
  const list = sources.filter(s => s.name.includes(q));
  const count = sources.filter(s => s.tags.includes(tag.id)).length;
  return (
    <AnchoredMenu anchorRef={anchorRef} align="right" width={284} onClose={onClose}>
      <div style={{ padding: '6px 10px 4px', fontSize: 11, color: '#8F959E', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <span>哪些来源属于「{tag.name}」</span><span>已选 {count}</span>
      </div>
      <div style={{ padding: '4px 6px 6px' }}><Input icon="search" placeholder="搜索来源" value={q} onChange={e => setQ(e.target.value)} width="100%" height={30} /></div>
      {list.map(s => {
        const on = s.tags.includes(tag.id);
        return (
          <MenuRow key={s.id} onClick={() => onToggleSourceTag(s.id, tag.id)}
            label={<span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}><SourceMark short={s.short} color={s.color} size={20} />{s.name}</span>}
            right={<span style={{ width: 16, height: 16, borderRadius: 4, border: `1.5px solid ${on ? '#1456F0' : '#C9CDD4'}`, background: on ? '#1456F0' : '#fff', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>{on && <Icon name="check" size={12} color="#fff" />}</span>} />
        );
      })}
      {list.length === 0 && <div style={{ padding: 16, textAlign: 'center', color: '#8F959E', fontSize: 12 }}>无匹配来源</div>}
    </AnchoredMenu>
  );
};

const TagRow = ({ tag, data, onToggleSub, onDelete, onToggleSourceTag }) => {
  const [hover, setHover] = React.useState(false);
  const [pickOpen, setPickOpen] = React.useState(false);
  const pickBtnRef = React.useRef(null);
  const used = data.SOURCES.filter(s => s.tags.includes(tag.id));
  const articleCount = used.filter(s => s.subscribed).reduce((a, s) => a + (s.article_count || 0), 0);
  return (
    <div onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '0 16px', height: 56, borderBottom: '1px solid #EDEFF2', background: hover ? '#F7F8FA' : '#fff' }}>
      <span style={{ width: 12, height: 12, borderRadius: 9999, background: tag.color, flexShrink: 0 }} />
      <div style={{ width: 160, flexShrink: 0 }}>
        <div style={{ fontSize: 14, color: '#1F2329', fontWeight: 500 }}>{tag.name}</div>
      </div>
      <div style={{ width: 150, flexShrink: 0, fontSize: 13, color: '#646A73' }}>{used.length} 个来源</div>
      <div style={{ flex: 1, fontSize: 13, color: '#646A73' }}>{articleCount} 条资讯</div>
      <div style={{ flexShrink: 0 }}>
        <span ref={pickBtnRef} style={{ display: 'inline-flex' }}>
          <Button variant="secondary" size="dense" icon="link" onClick={() => setPickOpen(o => !o)}>管理来源</Button>
        </span>
        {pickOpen && <SourcePickPopover tag={tag} sources={data.SOURCES} anchorRef={pickBtnRef} onToggleSourceTag={onToggleSourceTag} onClose={() => setPickOpen(false)} />}
      </div>
      <div style={{ flexShrink: 0, display: 'flex', alignItems: 'center', gap: 8, width: 120, justifyContent: 'flex-end' }}>
        <span style={{ fontSize: 12, color: tag.subscribed ? '#1456F0' : '#BBBFC4' }}>侧栏显示</span>
        <Switch on={tag.subscribed} onChange={() => onToggleSub(tag)} />
      </div>
      <button onClick={() => onDelete(tag)} title="删除标签"
        style={{ border: 'none', background: 'transparent', cursor: 'pointer', color: hover ? '#8F959E' : '#C9CDD4', padding: 4, display: 'inline-flex', flexShrink: 0 }}>
        <Icon name="trash-2" size={15} />
      </button>
    </div>
  );
};

const TagManager = ({ data, onCreateTag, onDeleteTag, onToggleTagSub, onToggleSourceTag, onClose }) => {
  useLucide();
  const [name, setName] = React.useState('');
  const [color, setColor] = React.useState(SWATCHES[0]);

  const create = () => { const v = name.trim(); if (!v) return; onCreateTag(v, color); setName(''); };

  return (
    <div style={{ flex: 1, minWidth: 0, height: '100%', overflowY: 'auto', background: '#F5F6F7' }}>
      <div style={{ background: '#fff', borderBottom: '1px solid #DEE0E3' }}>
        <div style={{ maxWidth: 960, margin: '0 auto', width: '100%', padding: '20px 32px 0' }}>
          <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 16 }}>
            <div>
              <h1 style={{ fontSize: 24, lineHeight: '32px', fontWeight: 600, color: '#1F2329', margin: 0 }}>标签管理</h1>
              <p style={{ fontSize: 13, color: '#646A73', margin: '6px 0 0' }}>标签是你给「来源」打的组织标签。一个来源可有多个标签，时间线可按标签筛选。</p>
            </div>
            <Button variant="text" icon="arrow-left" onClick={onClose}>返回时间线</Button>
          </div>

          {/* 新建标签 */}
          <div style={{ marginTop: 16, marginBottom: 20, border: '1px solid #DEE0E3', borderRadius: 8, padding: 16, background: '#FBFCFD' }}>
            <div style={{ fontSize: 13, fontWeight: 500, color: '#1F2329', marginBottom: 10, display: 'flex', alignItems: 'center', gap: 6 }}>
              <Icon name="plus-circle" size={15} color="#1456F0" />新建标签
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
              <Input placeholder="标签名称，如「植物基」" value={name} onChange={e => setName(e.target.value)} onKeyDown={e => e.key === 'Enter' && create()} width={240} height={36} />
              <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                <span style={{ fontSize: 12, color: '#8F959E' }}>颜色</span>
                {SWATCHES.slice(0, 8).map(c => (
                  <button key={c} onClick={() => setColor(c)} title={c}
                    style={{ width: 20, height: 20, borderRadius: 9999, background: c, cursor: 'pointer',
                             border: color === c ? '2px solid #1F2329' : '2px solid #fff', boxShadow: '0 0 0 1px #E5E6EB', padding: 0 }} />
                ))}
              </div>
              <Button variant="primary" size="large" icon="plus" onClick={create} disabled={!name.trim()}>创建标签</Button>
            </div>
            {!name.trim() && <div style={{ fontSize: 12, color: '#8F959E', marginTop: 8 }}>输入标签名称后即可创建（同名标签会被拦截）。</div>}
          </div>
        </div>
      </div>

      {/* tag list */}
      <div>
        <div style={{ maxWidth: 960, margin: '0 auto', width: '100%', padding: '20px 32px 40px' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12 }}>
            <span style={{ fontSize: 15, fontWeight: 600, color: '#1F2329' }}>全部标签</span>
            <span style={{ fontSize: 12, color: '#8F959E', fontFamily: 'var(--font-mono)' }}>{data.TAGS.length}</span>
          </div>
          <div style={{ border: '1px solid #DEE0E3', borderRadius: 8, overflow: 'hidden', background: '#fff' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '0 16px', height: 36, background: '#F7F8FA', borderBottom: '1px solid #E5E6EB', fontSize: 12, color: '#646A73' }}>
              <span style={{ width: 12, flexShrink: 0 }} />
              <span style={{ width: 160, flexShrink: 0 }}>标签</span>
              <span style={{ width: 150, flexShrink: 0 }}>关联来源</span>
              <span style={{ flex: 1 }}>资讯数</span>
              <span style={{ flexShrink: 0, width: 96 }} />
              <span style={{ flexShrink: 0, width: 120, textAlign: 'right' }}>侧栏</span>
              <span style={{ width: 23, flexShrink: 0 }} />
            </div>
            {data.TAGS.map(t => (
              <TagRow key={t.id} tag={t} data={data} onToggleSub={onToggleTagSub} onDelete={onDeleteTag} onToggleSourceTag={onToggleSourceTag} />
            ))}
            {data.TAGS.length === 0 && <div style={{ padding: 40, textAlign: 'center', color: '#8F959E', fontSize: 13 }}>暂无标签，先创建一个</div>}
          </div>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { TagManager });
