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

export interface SlashCommand {
  command: string;
  label: string;
  description: string;
  category: string;
  emoji: string;
}

const ALL_COMMANDS: SlashCommand[] = [
  // Tools
  { command: "/search", label: "Web Search", description: "Search the web for information", category: "Tools", emoji: "\ud83d\udd0d" },
  { command: "/image", label: "Generate Image", description: "Create an image with AI", category: "Tools", emoji: "\ud83c\udfa8" },
  { command: "/browse", label: "Browse URL", description: "Open and read a webpage", category: "Tools", emoji: "\ud83c\udf10" },
  { command: "/bash", label: "Run Command", description: "Execute a shell command", category: "Tools", emoji: "\ud83d\udcbb" },
  { command: "/code", label: "Write Code", description: "Generate or edit code", category: "Tools", emoji: "\ud83d\udcc4" },
  { command: "/repl", label: "JavaScript REPL", description: "Run JavaScript in sandbox", category: "Tools", emoji: "\u26a1" },
  // Memory
  { command: "/memory", label: "Memory Manager", description: "View and manage memories", category: "Memory", emoji: "\ud83e\udde0" },
  { command: "/remember", label: "Save Memory", description: "Save information for later", category: "Memory", emoji: "\ud83d\udcbe" },
  { command: "/recall", label: "Recall Memory", description: "Search saved memories", category: "Memory", emoji: "\ud83d\udd0e" },
  { command: "/forget", label: "Forget Memory", description: "Remove a saved memory", category: "Memory", emoji: "\ud83d\uddd1\ufe0f" },
  // Personas
  { command: "/persona", label: "Switch Persona", description: "Change JAE's personality", category: "Personas", emoji: "\ud83c\udfad" },
  { command: "/dev", label: "Senior Developer", description: "Switch to dev persona", category: "Personas", emoji: "\ud83d\udc68\u200d\ud83d\udcbb" },
  { command: "/writer", label: "Creative Writer", description: "Switch to writer persona", category: "Personas", emoji: "\u270d\ufe0f" },
  { command: "/data", label: "Data Scientist", description: "Switch to data scientist", category: "Personas", emoji: "\ud83d\udcca" },
  { command: "/security", label: "Red Team", description: "Switch to cybersec persona", category: "Personas", emoji: "\ud83d\udd12" },
  { command: "/tutor", label: "Tutor", description: "Switch to teacher persona", category: "Personas", emoji: "\ud83c\udf93" },
  { command: "/startup", label: "Startup Advisor", description: "Switch to business persona", category: "Personas", emoji: "\ud83d\ude80" },
  // Navigation
  { command: "/model", label: "Switch Model", description: "Open model selector", category: "Navigation", emoji: "\ud83e\udd16" },
  { command: "/settings", label: "Settings", description: "Open settings panel", category: "Navigation", emoji: "\u2699\ufe0f" },
  { command: "/history", label: "Chat History", description: "Browse past sessions", category: "Navigation", emoji: "\ud83d\udcda" },
  { command: "/new", label: "New Chat", description: "Start a fresh conversation", category: "Navigation", emoji: "\u2795" },
  { command: "/export", label: "Export Chat", description: "Download as Markdown", category: "Navigation", emoji: "\ud83d\udce4" },
  { command: "/clear", label: "Clear Chat", description: "Clear current conversation", category: "Navigation", emoji: "\ud83e\uddf9" },
  // Crypto
  { command: "/price", label: "Token Prices", description: "Show VVV and DIEM prices", category: "Crypto", emoji: "\ud83d\udcb0" },
  { command: "/chart", label: "Price Chart", description: "Show token price chart", category: "Crypto", emoji: "\ud83d\udcc8" },
  // Utilities
  { command: "/help", label: "Help", description: "Show all commands", category: "Utilities", emoji: "\u2753" },
  { command: "/shortcuts", label: "Keyboard Shortcuts", description: "Show keyboard shortcuts", category: "Utilities", emoji: "\u2328\ufe0f" },
  { command: "/voice", label: "Text to Speech", description: "Read response aloud", category: "Utilities", emoji: "\ud83d\udd0a" },
];

@customElement("jae-slash-commands")
export class JaeSlashCommands extends LitElement {
  @state() private open = false;
  @state() private filter = "";
  @state() private selectedIndex = 0;

