/* Interest tree picker — 560 categories
   props:
     onAdd(path)        — leaf selected
     onAddMany(paths[]) — bulk select
*/

const { useState, useMemo } = React;

function InterestTree({ onAdd, selectedSet }) {
  const [query, setQuery] = useState('');
  const [expanded, setExpanded] = useState(() => new Set(['관심사', '구매의도', '모바일']));
  const [filter, setFilter] = useState('all'); // all | new | intent | interest

  const taxonomy = window.TAXONOMY || [];

  const allLeaves = useMemo(() => {
    const out = [];
    function visit(n) {
      if (n.leaf) out.push(n.path);
      if (n.children) n.children.forEach(visit);
    }
    taxonomy.forEach(visit);
    return out;
  }, [taxonomy]);

  // Filtered tree by search/filter
  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    function visit(node) {
      const matches = (node.path || node.name).toLowerCase().includes(q);
      const tagOk = (
        filter === 'all' ||
        (filter === 'new'      && (node.path || '').startsWith('모바일')) ||
        (filter === 'intent'   && (node.path || '').startsWith('구매의도')) ||
        (filter === 'interest' && (node.path || '').startsWith('관심사'))
      );
      const children = (node.children || []).map(visit).filter(Boolean);
      if (children.length || (matches && (filter === 'all' || tagOk))) {
        return { ...node, children: children.length ? children : node.children };
      }
      return null;
    }
    if (!q && filter === 'all') return taxonomy;
    return taxonomy.map(visit).filter(Boolean);
  }, [taxonomy, query, filter]);

  function toggle(path) {
    setExpanded(prev => {
      const next = new Set(prev);
      if (next.has(path)) next.delete(path); else next.add(path);
      return next;
    });
  }

  function renderNode(node, depth = 0) {
    const isOpen = expanded.has(node.path) || (query && query.length > 1);
    const isLeaf = node.leaf;
    const isSelected = selectedSet.has(node.path);

    return (
      <div key={node.path || node.name} className="tree-node">
        <div
          className={'tree-row' + (isLeaf ? ' is-leaf' : '') + (isSelected ? ' is-selected' : '')}
          style={{ paddingLeft: 4 + depth * 12 }}
          onClick={() => {
            if (isLeaf) onAdd(node.path);
            else toggle(node.path);
          }}
        >
          {!isLeaf && (
            <span className="caret">{isOpen ? '▾' : '▸'}</span>
          )}
          {isLeaf && <span className="caret">›</span>}
          <span style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {node.name}
          </span>
          <span className="count">
            {isLeaf ? (isSelected ? '✓' : '') : node.count}
          </span>
        </div>
        {!isLeaf && isOpen && node.children && (
          <div>{node.children.map(c => renderNode(c, depth + 1))}</div>
        )}
      </div>
    );
  }

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <div style={{ padding: '8px 10px', borderBottom: '1px solid var(--border)' }}>
        <input
          type="text"
          placeholder="560개 카테고리 검색…"
          value={query}
          onChange={e => setQuery(e.target.value)}
          style={{
            width: '100%',
            background: 'var(--ink-200)',
            border: '1px solid var(--border-strong)',
            color: 'var(--text)',
            padding: '5px 8px',
            fontSize: '11px',
            outline: 'none',
            fontFamily: 'var(--font-mono)',
          }}
        />
        <div className="seg-control" style={{ marginTop: 8, width: '100%' }}>
          {[
            { id: 'all',      label: 'ALL  560' },
            { id: 'new',      label: '신규  100' },
            { id: 'interest', label: '관심사 192' },
            { id: 'intent',   label: '구매의도 268' },
          ].map(t => (
            <button
              key={t.id}
              aria-pressed={filter === t.id}
              onClick={() => setFilter(t.id)}
              style={{ flex: 1 }}
            >{t.label}</button>
          ))}
        </div>
      </div>
      <div style={{ flex: 1, overflowY: 'auto', padding: '4px 6px' }}>
        {filtered.map(n => renderNode(n))}
        {filtered.length === 0 && (
          <div style={{ padding: 20, textAlign: 'center', color: 'var(--text-mute)', fontSize: 11 }}>
            검색 결과 없음
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { InterestTree: React.memo(InterestTree) });
