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

/**
 * <bottom-sheet-switcher> - Mobile session-switching overlay.
 *
 * Properties:
 *   sessions:        Array   - session list (will be sorted by priority internally)
 *   viewingSession:  String  - name of currently viewed session
 *   viewingRemoteId: String  - remoteId of currently viewed session
 *   open:            Boolean - whether the sheet is visible
 *
 * Events:
 *   sheet-select { name, remoteId } - Session selected
 *   sheet-close                     - Backdrop/handle dismissed
 */
export class BottomSheetSwitcher extends LitElement {
  static properties = {
    sessions:        { type: Array },
    viewingSession:  { type: String, attribute: 'viewing-session' },
    viewingRemoteId: { type: String, attribute: 'viewing-remote-id' },
    open:            { type: Boolean, reflect: true },
  };

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

  constructor() {
    super();
    this.sessions = [];
    this.viewingSession = '';
    this.viewingRemoteId = '';
    this.open = false;
  }

  _onBackdropClick() {
    this.dispatchEvent(new CustomEvent('sheet-close', { bubbles: true, composed: true }));
  }

  _onItemClick(name, remoteId) {
    if (name !== this.viewingSession || (remoteId || '') !== (this.viewingRemoteId || '')) {
      this.dispatchEvent(new CustomEvent('sheet-select', {
        bubbles: true, composed: true,
        detail: { name, remoteId: remoteId || '' },
      }));
    }
    this.dispatchEvent(new CustomEvent('sheet-close', { bubbles: true, composed: true }));
  }

  render() {
    const sorted = sortByPriority(this.sessions || []);
    return html`
      <div class="bottom-sheet__backdrop" @click=${this._onBackdropClick}></div>
      <div class="bottom-sheet__panel">
        <div class="bottom-sheet__handle" aria-hidden="true"></div>
        <ul class="bottom-sheet__list" role="listbox" aria-label="Sessions">
          ${sorted.map(s => {
            const hasBell = s.bell && s.bell.unseen_count > 0 &&
              (s.bell.seen_at === null || s.bell.last_fired_at > s.bell.seen_at);
            const isActive = s.name === this.viewingSession &&
              (s.remoteId ?? '') === (this.viewingRemoteId ?? '');
            const name = s.name || '';
            const remoteId = s.remoteId ?? '';
            return html`
              <li class="sheet-item ${isActive ? 'sheet-item--active' : ''}"
                  role="option"
                  @click=${() => this._onItemClick(name, remoteId)}>
                <span class="sheet-item__name">${name}</span>
                ${hasBell ? html`<span class="sheet-item__bell">${unsafeHTML(icons.bell)}</span>` : nothing}
                <span class="sheet-item__time">${formatTimestamp(s.bell && s.bell.last_fired_at)}</span>
              </li>`;
          })}
        </ul>
      </div>
    `;
  }
}

customElements.define('bottom-sheet-switcher', BottomSheetSwitcher);