/**
 * MxAppShell — shared page layout with header and status bar.
 *
 * Provides consistent chrome for all Matrix webapps:
 * - Top header with app title, icon, and NATS connection indicator
 * - Status bar at bottom with daemon root, user identity, connection state
 * - Content slot for the app's root component
 *
 * Usage in index.html:
 *   <mx-app-shell title="Harness" icon="science">
 *     <mx-harness-app slot="content" name="harness"></mx-harness-app>
 *   </mx-app-shell>
 *
 * Or wrap programmatically — the shell injects theme tokens automatically.
 */

export class MxAppShell extends HTMLElement {
  private _connected = false;
  private _daemonRoot = '';
  private _principalId = '';

  constructor() {
    super();
    this.attachShadow({ mode: 'open' });
  }

  connectedCallback(): void {
    this._connected = true;
    this._render();
    this._watchConnection();
  }

  disconnectedCallback(): void {
    this._connected = false;
  }

  private _render(): void {
    if (!this.shadowRoot) return;
    const title = this.getAttribute('title') || 'Matrix';
    const icon = this.getAttribute('icon') || '';

    this.shadowRoot.innerHTML = `
      <style>
        :host {
          display: flex;
          flex-direction: column;
          height: 100%;
          font-family: var(--mx-font-family, system-ui, -apple-system, sans-serif);
          color: var(--mx-color-text, #f1f5f9);
          background: var(--mx-color-surface, #0f172a);
        }

        .shell-content {
          flex: 1;
          overflow: hidden;
          display: flex;
          flex-direction: column;
        }

        .shell-status-bar {
          display: flex;
          align-items: center;
          padding: 4px 12px;
          background: var(--mx-color-surface-inset, #020617);
          border-top: 1px solid var(--mx-color-border-light, #1e293b);
          font-size: var(--mx-font-size-xs, 10px);
          color: var(--mx-color-text-muted, #475569);
          gap: 12px;
          flex-shrink: 0;
          height: 24px;
        }

        .status-item {
          display: flex;
          align-items: center;
          gap: 4px;
        }

        .status-dot {
          width: 6px;
          height: 6px;
          border-radius: 50%;
          background: var(--mx-color-success, #22c55e);
        }

        .status-dot.disconnected {
          background: var(--mx-color-danger, #ef4444);
        }

        .status-spacer { flex: 1; }

        .status-label { color: var(--mx-color-text-secondary, #94a3b8); }
      </style>

      <div class="shell-content">
        <slot name="content"></slot>
        <slot></slot>
      </div>

      <div class="shell-status-bar">
        <div class="status-item">
          <span class="status-dot" id="conn-dot"></span>
          <span id="conn-label">Connecting...</span>
        </div>
        <div class="status-item">
          <span class="status-label">Root:</span>
          <span id="daemon-root">—</span>
        </div>
        <span class="status-spacer"></span>
        <div class="status-item">
          <span class="status-label">User:</span>
          <span id="principal-id">—</span>
        </div>
        <div class="status-item">
          <span class="status-label">${title}</span>
        </div>
      </div>
    `;
  }

  private _watchConnection(): void {
    // Poll for DSL host connection state
    const interval = setInterval(() => {
      if (!this._connected) { clearInterval(interval); return; }

      const dslHost = this.closest('matrix-dsl-host') ?? document.querySelector('matrix-dsl-host');
      const daemonRoot = dslHost?.getAttribute('daemon-root') ?? '';
      const dot = this.shadowRoot?.querySelector('#conn-dot') as HTMLElement;
      const label = this.shadowRoot?.querySelector('#conn-label') as HTMLElement;
      const rootEl = this.shadowRoot?.querySelector('#daemon-root') as HTMLElement;

      if (daemonRoot && daemonRoot.trim().length > 0) {
        this._daemonRoot = daemonRoot;
        if (dot) dot.classList.remove('disconnected');
        if (label) label.textContent = 'Connected';
        if (rootEl) rootEl.textContent = daemonRoot;
      } else {
        if (dot) dot.classList.add('disconnected');
        if (label) label.textContent = 'Connecting...';
      }
    }, 2000);
  }

  updatePrincipal(principalId: string): void {
    this._principalId = principalId;
    const el = this.shadowRoot?.querySelector('#principal-id') as HTMLElement;
    if (el) el.textContent = principalId;
  }
}

if (typeof customElements !== 'undefined' && !customElements.get('mx-app-shell')) {
  customElements.define('mx-app-shell', MxAppShell);
}
