# AI prompt selector

> Prompt input with dismissible model promo banner, inline slash commands, removable file chips, model and effort menus, and stream stop.

- Kind: block · Category: AI · Interactivity: script
- Install: `npx shadcn@latest add @haze/ai-prompt`
- File: `src/components/haze/blocks/ai-prompt.astro`
- npm dependencies: @lucide/astro
- Registry dependencies: @haze/utils
- Docs page: https://hazeui.com/blocks/ai-prompt

## Use when
- Launching a workspace prompt bar that highlights a featured model alongside command shortcuts
- Giving users separate model and reasoning effort controls with file attachments in one composer
- Prototyping an interactive AI prompt card with simulated streaming and stop controls

## Avoid when
- You need a grounded web search trace with live source citations; use ai-input-search instead
- You only need a compact model and effort pill without a full composer; use ai-model-selector instead

## Alternatives
- [ai-composer](https://hazeui.com/blocks/ai-composer.md)
- [ai-input-search](https://hazeui.com/blocks/ai-input-search.md)
- [ai-model-selector](https://hazeui.com/blocks/ai-model-selector.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` | "haze-ai-prompt" | no | Unique prefix for labels, menus and aria-controls references. |
| heading | `string` | "AI prompt selector" | no | Screen-reader section heading for the prompt composer. |
| promoText | `string` | "Solstice 5.1 is free this weekend" | no | Announcement copy shown inside the top promo strip. |
| promoModel | `string` | "Solstice 5.1" | no | Model selected automatically when activating the Try it button. |
| placeholder | `string` | "Ask anything. Type / for commands" | no | Placeholder copy inside the auto-growing textarea. |
| models | `{ name: string; note: string }[]` | 4 demo models | no | Models listed in the composer model menu. |
| efforts | `string[]` | ["Low", "Medium", "High", "Max"] | no | Reasoning effort levels available in the effort picker. |
| commands | `{ name: string; description: string }[]` | 4 slash commands | no | Commands shown when typing / or opening the slash menu. |
| class | `string` |  | no | Extra classes on the outer section. |

## Accessibility
- Slash command, model and effort trays wire aria-expanded and aria-controls to their triggers and close cleanly on Escape.
- Model switches, file attachments, promo dismissal and streaming completion announce through a polite role="status" element.
- Key /: Open and filter the inline slash-command menu inside the prompt field
- Key Escape: Dismiss any open command, model or effort tray
- Key Tab / Enter: Navigate toolbar controls, pick options, remove chips or submit the prompt

## Agent prompts

### Install and use

Install the Haze UI block "AI prompt selector" with `npx shadcn@latest add @haze/ai-prompt`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "https://hazeui.com/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import AiPrompt from "@/components/haze/blocks/ai-prompt.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: https://hazeui.com/blocks/ai-prompt.md

### Customize with real content

Adapt the Haze ai-prompt block for our product. Replace the demo values of these props with our real content: id, heading, promoText, promoModel, placeholder, models, efforts, commands, class. Keep the layout, the heading level rules and these accessibility details: Slash command, model and effort trays wire aria-expanded and aria-controls to their triggers and close cleanly on Escape. Model switches, file attachments, promo dismissal and streaming completion announce through a polite role="status" element. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using ai-prompt, check it fits: use it when launching a workspace prompt bar that highlights a featured model alongside command shortcuts; giving users separate model and reasoning effort controls with file attachments in one composer; prototyping an interactive ai prompt card with simulated streaming and stop controls. Avoid it when you need a grounded web search trace with live source citations; use ai-input-search instead; you only need a compact model and effort pill without a full composer; use ai-model-selector instead. Alternatives: @haze/ai-composer, @haze/ai-input-search, @haze/ai-model-selector.

## Example requests that should lead here
- Build an AI prompt input with a dismissible featured model banner, slash commands, file chips, model and effort pickers
- Add a prompt selector card that streams a demo reply and switches the send button to stop while generating

## Source

```astro
---
import { ArrowUp, Check, ChevronDown, Plus, Square } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";

interface ModelOption {
  name: string;
  note: string;
}

interface SlashCommand {
  name: string;
  description: string;
}

interface Props {
  id?: string;
  heading?: string;
  promoText?: string;
  promoModel?: string;
  placeholder?: string;
  models?: ModelOption[];
  efforts?: string[];
  commands?: SlashCommand[];
  class?: string;
}

const {
  id = "haze-ai-prompt",
  heading = "AI prompt selector",
  promoText = "Solstice 5.1 is free this weekend",
  promoModel = "Solstice 5.1",
  placeholder = "Ask anything. Type / for commands",
  models = [
    { name: "Opus 5.5", note: "Most capable, for complex work" },
    { name: "Sonnet 5.5", note: "Balanced coding and writing" },
    { name: "Solstice 5.1", note: "Weekend preview model" },
    { name: "Flash 4.0", note: "Fast lightweight replies" },
  ],
  efforts = ["Low", "Medium", "High", "Max"],
  commands = [
    { name: "/summarize", description: "Distill long notes into key decisions" },
    { name: "/compare", description: "Contrast two options side by side" },
    { name: "/audit", description: "Check code or copy for edge cases" },
    { name: "/explain", description: "Break down a concept step by step" },
  ],
  class: className,
} = Astro.props;

const defaultModel = models[0]?.name ?? "Opus 5.5";
const defaultEffort = efforts[2] ?? efforts[efforts.length - 1] ?? "High";
const defaultEffortBars = Math.max(1, efforts.indexOf(defaultEffort) + 1);
---

<section
  aria-labelledby={`${id}-title`}
  data-haze-ai-prompt
  data-promo-model={promoModel}
  data-efforts={JSON.stringify(efforts)}
  class={cn("bg-background px-4 py-10 sm:px-6 sm:py-14", className)}
>
  <h2 id={`${id}-title`} class="sr-only">{heading}</h2>

  <div class="mx-auto max-w-xl space-y-3">
    <div
      data-ap-shell
      class="rounded-2xl border border-border bg-muted/40 p-1.5 shadow-lift transition-[color,background-color,border-color,box-shadow] duration-150 ease-snappy has-[:is(input,textarea):focus-visible]:border-ring has-[:is(input,textarea):focus-visible]:ring-3 has-[:is(input,textarea):focus-visible]:ring-ring/24 data-[dragging=true]:border-foreground"
    >
      <div
        data-ap-promo
        class="flex flex-wrap items-center justify-between gap-2 px-3 py-2"
      >
        <div class="flex min-w-0 items-center gap-2.5">
          <svg
            viewBox="0 0 20 20"
            fill="none"
            class="size-4 shrink-0 text-muted-foreground"
            aria-hidden="true"
          >
            <path
              d="M10 2v16M2 10h16M4.34 4.34l11.32 11.32M15.66 4.34L4.34 15.66"
              stroke="currentColor"
              stroke-width="1.75"
              stroke-linecap="round"
            />
          </svg>
          <p class="wrap-anywhere text-sm/5 text-muted-foreground">{promoText}</p>
        </div>

        <button
          type="button"
          data-ap-try
          class="inline-flex min-h-8 shrink-0 cursor-pointer items-center rounded-lg px-2 text-sm font-medium text-foreground transition-colors duration-150 ease-snappy hover:bg-accent focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring active:scale-[0.98] active:duration-75"
        >
          Try it
        </button>
      </div>

      <form
        data-ap-form
        class="rounded-xl border border-border bg-card p-3.5 shadow-key"
      >
        <div data-ap-files hidden class="mb-2.5 flex flex-wrap gap-1.5"></div>

        <label for={`${id}-input`} class="sr-only">Prompt</label>
        <textarea
          id={`${id}-input`}
          data-ap-input
          rows="2"
          placeholder={placeholder}
          class="max-h-44 w-full resize-none bg-transparent px-1 py-0.5 text-[0.9375rem]/6 text-foreground placeholder:text-muted-foreground outline-hidden"
        ></textarea>

        <div
          id={`${id}-cmd-menu`}
          data-ap-panel="cmd"
          hidden
          class="mt-2.5 rounded-xl border border-border bg-popover p-1.5 shadow-float"
        >
          <p class="px-2.5 py-1 text-xs font-medium text-muted-foreground">
            Commands
          </p>
          <ul role="list" class="grid gap-0.5">
            {
              commands.map((cmd) => (
                <li data-ap-cmd-item={cmd.name}>
                  <button
                    type="button"
                    data-ap-cmd-pick={cmd.name}
                    class="flex w-full cursor-pointer items-center justify-between gap-3 rounded-lg px-2.5 py-2 text-left text-sm/5 transition-colors duration-150 ease-snappy hover:bg-accent focus-visible:outline-2 focus-visible:outline-ring"
                  >
                    <span class="shrink-0 font-mono text-xs font-medium text-foreground">{cmd.name}</span>
                    <span class="min-w-0 truncate text-xs text-muted-foreground">{cmd.description}</span>
                  </button>
                </li>
              ))
            }
          </ul>
        </div>

        <div
          id={`${id}-model-menu`}
          data-ap-panel="model"
          hidden
          class="mt-2.5 rounded-xl border border-border bg-popover p-1.5 shadow-float"
        >
          <ul role="list" class="grid gap-0.5">
            {
              models.map((m) => (
                <li>
                  <button
                    type="button"
                    data-ap-model-option={m.name}
                    aria-pressed={m.name === defaultModel ? "true" : "false"}
                    class={cn(
                      "flex w-full cursor-pointer items-center justify-between gap-3 rounded-lg px-3 py-2 text-left transition-colors duration-150 ease-snappy hover:bg-accent focus-visible:outline-2 focus-visible:outline-ring",
                      m.name === defaultModel && "bg-accent/60"
                    )}
                  >
                    <span class="min-w-0">
                      <span class="block text-sm/5 font-medium text-foreground">{m.name}</span>
                      <span class="block truncate text-xs/4 text-muted-foreground">{m.note}</span>
                    </span>
                    <Check
                      data-ap-check
                      class={cn("size-4 shrink-0 text-foreground", m.name !== defaultModel && "opacity-0")}
                      aria-hidden="true"
                    />
                  </button>
                </li>
              ))
            }
          </ul>
        </div>

        <div
          id={`${id}-effort-menu`}
          data-ap-panel="effort"
          hidden
          class="mt-2.5 rounded-xl border border-border bg-popover p-1.5 shadow-float"
        >
          <div class="grid grid-cols-2 gap-1 sm:grid-cols-4">
            {
              efforts.map((level) => (
                <button
                  type="button"
                  data-ap-effort-option={level}
                  aria-pressed={level === defaultEffort ? "true" : "false"}
                  class={cn(
                    "flex min-h-8 cursor-pointer items-center justify-between gap-2 rounded-lg px-2.5 py-1.5 text-xs font-medium transition-colors duration-150 ease-snappy hover:bg-accent focus-visible:outline-2 focus-visible:outline-ring",
                    level === defaultEffort
                      ? "bg-accent text-foreground"
                      : "text-muted-foreground hover:text-foreground"
                  )}
                >
                  <span>{level}</span>
                  <Check
                    data-ap-check
                    class={cn("size-3.5 shrink-0 text-foreground", level !== defaultEffort && "opacity-0")}
                    aria-hidden="true"
                  />
                </button>
              ))
            }
          </div>
        </div>

        <div class="mt-3 flex flex-wrap items-center justify-between gap-2 pt-1">
          <div class="flex flex-wrap items-center gap-1.5">
            <button
              type="button"
              data-ap-attach
              aria-label="Attach file"
              class="inline-flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-full border border-border bg-transparent text-muted-foreground transition-colors duration-150 ease-snappy hover:border-border-strong hover:bg-accent hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring active:scale-95 active:duration-75"
            >
              <Plus class="size-4" aria-hidden="true" />
            </button>

            <button
              type="button"
              data-ap-toggle="model"
              aria-expanded="false"
              aria-controls={`${id}-model-menu`}
              class="inline-flex min-h-8 cursor-pointer items-center gap-1.5 rounded-lg px-2 py-1 text-sm font-medium text-foreground transition-colors duration-150 ease-snappy hover:bg-accent aria-expanded:bg-accent focus-visible:outline-2 focus-visible:outline-ring"
            >
              <svg
                viewBox="0 0 20 20"
                fill="none"
                class="size-4 shrink-0 text-muted-foreground"
                aria-hidden="true"
              >
                <path
                  d="M10 2v16M2 10h16M4.34 4.34l11.32 11.32M15.66 4.34L4.34 15.66"
                  stroke="currentColor"
                  stroke-width="1.75"
                  stroke-linecap="round"
                />
              </svg>
              <span data-ap-model-label>{defaultModel}</span>
              <ChevronDown class="size-3.5 text-muted-foreground" aria-hidden="true" />
            </button>

            <button
              type="button"
              data-ap-toggle="effort"
              aria-expanded="false"
              aria-controls={`${id}-effort-menu`}
              class="inline-flex min-h-8 cursor-pointer items-center gap-1.5 rounded-lg px-2 py-1 text-sm text-muted-foreground transition-colors duration-150 ease-snappy hover:bg-accent hover:text-foreground aria-expanded:bg-accent aria-expanded:text-foreground focus-visible:outline-2 focus-visible:outline-ring"
            >
              <svg
                data-ap-signal
                viewBox="0 0 16 14"
                fill="none"
                class="size-3.5 shrink-0"
                aria-hidden="true"
              >
                <rect
                  data-ap-sig-bar="1"
                  x="1"
                  y="9"
                  width="2.5"
                  height="4"
                  rx="1"
                  class={defaultEffortBars >= 1 ? "fill-current text-foreground" : "fill-current text-muted-foreground/30"}
                />
                <rect
                  data-ap-sig-bar="2"
                  x="5"
                  y="6.5"
                  width="2.5"
                  height="6.5"
                  rx="1"
                  class={defaultEffortBars >= 2 ? "fill-current text-foreground" : "fill-current text-muted-foreground/30"}
                />
                <rect
                  data-ap-sig-bar="3"
                  x="9"
                  y="4"
                  width="2.5"
                  height="9"
                  rx="1"
                  class={defaultEffortBars >= 3 ? "fill-current text-foreground" : "fill-current text-muted-foreground/30"}
                />
                <rect
                  data-ap-sig-bar="4"
                  x="13"
                  y="1.5"
                  width="2.5"
                  height="11.5"
                  rx="1"
                  class={defaultEffortBars >= 4 ? "fill-current text-foreground" : "fill-current text-muted-foreground/30"}
                />
              </svg>
              <span data-ap-effort-label>{defaultEffort}</span>
            </button>
          </div>

          <div class="flex shrink-0 items-center">
            <button
              type="submit"
              data-ap-send
              disabled
              aria-label="Send prompt"
              class="inline-flex size-8 cursor-pointer items-center justify-center rounded-full bg-primary text-primary-foreground transition-[background-color,color,opacity,scale] duration-150 ease-snappy hover:opacity-90 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring active:scale-95 disabled:cursor-not-allowed disabled:bg-muted disabled:text-muted-foreground"
            >
              <ArrowUp class="size-4" aria-hidden="true" />
            </button>

            <button
              type="button"
              data-ap-stop
              hidden
              aria-label="Stop response"
              class="inline-flex size-8 cursor-pointer items-center justify-center rounded-full bg-primary text-primary-foreground transition-[opacity,scale] duration-150 ease-snappy hover:opacity-90 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring active:scale-95"
            >
              <Square class="size-3 fill-current" aria-hidden="true" />
            </button>
          </div>
        </div>
      </form>
    </div>

    <div
      data-ap-reply
      hidden
      class="rounded-2xl border border-border bg-card px-4 py-3.5 text-sm/6 text-foreground shadow-key"
    >
      <div class="mb-1.5 flex flex-wrap items-center justify-between gap-2 text-xs/4 text-muted-foreground">
        <span data-ap-reply-meta class="font-medium text-foreground"></span>
        <span data-ap-reply-state>Streaming…</span>
      </div>
      <p data-ap-reply-body class="wrap-anywhere text-sm/6 text-muted-foreground"></p>
    </div>

    <p data-ap-status role="status" class="sr-only"></p>
  </div>
</section>

<script>
  function initAiPromptSelectors() {
    document.querySelectorAll<HTMLElement>("[data-haze-ai-prompt]").forEach((root) => {
      if (root.hasAttribute("data-enhanced")) return;
      root.setAttribute("data-enhanced", "");

      const shell = root.querySelector<HTMLElement>("[data-ap-shell]");
      const promo = root.querySelector<HTMLElement>("[data-ap-promo]");
      const tryBtn = root.querySelector<HTMLButtonElement>("[data-ap-try]");
      const form = root.querySelector<HTMLFormElement>("[data-ap-form]");
      const input = root.querySelector<HTMLTextAreaElement>("[data-ap-input]");
      const files = root.querySelector<HTMLElement>("[data-ap-files]");
      const attachBtn = root.querySelector<HTMLButtonElement>("[data-ap-attach]");
      const modelLabel = root.querySelector<HTMLElement>("[data-ap-model-label]");
      const effortLabel = root.querySelector<HTMLElement>("[data-ap-effort-label]");
      const sigBars = Array.from(root.querySelectorAll<SVGElement>("[data-ap-sig-bar]"));
      const sendBtn = root.querySelector<HTMLButtonElement>("[data-ap-send]");
      const stopBtn = root.querySelector<HTMLButtonElement>("[data-ap-stop]");
      const replyBox = root.querySelector<HTMLElement>("[data-ap-reply]");
      const replyMeta = root.querySelector<HTMLElement>("[data-ap-reply-meta]");
      const replyState = root.querySelector<HTMLElement>("[data-ap-reply-state]");
      const replyBody = root.querySelector<HTMLElement>("[data-ap-reply-body]");
      const status = root.querySelector<HTMLElement>("[data-ap-status]");

      let effortList: string[] = ["Low", "Medium", "High", "Max"];
      try {
        const parsed = JSON.parse(root.dataset.efforts ?? "[]") as string[];
        if (parsed.length > 0) effortList = parsed;
      } catch {
        // fallback to default list
      }

      const sampleFiles = ["roadmap-q4.md", "latency-report.csv", "schema-diff.sql", "audit-checklist.pdf"];
      let fileIdx = 0;
      let currentModel = modelLabel?.textContent?.trim() ?? "Opus 5.5";
      let currentEffort = effortLabel?.textContent?.trim() ?? "High";
      let streamTimer: number | undefined;
      let isStreaming = false;
      const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;

      const announce = (msg: string) => {
        if (status) status.textContent = msg;
      };

      const resizeInput = () => {
        if (!input) return;
        input.style.height = "auto";
        input.style.height = `${Math.min(input.scrollHeight, 176)}px`;
      };

      const syncSendState = () => {
        if (!sendBtn || !input) return;
        sendBtn.disabled = isStreaming || input.value.trim().length === 0;
      };

      const closePanels = () => {
        root.querySelectorAll<HTMLElement>("[data-ap-panel]").forEach((panel) => {
          panel.hidden = true;
        });
        root.querySelectorAll<HTMLButtonElement>("[data-ap-toggle]").forEach((btn) => {
          btn.setAttribute("aria-expanded", "false");
        });
      };

      const openPanel = (name: string) => {
        closePanels();
        const panel = root.querySelector<HTMLElement>(`[data-ap-panel="${name}"]`);
        const btn = root.querySelector<HTMLButtonElement>(`[data-ap-toggle="${name}"]`);
        if (panel) panel.hidden = false;
        if (btn) btn.setAttribute("aria-expanded", "true");
      };

      const paintSignal = (level: string) => {
        const idx = Math.max(0, effortList.indexOf(level));
        const activeCount = Math.min(4, idx + 1);
        sigBars.forEach((bar, i) => {
          const lit = i < activeCount;
          bar.classList.toggle("text-foreground", lit);
          bar.classList.toggle("text-muted-foreground/30", !lit);
        });
      };

      const selectModel = (name: string) => {
        currentModel = name;
        if (modelLabel) modelLabel.textContent = name;
        root.querySelectorAll<HTMLButtonElement>("[data-ap-model-option]").forEach((opt) => {
          const active = opt.dataset.apModelOption === name;
          opt.setAttribute("aria-pressed", String(active));
          opt.classList.toggle("bg-accent/60", active);
          const check = opt.querySelector<HTMLElement>("[data-ap-check]");
          check?.classList.toggle("opacity-0", !active);
        });
        closePanels();
        announce(`Model switched to ${name}.`);
      };

      const selectEffort = (level: string) => {
        currentEffort = level;
        if (effortLabel) effortLabel.textContent = level;
        paintSignal(level);
        root.querySelectorAll<HTMLButtonElement>("[data-ap-effort-option]").forEach((opt) => {
          const active = opt.dataset.apEffortOption === level;
          opt.setAttribute("aria-pressed", String(active));
          opt.classList.toggle("bg-accent", active);
          opt.classList.toggle("text-foreground", active);
          opt.classList.toggle("text-muted-foreground", !active);
          const check = opt.querySelector<HTMLElement>("[data-ap-check]");
          check?.classList.toggle("opacity-0", !active);
        });
        closePanels();
        announce(`Reasoning effort set to ${level}.`);
      };

      const addFileChip = (fileName: string) => {
        if (!files) return;
        files.hidden = false;
        const chip = document.createElement("span");
        chip.setAttribute("data-ap-chip", "");
        chip.className =
          "inline-flex max-w-full items-center gap-1.5 rounded-lg border border-border bg-muted/40 px-2.5 py-1 text-xs/4 text-foreground";

        const label = document.createElement("span");
        label.className = "truncate";
        label.textContent = fileName;

        const rm = document.createElement("button");
        rm.type = "button";
        rm.setAttribute("data-ap-remove", "");
        rm.setAttribute("aria-label", `Remove ${fileName}`);
        rm.className =
          "inline-flex size-5 shrink-0 cursor-pointer items-center justify-center rounded-sm text-muted-foreground transition-colors duration-150 ease-snappy hover:bg-accent hover:text-foreground focus-visible:outline-2 focus-visible:outline-ring";
        rm.textContent = "×";

        chip.append(label, rm);
        files.append(chip);
        announce(`Attached ${fileName}.`);
      };

      const filterCommands = (query: string) => {
        const items = root.querySelectorAll<HTMLElement>("[data-ap-cmd-item]");
        let visible = 0;
        items.forEach((item) => {
          const cmd = (item.dataset.apCmdItem ?? "").toLowerCase();
          const show = cmd.includes(query.toLowerCase());
          item.hidden = !show;
          if (show) visible++;
        });
        return visible;
      };

      tryBtn?.addEventListener("click", () => {
        const promoModel = root.dataset.promoModel ?? "Solstice 5.1";
        selectModel(promoModel);
        if (promo) promo.hidden = true;
        input?.focus();
      });

      root.querySelectorAll<HTMLButtonElement>("[data-ap-toggle]").forEach((btn) => {
        btn.addEventListener("click", () => {
          const name = btn.dataset.apToggle;
          if (!name) return;
          const panel = root.querySelector<HTMLElement>(`[data-ap-panel="${name}"]`);
          const wasHidden = panel ? panel.hidden : true;
          closePanels();
          if (wasHidden) openPanel(name);
        });
      });

      root.querySelectorAll<HTMLButtonElement>("[data-ap-model-option]").forEach((opt) => {
        opt.addEventListener("click", () => {
          const name = opt.dataset.apModelOption;
          if (name) selectModel(name);
        });
      });

      root.querySelectorAll<HTMLButtonElement>("[data-ap-effort-option]").forEach((opt) => {
        opt.addEventListener("click", () => {
          const level = opt.dataset.apEffortOption;
          if (level) selectEffort(level);
        });
      });

      root.querySelectorAll<HTMLButtonElement>("[data-ap-cmd-pick]").forEach((btn) => {
        btn.addEventListener("click", () => {
          const cmd = btn.dataset.apCmdPick;
          if (!cmd || !input) return;
          const val = input.value;
          const slashMatch = val.match(/(?:^|\s)(\/[a-z]*)$/i);
          if (slashMatch && slashMatch.index !== undefined) {
            const prefixEnd = val.length - slashMatch[1].length;
            input.value = `${val.slice(0, prefixEnd)}${cmd} `;
          } else {
            input.value = `${val}${val && !val.endsWith(" ") ? " " : ""}${cmd} `;
          }
          closePanels();
          resizeInput();
          syncSendState();
          input.focus();
          announce(`Inserted ${cmd} command.`);
        });
      });

      attachBtn?.addEventListener("click", () => {
        const nextFile = sampleFiles[fileIdx % sampleFiles.length];
        fileIdx++;
        addFileChip(nextFile);
      });

      files?.addEventListener("click", (ev) => {
        const rm = (ev.target as HTMLElement | null)?.closest<HTMLButtonElement>("[data-ap-remove]");
        if (!rm) return;
        const chip = rm.closest<HTMLElement>("[data-ap-chip]");
        const name = chip?.querySelector("span")?.textContent ?? "file";
        chip?.remove();
        if (files.children.length === 0) files.hidden = true;
        announce(`Removed ${name}.`);
      });

      input?.addEventListener("input", () => {
        resizeInput();
        syncSendState();
        const match = input.value.match(/(?:^|\s)(\/[a-z]*)$/i);
        if (match) {
          const visible = filterCommands(match[1]);
          if (visible > 0) openPanel("cmd");
          else closePanels();
        } else {
          const cmdPanel = root.querySelector<HTMLElement>('[data-ap-panel="cmd"]');
          if (cmdPanel && !cmdPanel.hidden) closePanels();
        }
      });

      input?.addEventListener("keydown", (ev) => {
        if (ev.key === "Escape") {
          closePanels();
        }
      });

      input?.addEventListener("paste", (ev) => {
        const pastedFiles = ev.clipboardData?.files;
        if (pastedFiles && pastedFiles.length > 0) {
          ev.preventDefault();
          Array.from(pastedFiles).forEach((f) => addFileChip(f.name));
        }
      });

      shell?.addEventListener("dragover", (ev) => {
        ev.preventDefault();
        shell.setAttribute("data-dragging", "true");
      });

      shell?.addEventListener("dragleave", () => {
        shell.removeAttribute("data-dragging");
      });

      shell?.addEventListener("drop", (ev) => {
        ev.preventDefault();
        shell.removeAttribute("data-dragging");
        const dropped = ev.dataTransfer?.files;
        if (dropped && dropped.length > 0) {
          Array.from(dropped).forEach((f) => addFileChip(f.name));
        } else {
          const nextFile = sampleFiles[fileIdx % sampleFiles.length];
          fileIdx++;
          addFileChip(nextFile);
        }
      });

      const finishStreaming = (stopped: boolean) => {
        if (streamTimer !== undefined) {
          window.clearInterval(streamTimer);
          streamTimer = undefined;
        }
        isStreaming = false;
        if (sendBtn) sendBtn.hidden = false;
        if (stopBtn) stopBtn.hidden = true;
        if (replyState) replyState.textContent = stopped ? "Stopped" : "Complete";
        syncSendState();
        announce(stopped ? "Generation stopped." : `Reply finished with ${currentModel}.`);
      };

      stopBtn?.addEventListener("click", () => {
        finishStreaming(true);
      });

      form?.addEventListener("submit", (ev) => {
        ev.preventDefault();
        if (!input) return;
        const prompt = input.value.trim();
        if (!prompt || isStreaming) return;

        closePanels();
        isStreaming = true;
        if (sendBtn) sendBtn.hidden = true;
        if (stopBtn) stopBtn.hidden = false;
        if (replyBox) replyBox.hidden = false;
        if (replyMeta) replyMeta.textContent = `${currentModel} · ${currentEffort}`;
        if (replyState) replyState.textContent = "Streaming…";

        const chipCount = files?.querySelectorAll("[data-ap-chip]").length ?? 0;
        const attachmentNote = chipCount > 0 ? ` using ${chipCount} attached ${chipCount === 1 ? "file" : "files"}` : "";
        const fullText = `Analyzed "${prompt.slice(0, 72)}"${attachmentNote}. Isolate the rollout behind a feature flag, verify p95 latency in staging, and confirm fallback copy before launch.`;

        input.value = "";
        resizeInput();
        announce(`Generating reply with ${currentModel} at ${currentEffort} effort…`);

        if (reducedMotion) {
          if (replyBody) replyBody.textContent = fullText;
          finishStreaming(false);
          return;
        }

        const words = fullText.split(" ");
        let cursor = 0;
        if (replyBody) replyBody.textContent = "";
        streamTimer = window.setInterval(() => {
          cursor += 2;
          if (replyBody) replyBody.textContent = words.slice(0, cursor).join(" ");
          if (cursor >= words.length) {
            finishStreaming(false);
          }
        }, 70);
      });

      syncSendState();
    });
  }

  initAiPromptSelectors();
  document.addEventListener("astro:page-load", initAiPromptSelectors);
</script>
```
