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

export interface Skill {
  id: string;
  name: string;
  description: string;
  emoji: string;
  category: string;
  enabled: boolean;
  builtin: boolean;
}

const DEFAULT_SKILLS: Skill[] = [
  { id: "bash", name: "Shell Commands", description: "Execute bash/terminal commands", emoji: "💻", category: "Core", enabled: true, builtin: true },
  { id: "browser", name: "Web Browser", description: "Browse and interact with websites", emoji: "🌐", category: "Core", enabled: true, builtin: true },
  { id: "web_search", name: "Web Search", description: "Search the internet for information", emoji: "🔍", category: "Core", enabled: true, builtin: true },
  { id: "javascript_repl", name: "JavaScript REPL", description: "Run JS code and create artifacts", emoji: "⚡", category: "Core", enabled: true, builtin: true },
  { id: "image_gen", name: "Image Generation", description: "Generate images with Venice AI", emoji: "🎨", category: "Creative", enabled: true, builtin: false },
  { id: "tts", name: "Text to Speech", description: "Convert text to spoken audio", emoji: "🔊", category: "Creative", enabled: true, builtin: false },
  { id: "memory", name: "Memory", description: "Save and recall information", emoji: "🧠", category: "Intelligence", enabled: true, builtin: false },
  { id: "code_analysis", name: "Code Analysis", description: "Analyse and review code quality", emoji: "🔬", category: "Developer", enabled: true, builtin: false },
  { id: "git_ops", name: "Git Operations", description: "Commit, push, branch management", emoji: "🔀", category: "Developer", enabled: false, builtin: false },
  { id: "doc_gen", name: "Doc Generator", description: "Generate README, API docs from code", emoji: "📝", category: "Developer", enabled: false, builtin: false },
  { id: "crypto_tracker", name: "Crypto Tracker", description: "Real-time token prices and charts", emoji: "💰", category: "Finance", enabled: true, builtin: false },
  { id: "chart_analysis", name: "Chart Analysis", description: "Technical analysis with indicators", emoji: "📈", category: "Finance", enabled: false, builtin: false },
  { id: "podcast", name: "Podcast Mode", description: "AI hosts discuss topics with voices", emoji: "🎧", category: "Creative", enabled: false, builtin: false },
  { id: "rag", name: "RAG Pipeline", description: "Query documents with citations", emoji: "📚", category: "Intelligence", enabled: false, builtin: false },
  { id: "mcp", name: "MCP Servers", description: "Connect to external APIs via MCP", emoji: "🔌", category: "Integration", enabled: false, builtin: false },
  { id: "sub_agents", name: "Sub-Agents", description: "Delegate to specialised agents", emoji: "🤖", category: "Intelligence", enabled: false, builtin: false },
];

@customElement("jae-marketplace")
export class JaeMarketplace extends LitElement {
  @state() private open = false;
  @state() private skills: Skill[] = [];
  @state() private filterCat = "All";

  protected override createRenderRoot() { return this; }

  override connectedCallback() {
    super.connectedCallback();
    const saved = localStorage.getItem("jae-marketplace-skills");
    if (saved) {
      try { this.skills = JSON.parse(saved); } catch { this.skills = [...DEFAULT_SKILLS]; }
    } else {
      this.skills = [...DEFAULT_SKILLS];
    }
  }

  toggle() { this.open = !this.open; this.requestUpdate(); }
  show() { this.open = true; this.requestUpdate(); }
  hide() { this.open = false; this.requestUpdate(); }

  isEnabled(id: string): boolean {
    return this.skills.find(s => s.id === id)?.enabled ?? false;
  }

  getEnabledSkills(): Skill[] {
    return this.skills.filter(s => s.enabled);
  }

  private _toggle(id: string) {
    this.skills = this.skills.map(s =>
      s.id === id && !s.builtin ? { ...s, enabled: !s.enabled } : s
    );
    localStorage.setItem("jae-marketplace-skills", JSON.stringify(this.skills));
    this.dispatchEvent(new CustomEvent("skills-change", {
      detail: this.getEnabledSkills(),
      bubbles: true,
      composed: true,
    }));
    this.requestUpdate();
  }

  private get categories(): string[] {
    return ["All", ...new Set(this.skills.map(s => s.category))];
  }

  private get filtered(): Skill[] {
    if (this.filterCat === "All") return this.skills;
    return this.skills.filter(s => s.category === this.filterCat);
  }

