// src/framework/shadowlisp/primitives/SlQuote.ts
//
// Vision 49: Quote element - returns child unevaluated - IS a Matrix component
//
// John McCarthy (LISP creator, Turing Award 1971):
//   "Quote is the bridge between data and code. It says 'treat this as data,
//    not as a program to run.'"
//
// <sl-quote><sl-sym>x</sl-sym></sl-quote> => 'x (the symbol x, not its value)

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

/**
 * SlQuote - Quote element (McCarthy primitive #1) that IS a Matrix component.
 *
 * Returns the child expression without evaluating it.
 * This is the foundation of homoiconicity - code as data.
 *
 * @example
 * <sl-quote><sl-sym>x</sl-sym></sl-quote>              => "x"
 * <sl-quote><sl-list>...</sl-list></sl-quote>          => the list as data
 */
export class SlQuote extends SlMatrixElement {
  /**
   * Quote returns its child WITHOUT evaluating it.
   */
  async evalSelf(_env: SExpr[]): Promise<SExpr> {
    const child = this.firstElementChild;
    if (!child) {
      return null;
    }

    // Return the S-expression representation, not the evaluated result
    if (child instanceof SlMatrixElement) {
      return child.toSExpr();
    }

    // For non-evaluable children, return textContent
    return child.textContent?.trim() ?? null;
  }

  /**
   * Convert to S-expression: ['quote', child]
   */
  toSExpr(): SExpr {
    const child = this.firstElementChild;
    if (!child) {
      return ['quote', null];
    }

    if (child instanceof SlMatrixElement) {
      return ['quote', child.toSExpr()];
    }

    return ['quote', child.textContent?.trim() ?? null];
  }
}

if (!customElements.get('sl-quote')) {
  customElements.define('sl-quote', SlQuote);
}