  protected override createRenderRoot() { return this; }

  show(initialFilter = "") {
    this.filter = initialFilter;
    this.selectedIndex = 0;
    this.open = true;
    this.requestUpdate();
  }

  hide() {
    this.open = false;
    this.filter = "";
    this.requestUpdate();
  }

  updateFilter(text: string) {
    if (text.startsWith("/")) {
      this.filter = text.slice(1).toLowerCase();
      this.selectedIndex = 0;
      if (!this.open) this.open = true;
      this.requestUpdate();
    } else if (this.open && !text.startsWith("/")) {
      this.hide();
    }
  }

  private get filtered(): SlashCommand[] {
    if (!this.filter) return ALL_COMMANDS;
    const q = this.filter.toLowerCase();
    return ALL_COMMANDS.filter(c =>
      c.command.slice(1).includes(q) ||
      c.label.toLowerCase().includes(q) ||
      c.description.toLowerCase().includes(q) ||
      c.category.toLowerCase().includes(q)
    );
  }

  handleKeydown(e: KeyboardEvent): boolean {
    if (!this.open) return false;
    const items = this.filtered;
    if (e.key === "ArrowDown") {
      e.preventDefault();
      this.selectedIndex = Math.min(this.selectedIndex + 1, items.length - 1);
      this.requestUpdate();
      return true;
    }
    if (e.key === "ArrowUp") {
      e.preventDefault();
      this.selectedIndex = Math.max(this.selectedIndex - 1, 0);
      this.requestUpdate();
      return true;
    }
    if (e.key === "Enter" || e.key === "Tab") {
      e.preventDefault();
      if (items[this.selectedIndex]) this._select(items[this.selectedIndex]);
      return true;
    }
    if (e.key === "Escape") {
      this.hide();
      return true;
    }
    return false;
  }

  private _select(cmd: SlashCommand) {
    this.dispatchEvent(new CustomEvent("command", {
      detail: cmd,
      bubbles: true,
      composed: true,
    }));
    this.hide();
  }

  override render() {
    if (!this.open) return nothing;
    const items = this.filtered;
    if (items.length === 0) return nothing;

    // Group by category
    const groups = new Map<string, SlashCommand[]>();
    for (const cmd of items) {
      const list = groups.get(cmd.category) || [];
      list.push(cmd);
      groups.set(cmd.category, list);
    }

    let globalIdx = 0;

    return html`
      <div class="absolute bottom-full left-0 right-0 mb-1 mx-4 z-50">
        <div class="rounded-xl border shadow-2xl overflow-hidden jae-scale-in"
          style="background:var(--color-card, hsl(240 6% 10%));border-color:rgba(255,255,255,0.1);color:var(--color-card-foreground, hsl(0 0% 95%));max-height:340px;overflow-y:auto">
          ${Array.from(groups.entries()).map(([cat, cmds]) => html`
            <div class="px-3 pt-2 pb-1">
              <span class="text-[10px] font-semibold uppercase tracking-widest" style="color:var(--color-muted-foreground, hsl(0 0% 55%))">${cat}</span>
            </div>
            ${cmds.map(cmd => {
              const idx = globalIdx++;
              const isSelected = idx === this.selectedIndex;
              return html`
                <button @click=${() => this._select(cmd)}
                  class="flex items-center gap-3 w-full px-3 py-2 text-left transition-all duration-150"
                  style="background:${isSelected ? "rgba(255,255,255,0.08)" : "transparent"}"
                  @mouseenter=${() => { this.selectedIndex = idx; this.requestUpdate(); }}>
                  <span class="text-base w-6 text-center">${cmd.emoji}</span>
                  <div class="flex-1 min-w-0">
                    <div class="flex items-center gap-2">
                      <span class="text-xs font-semibold" style="color:var(--color-card-foreground, hsl(0 0% 95%))">${cmd.label}</span>
                      <span class="text-[10px] font-mono" style="color:var(--color-muted-foreground, hsl(0 0% 50%))">${cmd.command}</span>
                    </div>
                    <p class="text-[10px] truncate" style="color:var(--color-muted-foreground, hsl(0 0% 55%))">${cmd.description}</p>
                  </div>
                </button>
              `;
            })}
          `)}
        </div>
      </div>
    `;
  }
}
