// src/framework/shadowlisp/primitives/SlSym.ts
//
// Vision 49: Symbol element - IS a Matrix component
//
// <sl-sym>foo</sl-sym> represents a symbol (identifier).
// When evaluated, symbols look up their value in the environment.
// When quoted, they return themselves.

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

/**
 * SlSym - Symbol element that IS a Matrix component.
 *
 * @example
 * <sl-sym>x</sl-sym>         => looks up 'x' in environment
 * <sl-sym>my-var</sl-sym>    => looks up 'my-var'
 */
export class SlSym extends SlMatrixElement {
  /**
   * Get the symbol name.
   */
  get name(): string {
    return this.textContent?.trim() ?? '';
  }

  /**
   * Set the symbol name.
   */
  set name(s: string) {
    this.textContent = s;
  }

  /**
   * Symbols evaluate by looking up in the environment.
   */
  async evalSelf(env: SExpr[]): Promise<SExpr> {
    // Cast to SExpr - closures are handled specially elsewhere
    return SlBootstrap.lookup(this.name, env as SlEnv) as SExpr;
  }

  /**
   * Convert to S-expression (the symbol name).
   */
  toSExpr(): SExpr {
    return this.name;
  }
}

// Register the custom element
if (!customElements.get('sl-sym')) {
  customElements.define('sl-sym', SlSym);
}
