import { LitElement, html, css } from '/vendor/lit/lit.min.js';

export class SearchFilter extends LitElement {
  static properties = {
    query: { type: String, reflect: true },
    placeholder: { type: String },
    count: { type: Number },
    total: { type: Number },
  };

  static styles = css`
    :host { display: block; }
    .filter-bar {
      display: flex;
      align-items: center;
      gap: 8px;
      padding: 0 var(--grid-padding, 16px);
      height: 40px;
    }
    .filter-input {
      flex: 1;
      max-width: 320px;
      padding: 6px 12px;
      font-size: 13px;
      background: var(--bg-tile, #10131C);
      color: var(--text, #F0F6FF);
      border: 1px solid var(--border, #2A3040);
      border-radius: 6px;
      outline: none;
      transition: border-color 150ms;
    }
    .filter-input:focus {
      border-color: var(--accent, #00D9F5);
    }
    .filter-input::placeholder {
      color: var(--text-muted, #8E95A3);
    }
    .filter-count {
      font-size: 12px;
      color: var(--text-muted, #8E95A3);
    }
    .filter-clear {
      background: none;
      border: none;
      color: var(--text-muted, #8E95A3);
      cursor: pointer;
      padding: 4px;
      font-size: 12px;
    }
    .filter-clear:hover { color: var(--text, #F0F6FF); }
  `;

  constructor() {
    super();
    this.query = '';
    this.placeholder = 'Filter sessions...';
    this.count = 0;
    this.total = 0;
  }

  _onInput(e) {
    this.query = e.target.value;
    this.dispatchEvent(new CustomEvent('filter-change', {
      bubbles: true, composed: true,
      detail: { query: this.query },
    }));
  }

  _onClear() {
    this.query = '';
    this.dispatchEvent(new CustomEvent('filter-change', {
      bubbles: true, composed: true,
      detail: { query: '' },
    }));
  }

  _onKeydown(e) {
    if (e.key === 'Escape') {
      this._onClear();
      e.target.blur();
    }
  }

  render() {
    const showCount = this.query && this.query.length > 0;
    return html`
      <div class="filter-bar">
        <input
          class="filter-input"
          type="text"
          .value=${this.query}
          placeholder=${this.placeholder}
          @input=${this._onInput}
          @keydown=${this._onKeydown}
          aria-label="Filter sessions"
        />
        ${showCount ? html`
          <span class="filter-count">${this.count} of ${this.total}</span>
          <button class="filter-clear" @click=${this._onClear} aria-label="Clear filter">&times;</button>
        ` : html``}
      </div>
    `;
  }
}

customElements.define('search-filter', SearchFilter);