/* 業務OS — ナレッジ tab (knowledge base / past decisions) */

function KnowledgeTab() {
  const D = window.GYOMU;
  const [typeFilter, setTypeFilter] = useState('all');
  const [search, setSearch] = useState('');
  const [selected, setSelected] = useState(null);

  const types = ['all', '成果', '判断記録', '改善', '失敗', 'テンプレート'];
  const typeColors = { '成果': 'var(--success)', '判断記録': 'var(--info)', '改善': 'var(--stage-s0)', '失敗': 'var(--danger)', 'テンプレート': 'var(--warning)' };

  let items = D.knowledge;
  if (typeFilter !== 'all') items = items.filter(k => k.type === typeFilter);
  if (search) items = items.filter(k => k.title.includes(search) || k.summary.includes(search) || k.tags.some(t => t.includes(search)));

  const sel = D.knowledge.find(k => k.id === selected);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <div style={{ flex: 1, overflowY: 'auto', padding: 16 }}>
        <div style={{ marginBottom: 14 }}>
          <div style={{ fontSize: 18, fontWeight: 600, color: 'var(--text-0)', letterSpacing: '-.01em', marginBottom: 4 }}>ナレッジベース</div>
          <div style={{ fontSize: 11, color: 'var(--text-2)' }}>判断・成果・失敗の蓄積 — AI業務OSの学習データとして次回の精度向上に反映</div>
        </div>

        {/* Search + filters */}
        <div style={{ display: 'flex', gap: 8, marginBottom: 14, alignItems: 'center' }}>
          <div style={{ position: 'relative', flex: 1, maxWidth: 280 }}>
            <Icon name="search" size={13} style={{ position: 'absolute', left: 8, top: 7, color: 'var(--text-3)' }} />
            <input value={search} onChange={e => setSearch(e.target.value)} placeholder="キーワード検索..."
              style={{ width: '100%', fontSize: 11, padding: '6px 8px 6px 26px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--bg-3)', color: 'var(--text-1)', fontFamily: 'var(--font-sans)', outline: 'none' }} />
          </div>
          {types.map(t => <FilterChip key={t} label={t === 'all' ? 'すべて' : t} active={typeFilter === t} onClick={() => setTypeFilter(t)} />)}
          <div style={{ flex: 1 }} />
          <span style={{ fontSize: 10, color: 'var(--text-3)', fontFamily: 'var(--font-mono)' }}>{items.length} 件</span>
        </div>

        {/* Knowledge cards */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {items.map(k => (
            <KnowledgeCard key={k.id} item={k} selected={selected === k.id}
              onClick={() => setSelected(selected === k.id ? null : k.id)}
              typeColor={typeColors[k.type] || 'var(--text-3)'} />
          ))}
          {items.length === 0 && (
            <div style={{ textAlign: 'center', padding: '32px 24px', color: 'var(--text-3)', fontSize: 12 }}>
              該当するナレッジがありません
            </div>
          )}
        </div>
      </div>

      {/* Detail panel */}
      {sel && (
        <div style={{ borderTop: '2px solid var(--accent)', padding: '14px 16px', background: 'var(--surface)', flexShrink: 0 }}>
          <div style={{ display: 'flex', gap: 16 }}>
            <div style={{ flex: 1 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
                <span style={{ fontSize: 9, fontWeight: 700, padding: '2px 7px', borderRadius: 3, background: (typeColors[sel.type] || 'var(--text-3)') + '18', color: typeColors[sel.type] }}>{sel.type}</span>
                <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--text-0)' }}>{sel.title}</span>
              </div>
              <div style={{ fontSize: 11, color: 'var(--text-1)', lineHeight: 1.7, marginBottom: 8 }}>{sel.summary}</div>
              <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
                {sel.tags.map((tag, i) => (
                  <span key={i} style={{ fontSize: 9, padding: '2px 8px', borderRadius: 'var(--radius-pill)', background: 'var(--bg-3)', color: 'var(--text-2)', fontWeight: 500 }}>#{tag}</span>
                ))}
              </div>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6, flexShrink: 0, minWidth: 120 }}>
              <div>
                <div style={{ fontSize: 9, fontWeight: 600, letterSpacing: '.06em', textTransform: 'uppercase', color: 'var(--text-3)', marginBottom: 2 }}>記録者</div>
                <div style={{ fontSize: 11, fontWeight: 500, color: 'var(--text-0)' }}>{sel.author}</div>
              </div>
              <div>
                <div style={{ fontSize: 9, fontWeight: 600, letterSpacing: '.06em', textTransform: 'uppercase', color: 'var(--text-3)', marginBottom: 2 }}>日付</div>
                <div style={{ fontSize: 11, fontFamily: 'var(--font-mono)', color: 'var(--text-1)' }}>{sel.date}</div>
              </div>
              <div>
                <div style={{ fontSize: 9, fontWeight: 600, letterSpacing: '.06em', textTransform: 'uppercase', color: 'var(--text-3)', marginBottom: 2 }}>有用度</div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
                  <span style={{ fontFamily: 'var(--font-mono)', fontSize: 14, fontWeight: 600, color: 'var(--accent)' }}>{sel.score}</span>
                  <span style={{ fontSize: 9, color: 'var(--text-3)' }}>/ 5.0</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

function KnowledgeCard({ item, selected, onClick, typeColor }) {
  const [h, setH] = useState(false);
  return (
    <div onClick={onClick} onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
      style={{
        background: selected ? 'var(--accent-soft)' : h ? 'var(--surface-hover)' : 'var(--surface)',
        border: '1px solid ' + (selected ? 'var(--accent)' : h ? 'var(--border)' : 'var(--border-subtle)'),
        boxShadow: selected ? 'var(--glow-accent)' : 'none',
        borderRadius: 6, padding: '10px 14px', cursor: 'pointer', transition: 'all .12s',
      }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
        <span style={{ fontSize: 9, fontWeight: 700, padding: '2px 7px', borderRadius: 3, background: typeColor + '18', color: typeColor }}>{item.type}</span>
        <span style={{ fontSize: 12, fontWeight: 600, color: 'var(--text-0)', flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{item.title}</span>
        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--text-3)' }}>{item.date}</span>
      </div>
      <div style={{ fontSize: 10, color: 'var(--text-2)', lineHeight: 1.5, marginBottom: 6, display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>{item.summary}</div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
        <span style={{ fontSize: 9, color: 'var(--text-3)' }}>{item.author} · {item.dept}</span>
        <div style={{ flex: 1 }} />
        <div style={{ display: 'flex', gap: 3 }}>
          {item.tags.slice(0, 3).map((tag, i) => (
            <span key={i} style={{ fontSize: 8, padding: '1px 6px', borderRadius: 'var(--radius-pill)', background: 'var(--bg-3)', color: 'var(--text-3)' }}>#{tag}</span>
          ))}
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 2 }}>
          <Icon name="star" size={10} style={{ color: 'var(--warning)' }} />
          <span style={{ fontFamily: 'var(--font-mono)', fontSize: 9, fontWeight: 600, color: 'var(--text-2)' }}>{item.score}</span>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { KnowledgeTab, KnowledgeCard });
