<script lang="ts">
  interface AgentResult {
    value: string;
    label: string;
    type: string;
  }

  let {
    id = '',
    value = '',
    onChange = (_v: unknown) => {},
    required = false,
    ariaDescribedBy = undefined,
  }: {
    id?: string;
    value?: string;
    onChange?: (v: unknown) => void;
    required?: boolean;
    ariaDescribedBy?: string;
  } = $props();

  let selectedId = $state(value || '');
  let selectedLabel = $state('');
  let searchQuery = $state('');
  let searchResults: AgentResult[] = $state([]);
  let showDropdown = $state(false);
  let isSearching = $state(false);
  let allAgents: AgentResult[] = $state([]);

  // The per-agent Context Control Center settings URL.
  let contextUrl = $state('');

  if (selectedId) {
    resolveLabel(selectedId);
    loadContextUrl(selectedId);
  }

  async function fetchAgents(q: string): Promise<AgentResult[]> {
    try {
      const res = await fetch(
        `/api/flowdrop/ai-agents/autocomplete?q=${encodeURIComponent(q)}`,
      );
      if (!res.ok) return [];
      const json = await res.json();
      return json.results ?? [];
    }
    catch {
      return [];
    }
  }

  async function resolveLabel(agentId: string) {
    if (allAgents.length === 0) {
      allAgents = await fetchAgents('');
    }
    const match = allAgents.find((a) => a.value === agentId);
    if (match) selectedLabel = match.label;
  }

  async function loadContextUrl(agentId: string) {
    contextUrl = '';
    if (!agentId) return;
    try {
      const res = await fetch(
        `/api/flowdrop/ai-context-agent/${encodeURIComponent(agentId)}/context-url`,
      );
      if (!res.ok) return;
      const json = await res.json();
      contextUrl = json.url ?? '';
    }
    catch {
      contextUrl = '';
    }
  }

  async function handleFocus() {
    isSearching = true;
    if (allAgents.length === 0) {
      allAgents = await fetchAgents('');
    }
    searchResults = allAgents;
    showDropdown = searchResults.length > 0;
    isSearching = false;
  }

  async function handleSearch(q: string) {
    searchQuery = q;
    isSearching = true;
    searchResults = await fetchAgents(q.trim());
    showDropdown = searchResults.length > 0;
    isSearching = false;
  }

  function selectAgent(agent: AgentResult) {
    selectedId = agent.value;
    selectedLabel = agent.label;
    searchQuery = '';
    searchResults = [];
    showDropdown = false;
    onChange(agent.value);
    loadContextUrl(agent.value);
  }

  function clearSelection() {
    selectedId = '';
    selectedLabel = '';
    contextUrl = '';
    onChange('');
  }

  function handleClickAway(e: MouseEvent) {
    const target = e.target as HTMLElement;
    if (!target.isConnected) return;
    if (!target.closest('.fd-agent-context')) {
      showDropdown = false;
    }
  }
</script>

<svelte:window onclick={handleClickAway} />

<div class="fd-agent-context" aria-describedby={ariaDescribedBy}>
  {#if selectedId}
    <div class="fd-agent-context__selected">
      <span class="fd-agent-context__selected-label">{selectedLabel || selectedId}</span>
      <button
        type="button"
        class="fd-agent-context__clear"
        onclick={clearSelection}
        aria-label="Clear selection"
      >&times;</button>
    </div>

    {#if contextUrl}
      <a
        href={contextUrl}
        class="fd-agent-context__cc-link"
        target="_blank"
        rel="noopener noreferrer"
      >
        Configure context for this agent ↗
      </a>
    {/if}
  {:else}
    <input
      type="text"
      class="fd-agent-context__search"
      placeholder="Search AI agents…"
      value={searchQuery}
      {required}
      oninput={(e) => handleSearch((e.target as HTMLInputElement).value)}
      onfocus={handleFocus}
    />

    {#if showDropdown}
      <ul class="fd-agent-context__dropdown" role="listbox">
        {#each searchResults as result (result.value)}
          <li
            class="fd-agent-context__option"
            role="option"
            tabindex="0"
            aria-selected="false"
            onclick={() => selectAgent(result)}
            onkeydown={(e) => { if (e.key === 'Enter') selectAgent(result); }}
          >
            <span>{result.label}</span>
            <span class="fd-agent-context__type">{result.type}</span>
          </li>
        {/each}
      </ul>
    {/if}
  {/if}
</div>

<style>
  .fd-agent-context {
    font-family: inherit;
    font-size: 0.8125rem;
    line-height: 1.4;
  }

  .fd-agent-context__search {
    width: 100%;
    padding: 0.5rem;
    border: 1px solid var(--fd-border-color, #d0d5dd);
    border-radius: 4px;
    background: var(--fd-bg-color, #fff);
    color: var(--fd-text-color, #344054);
    font-size: 0.8125rem;
    box-sizing: border-box;
  }

  .fd-agent-context__search:focus {
    outline: none;
    border-color: var(--fd-primary-color, #2563eb);
    box-shadow: 0 0 0 2px rgba(37, 99, 235, 0.15);
  }

  .fd-agent-context__dropdown {
    list-style: none;
    margin: 0.25rem 0 0;
    padding: 0.25rem 0;
    border: 1px solid var(--fd-border-color, #d0d5dd);
    border-radius: 4px;
    background: var(--fd-bg-color, #fff);
    max-height: 200px;
    overflow-y: auto;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  }

  .fd-agent-context__option {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0.375rem 0.5rem;
    cursor: pointer;
  }

  .fd-agent-context__option:hover {
    background: var(--fd-primary-color-light, #eff6ff);
  }

  .fd-agent-context__type {
    font-size: 0.6875rem;
    padding: 0.125rem 0.375rem;
    border-radius: 3px;
    color: var(--fd-accent, #6941c6);
    background: var(--fd-accent-muted, rgba(105, 65, 198, 0.08));
  }

  .fd-agent-context__selected {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0.5rem;
    border: 1px solid var(--fd-primary-color, #2563eb);
    border-radius: 4px;
    background: var(--fd-primary-color-light, #eff6ff);
  }

  .fd-agent-context__selected-label {
    font-weight: 500;
    color: var(--fd-primary-color, #2563eb);
  }

  .fd-agent-context__clear {
    background: none;
    border: none;
    color: var(--fd-text-muted, #98a2b3);
    cursor: pointer;
    font-size: 1.125rem;
    padding: 0 0.25rem;
    line-height: 1;
  }

  .fd-agent-context__cc-link {
    display: inline-block;
    margin-top: 0.375rem;
    font-size: 0.75rem;
    font-weight: 500;
    color: var(--fd-primary-color, #2563eb);
    text-decoration: none;
  }

  .fd-agent-context__cc-link:hover {
    text-decoration: underline;
  }
</style>
