/* Boolean query builder — groups of leaves combined with AND/OR.
   Renders the expression (A∪B)∩C live preview.
   props:
     value: [{ op:'AND'|'OR', leaves:[path...] }]
     onChange(value)
*/

const { useState: useStateQB, useMemo: useMemoQB } = React;

function QueryBuilder({ value, onChange }) {
  const groups = value;

  function setGroup(idx, next) {
    const copy = [...groups];
    copy[idx] = next;
    onChange(copy);
  }
  function removeGroup(idx) {
    onChange(groups.filter((_, i) => i !== idx));
  }
  function addGroup() {
    onChange([...groups, { op: 'OR', leaves: [] }]);
  }
  function removeLeaf(gi, leaf) {
    const g = groups[gi];
    setGroup(gi, { ...g, leaves: g.leaves.filter(l => l !== leaf) });
  }

  // Build expression preview: (A1∪A2)∩(B1∪B2)
  const expr = useMemoQB(() => {
    const parts = groups
      .filter(g => g.leaves.length)
      .map((g, gi) => {
        if (g.leaves.length === 1) return label(g.leaves[0], gi);
        const joiner = g.op === 'OR' ? ' ∪ ' : ' ∩ ';
        return '(' + g.leaves.map((l, i) => label(l, gi, i)).join(joiner) + ')';
      });
    return parts.join(' ∩ ');
  }, [groups]);

  function label(path, gi, li) {
    const parts = path.split(' > ');
    return parts[parts.length - 1];
  }

  return (
    <div className="qb">
      {/* Expression preview */}
      <div className="qb-expr">
        <div className="qb-expr-label">
          <span className="label">QUERY EXPR</span>
          <span className="mono mute" style={{ fontSize: 9 }}>
            {groups.reduce((s, g) => s + g.leaves.length, 0)} leaves
          </span>
        </div>
        <div className="qb-expr-text">
          {expr || <span style={{ color: 'var(--text-mute)' }}>// 좌측 트리에서 카테고리 선택…</span>}
        </div>
      </div>

      {/* Groups */}
      <div className="qb-groups">
        {groups.map((g, gi) => (
          <div className="qb-group" key={gi}>
            <div className="qb-group-head">
              <div className="qb-group-name">
                <span className="qb-group-letter">{String.fromCharCode(65 + gi)}</span>
                <span className="label">GROUP</span>
              </div>
              <div className="qb-group-ops">
                <div className="seg-control">
                  <button
                    aria-pressed={g.op === 'OR'}
                    onClick={() => setGroup(gi, { ...g, op: 'OR' })}
                    title="합집합"
                  >∪ OR</button>
                  <button
                    aria-pressed={g.op === 'AND'}
                    onClick={() => setGroup(gi, { ...g, op: 'AND' })}
                    title="교집합"
                  >∩ AND</button>
                </div>
                {groups.length > 1 && (
                  <button className="btn" data-variant="ghost" data-size="sm"
                          onClick={() => removeGroup(gi)}>✕</button>
                )}
              </div>
            </div>
            <div className="qb-group-body">
              {g.leaves.length === 0 && (
                <div className="qb-empty">트리에서 카테고리 추가 →</div>
              )}
              {g.leaves.map(leaf => (
                <div key={leaf} className="qb-leaf">
                  <span className="qb-leaf-path">
                    {leaf.split(' > ').slice(-2).join(' › ')}
                  </span>
                  <button onClick={() => removeLeaf(gi, leaf)}>✕</button>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>

      <button className="btn" data-variant="ghost" onClick={addGroup} style={{ width: '100%', justifyContent: 'center' }}>
        + 그룹 추가 (∩ 교집합)
      </button>

      <style>{`
        .qb { display: flex; flex-direction: column; gap: 10px; }
        .qb-expr {
          padding: 10px 12px;
          background: var(--ink-200);
          border: 1px solid var(--border-strong);
        }
        .qb-expr-label {
          display: flex; justify-content: space-between; align-items: center;
          margin-bottom: 6px;
        }
        .qb-expr-text {
          font-family: var(--font-mono);
          font-size: 12px;
          color: var(--signal);
          line-height: 1.4;
          word-break: break-all;
          min-height: 18px;
        }
        .qb-groups { display: flex; flex-direction: column; gap: 8px; }
        .qb-group {
          border: 1px solid var(--border);
          background: var(--ink-100);
        }
        .qb-group-head {
          display: flex; justify-content: space-between; align-items: center;
          padding: 6px 8px;
          border-bottom: 1px solid var(--border);
          background: var(--ink-200);
        }
        .qb-group-name { display: flex; align-items: center; gap: 8px; }
        .qb-group-letter {
          width: 20px; height: 20px;
          display: grid; place-items: center;
          background: var(--signal);
          color: var(--ink-000);
          font-family: var(--font-mono);
          font-weight: 600;
          font-size: 11px;
        }
        .qb-group-ops { display: flex; gap: 6px; }
        .qb-group-body { padding: 6px 8px; min-height: 32px; }
        .qb-empty {
          font-family: var(--font-mono);
          font-size: 10px;
          color: var(--text-mute);
          padding: 4px 0;
        }
        .qb-leaf {
          display: flex; justify-content: space-between; align-items: center;
          padding: 2px 6px;
          font-family: var(--font-mono);
          font-size: 10px;
          color: var(--text-dim);
          border-bottom: 1px dashed var(--border);
        }
        .qb-leaf:last-child { border-bottom: none; }
        .qb-leaf:hover { color: var(--text); background: var(--ink-200); }
        .qb-leaf button {
          background: none; border: none; color: var(--text-mute); cursor: pointer;
          font-size: 10px;
        }
        .qb-leaf button:hover { color: var(--alert); }
      `}</style>
    </div>
  );
}

Object.assign(window, { QueryBuilder });
