import { html, LitElement } from "lit";
import { customElement, state } from "lit/decorators.js";

interface Session {
  id: string;
  title: string;
  date: string;
  pinned: boolean;
}

@customElement("jae-session-sidebar")
export class JaeSessionSidebar extends LitElement {
  @state() private _sessions: Session[] = [];
  @state() private _activeId = "";

  protected override createRenderRoot() { return this; }

  override connectedCallback() {
    super.connectedCallback();
    this.refresh();
  }

  refresh() {
    try {
      const raw = localStorage.getItem("jae-sessions");
      if (raw) this._sessions = JSON.parse(raw);
    } catch {}
    this.requestUpdate();
  }

  setActive(id: string) {
    this._activeId = id;
    this.requestUpdate();
  }

  addSession(s: Session) {
    const exists = this._sessions.find(x => x.id === s.id);
    if (exists) {
      exists.title = s.title || exists.title;
      exists.date = s.date;
    } else {
      this._sessions.unshift(s);
    }
    this._save();
    this.requestUpdate();
  }

  private _save() {
    localStorage.setItem("jae-sessions", JSON.stringify(this._sessions));
  }

  private _pin(id: string) {
    const s = this._sessions.find(x => x.id === id);
    if (s) { s.pinned = !s.pinned; this._save(); this.requestUpdate(); }
  }

  private _delete(id: string) {
    this._sessions = this._sessions.filter(x => x.id !== id);
    this._save();
    this.dispatchEvent(new CustomEvent("session-delete", { detail: id, bubbles: true, composed: true }));
    this.requestUpdate();
  }

  private _select(id: string) {
    this._activeId = id;
    this.dispatchEvent(new CustomEvent("session-select", { detail: id, bubbles: true, composed: true }));
    this.requestUpdate();
  }

  private get _sorted() {
    const pinned = this._sessions.filter(s => s.pinned);
    const unpinned = this._sessions.filter(s => !s.pinned);
    return [...pinned, ...unpinned];
  }

  override render() {
    const items = this._sorted;
    const MAX_VISIBLE = 6;
    const needsScroll = items.length > MAX_VISIBLE;
    const maxH = needsScroll ? `${MAX_VISIBLE * 44}px` : "auto";

    return html`
      <div class="flex flex-col h-full">
        <div class="flex items-center justify-between px-3 py-2.5 border-b border-border/30 shrink-0">
          <span class="text-[11px] font-semibold text-muted-foreground uppercase tracking-widest">Chats</span>
          <button @click=${() => this.dispatchEvent(new CustomEvent("new-session", { bubbles: true, composed: true }))}
            class="w-6 h-6 flex items-center justify-center rounded-md hover:bg-secondary/60 text-muted-foreground hover:text-foreground transition-all duration-200"
            title="New chat">+</button>
        </div>
        <div class="flex-1 jae-sidebar overflow-y-auto py-1" style="max-height: ${maxH}">
          ${items.length === 0 ? html`
            <div class="px-3 py-8 text-center text-[11px] text-muted-foreground/50">No conversations yet</div>
          ` : ""}
          ${items.map(s => html`
            <div class="group flex items-center gap-2 px-2 py-2 mx-1 rounded-lg cursor-pointer transition-all duration-200
              ${s.id === this._activeId ? "bg-primary/10 border-l-2 border-primary" : "hover:bg-secondary/30"}"
              @click=${() => this._select(s.id)}>
              ${s.pinned ? html`<span class="text-[10px] text-amber-400 shrink-0">\u{1F4CC}</span>` : ""}
              <div class="flex-1 min-w-0">
                <div class="text-xs font-medium text-foreground/90 truncate">${s.title || "New chat"}</div>
                <div class="text-[10px] text-muted-foreground/60">${s.date}</div>
              </div>
              <div class="flex gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity duration-200 shrink-0">
                <button @click=${(e: Event) => { e.stopPropagation(); this._pin(s.id); }}
                  class="w-5 h-5 flex items-center justify-center rounded text-[10px] hover:bg-secondary/60 transition-colors"
                  title="${s.pinned ? "Unpin" : "Pin"}">${s.pinned ? "\u{1F4CC}" : "\u{1F4CC}"}</button>
                <button @click=${(e: Event) => { e.stopPropagation(); this._delete(s.id); }}
                  class="w-5 h-5 flex items-center justify-center rounded text-[10px] hover:bg-red-500/20 text-red-400 transition-colors"
                  title="Delete">\u2715</button>
              </div>
            </div>
          `)}
        </div>
      </div>`;
  }
}
