import { LitElement, html, css, nothing } from '/vendor/lit/lit.min.js';
import { unsafeHTML } from '/vendor/lit/lit.min.js';
import { escapeHtml, formatTimestamp, sessionPriority, ansiToHtml } from './utils.js';
import { icons } from './icons.js';

/**
 * <session-tile> - Dashboard tile representing a tmux session.
 *
 * Properties:
 *   session:           Object - session data { name, snapshot, last_activity_at, bell, ... }
 *   mobile:            Boolean - mobile layout mode
 *   multiDevice:       Boolean - multi-device support enabled
 *   showDeviceBadges:  Boolean - whether to show device name badges
 *   activityIndicator: String - 'none' | 'glow' | 'dot' | 'both'
 *   viewMode:          String - 'auto' | 'fit' (controls snapshot line count)
 *
 * Events:
 *   tile-click    { name, remoteId }   - Session selected
 *   tile-options  { name, remoteId, sessionKey, rect }  - Kebab menu opened
 */
export class SessionTile extends LitElement {
  static properties = {
    session:           { type: Object },
    mobile:            { type: Boolean },
    multiDevice:       { type: Boolean, attribute: 'multi-device' },
    showDeviceBadges:  { type: Boolean, attribute: 'show-device-badges' },
    activityIndicator: { type: String, attribute: 'activity-indicator' },
    viewMode:          { type: String, attribute: 'view-mode' },
  };

  // Render into light DOM so existing CSS applies without migration.
  createRenderRoot() { return this; }

  constructor() {
    super();
    this.session = {};
    this.mobile = false;
    this.multiDevice = false;
    this.showDeviceBadges = true;
    this.activityIndicator = 'both';
    this.viewMode = 'auto';
  }

  get _priority() {
    return sessionPriority(this.session);
  }

  get _isBell() {
    return this._priority === 'bell';
  }

  get _name() {
    return this.session.name || '';
  }

  get _sessionKey() {
    return this.session.sessionKey || this._name;
  }

  get _remoteId() {
    return this.session.remoteId ?? null;
  }

  get _classes() {
    let cls = 'session-tile';
    const ind = this.activityIndicator;
    const priority = this._priority;
    if (this._isBell && (ind === 'glow' || ind === 'both')) cls += ' session-tile--bell';
    if (this._isBell && (ind === 'dot' || ind === 'both')) cls += ' session-tile--edge-bell';
    if (priority === 'active') cls += ' session-tile--active';
    const activity = this.session && this.session.last_activity_at;
    if (!activity || (Date.now() / 1000 - activity) > 3600) cls += ' session-tile--stale';
    if (this.mobile) cls += ` session-tile--tier-${priority}`;
    return cls;
  }

  get _snapshotHtml() {
    const snapshot = this.session.snapshot || '';
    const lineCount = this.viewMode === 'fit' ? -80 : -20;
    // Trim trailing blank lines first (see buildTileHTML comment in app.js)
    const allLines = snapshot.split('\n');
    while (allLines.length > 0 && allLines[allLines.length - 1].trim() === '') {
      allLines.pop();
    }
    const lastLines = allLines.slice(lineCount).join('\n');
    return ansiToHtml(lastLines);
  }

  _onTileClick(e) {
    // Don't trigger tile-click when clicking the options button
    if (e.target.closest('.tile-options-btn')) return;
    this.dispatchEvent(new CustomEvent('tile-click', {
      bubbles: true, composed: true,
      detail: { name: this._name, remoteId: this._remoteId },
    }));
  }

  _onOptionsClick(e) {
    e.stopPropagation();
    const btn = e.currentTarget;
    this.dispatchEvent(new CustomEvent('tile-options', {
      bubbles: true, composed: true,
      detail: {
        name: this._name,
        remoteId: this._remoteId,
        sessionKey: this._sessionKey,
        rect: btn.getBoundingClientRect(),
      },
    }));
  }

  render() {
    const name = this._name;
    const timeStr = formatTimestamp(this.session.last_activity_at || null);

    const showBadge = this.multiDevice && this.session.deviceName && this.showDeviceBadges;

    return html`
      <article
        class=${this._classes}
        data-session=${name}
        data-session-key=${this._sessionKey}
        tabindex="0"
        role="listitem"
        aria-label=${name}
        @click=${this._onTileClick}
      >
        <div class="tile-header">
          <span class="tile-name">${name}</span>
          ${showBadge
            ? html`<span class="device-badge">${this.session.deviceName}</span>`
            : nothing}
          <span class="tile-meta">${timeStr}</span>
          <button
            class="tile-options-btn"
            data-session=${name}
            aria-label="Session options"
            aria-haspopup="true"
            @click=${this._onOptionsClick}
          >${unsafeHTML(icons.kebab)}</button>
        </div>
        <div class="tile-body">
          <pre>${unsafeHTML(this._snapshotHtml)}</pre>
        </div>
      </article>
    `;
  }
}

customElements.define('session-tile', SessionTile);