// src/framework/shadowlisp/primitives/SlMul.ts
//
// Vision 49: Multiplication element - IS a Matrix component
//
// <sl-mul><a><b></sl-mul> => a * b

import type { SExpr } from '../../../lisp/SExpr';
import { SlMatrixElement } from '../SlMatrixElement';
import { SlBootstrap } from '../SlBootstrap';

/**
 * SlMul - Multiplication element that IS a Matrix component.
 *
 * @example
 * <sl-mul><sl-num>4</sl-num><sl-num>5</sl-num></sl-mul>  => 20
 */
export class SlMul extends SlMatrixElement {
  async evalSelf(env: SExpr[]): Promise<SExpr> {
    let result = 1;

    for (const child of this.children) {
      const value = await this.evalChild(child, env);
      if (typeof value !== 'number') {
        throw new Error(`sl-mul: expected number, got ${typeof value}`);
      }
      result = SlBootstrap.mul(result, value);
    }

    return result;
  }

  toSExpr(): SExpr {
    const args = Array.from(this.children).map(c =>
      (c instanceof SlMatrixElement) ? c.toSExpr() : null
    );
    return ['*', ...args];
  }
}

if (!customElements.get('sl-mul')) {
  customElements.define('sl-mul', SlMul);
}
