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

/**
 * <sidebar-item> - Session entry in the expanded-view sidebar.
 *
 * Properties:
 *   session:           Object  - session data
 *   active:            Boolean - whether this is the currently viewed session
 *   multiDevice:       Boolean - multi-device enabled
 *   showDeviceBadges:  Boolean - show device name badges
 *   activityIndicator: String  - 'none' | 'glow' | 'dot' | 'both'
 *
 * Events:
 *   sidebar-select  { name, remoteId }            - Session clicked
 *   sidebar-options { name, remoteId, sessionKey, rect } - Kebab menu clicked
 */
export class SidebarItem extends LitElement {
  static properties = {
    session:           { type: Object },
    active:            { type: Boolean, reflect: true },
    multiDevice:       { type: Boolean, attribute: 'multi-device' },
    showDeviceBadges:  { type: Boolean, attribute: 'show-device-badges' },
    activityIndicator: { type: String, attribute: 'activity-indicator' },
  };

  // Light DOM — existing CSS applies
  createRenderRoot() { return this; }

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

  get _name() { return this.session.name || ''; }
  get _sessionKey() { return this.session.sessionKey || this._name; }
  get _remoteId() { return this.session.remoteId ?? null; }

  get _isBell() {
    const unseen = this.session.bell && this.session.bell.unseen_count;
    return unseen && unseen > 0;
  }

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

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

  get _snapshotHtml() {
    const snapshot = this.session.snapshot || '';
    const allLines = snapshot.split('\n');
    while (allLines.length > 0 && allLines[allLines.length - 1].trim() === '') {
      allLines.pop();
    }
    return ansiToHtml(allLines.slice(-20).join('\n'));
  }

  _onClick(e) {
    if (e.target.closest('.tile-options-btn')) return;
    this.dispatchEvent(new CustomEvent('sidebar-select', {
      bubbles: true, composed: true,
      detail: { name: this._name, remoteId: this._remoteId },
    }));
  }

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

  render() {
    const name = this._name;
    const remoteIdStr = this._remoteId != null ? String(this._remoteId) : '';
    const showBadge = this.multiDevice && this.session.deviceName && this.showDeviceBadges;

    return html`
      <article
        class=${this._classes}
        data-session=${name}
        data-session-key=${this._sessionKey}
        data-remote-id=${remoteIdStr}
        tabindex="0"
        role="listitem"
        @click=${this._onClick}
      >
        <div class="sidebar-item-header">
          <span class="sidebar-item-name">${name}</span>
          ${showBadge
            ? html`<span class="device-badge">${this.session.deviceName}</span>`
            : nothing}
          <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="sidebar-item-body">
          <pre>${unsafeHTML(this._snapshotHtml)}</pre>
        </div>
      </article>
    `;
  }
}

customElements.define('sidebar-item', SidebarItem);