  override render() {
    return html`
      <button @click=${() => this.toggle()}
        class="flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-[11px] font-medium transition-all duration-300"
        style="background:rgba(255,255,255,0.04);border:1px solid rgba(255,255,255,0.08);color:var(--color-card-foreground, hsl(0 0% 90%))"
        @mouseenter=${(e: Event) => (e.currentTarget as HTMLElement).style.background = "rgba(255,255,255,0.08)"}
        @mouseleave=${(e: Event) => (e.currentTarget as HTMLElement).style.background = "rgba(255,255,255,0.04)"}>
        <span>🛒</span> Marketplace
      </button>

      ${this.open ? html`
        <div class="fixed inset-0 z-50" @click=${(e: Event) => { if (e.target === e.currentTarget) this.hide(); }}
          style="background:rgba(0,0,0,0.5);backdrop-filter:blur(4px)">
          <div class="fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[520px] max-h-[70vh] rounded-2xl border shadow-2xl jae-scale-in overflow-hidden flex flex-col"
            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%))">
            <div class="px-5 py-4 border-b flex items-center justify-between shrink-0" style="border-color:rgba(255,255,255,0.08)">
              <div>
                <h2 class="text-base font-bold">🛒 Skills Marketplace</h2>
                <p class="text-[11px] mt-0.5" style="color:var(--color-muted-foreground, hsl(0 0% 60%))">Toggle capabilities on or off</p>
              </div>
              <button @click=${() => this.hide()} class="w-7 h-7 flex items-center justify-center rounded-lg hover:bg-secondary/60 transition-colors" style="color:var(--color-muted-foreground, hsl(0 0% 55%))">✕</button>
            </div>
            <div class="flex gap-1 px-4 py-2 overflow-x-auto shrink-0" style="border-bottom:1px solid rgba(255,255,255,0.05)">
              ${this.categories.map(cat => html`
                <button @click=${() => { this.filterCat = cat; this.requestUpdate(); }}
                  class="px-2.5 py-1 rounded-full text-[10px] font-medium whitespace-nowrap transition-all duration-200"
                  style="background:${cat === this.filterCat ? "rgba(255,255,255,0.1)" : "transparent"};color:${cat === this.filterCat ? "var(--color-card-foreground, hsl(0 0% 95%))" : "var(--color-muted-foreground, hsl(0 0% 55%))"};border:1px solid ${cat === this.filterCat ? "rgba(255,255,255,0.15)" : "transparent"}">
                  ${cat}
                </button>
              `)}
            </div>
            <div class="flex-1 overflow-y-auto p-4 grid grid-cols-2 gap-2">
              ${this.filtered.map(skill => html`
                <div class="flex items-start gap-3 p-3 rounded-xl transition-all duration-200"
                  style="background:${skill.enabled ? "rgba(255,255,255,0.05)" : "transparent"};border:1px solid ${skill.enabled ? "rgba(255,255,255,0.1)" : "rgba(255,255,255,0.04)"}">
                  <span class="text-xl mt-0.5">${skill.emoji}</span>
                  <div class="flex-1 min-w-0">
                    <div class="flex items-center gap-2">
                      <span class="text-xs font-semibold">${skill.name}</span>
                      ${skill.builtin ? html`<span class="text-[8px] px-1 py-0.5 rounded" style="background:rgba(96,165,250,0.15);color:rgb(96,165,250)">CORE</span>` : nothing}
                    </div>
                    <p class="text-[10px] mt-0.5" style="color:var(--color-muted-foreground, hsl(0 0% 55%))">${skill.description}</p>
                  </div>
                  <button @click=${() => this._toggle(skill.id)}
                    class="shrink-0 w-9 h-5 rounded-full transition-all duration-300 relative mt-1"
                    style="background:${skill.enabled ? "rgb(34,197,94)" : "rgba(255,255,255,0.1)"};cursor:${skill.builtin ? "not-allowed" : "pointer"};opacity:${skill.builtin ? "0.5" : "1"}">
                    <div class="absolute top-0.5 w-4 h-4 rounded-full transition-all duration-300"
                      style="background:white;left:${skill.enabled ? "18px" : "2px"}"></div>
                  </button>
                </div>
              `)}
            </div>
            <div class="px-4 py-3 border-t shrink-0 flex items-center justify-between" style="border-color:rgba(255,255,255,0.08)">
              <span class="text-[10px]" style="color:var(--color-muted-foreground, hsl(0 0% 55%))">${this.skills.filter(s => s.enabled).length} of ${this.skills.length} skills active</span>
              <span class="text-[10px]" style="color:var(--color-muted-foreground, hsl(0 0% 45%))">Core skills cannot be disabled</span>
            </div>
          </div>
        </div>
      ` : nothing}
    `;
  }
}
