<script lang="ts">
  import { getCapabilities } from './provider-capabilities';

  interface Props {
    value: string;
    model?: string;
    provider?: string;
    contextPct?: number;
    disabled?: boolean;
    placeholder?: string;
    onSend?: () => void;
    onInput?: (v: string) => void;
  }

  let {
    value,
    model = 'claude-opus-4-5',
    provider = 'claude',
    contextPct = 78,
    disabled = false,
    placeholder = 'Ask Claude anything...',
    onSend,
    onInput,
  }: Props = $props();

  let textareaEl: HTMLTextAreaElement;

  // Which popup is open: 'upload' | 'context' | 'web' | 'slash' | null
  let openPopup = $state<string | null>(null);

  let caps = $derived(getCapabilities(provider));

  // Radial progress arc path
  let arcPath = $derived.by(() => {
    const pct = Math.min(100, Math.max(0, contextPct));
    const r = 8;
    const cx = 10, cy = 10;
    const angle = (pct / 100) * 2 * Math.PI;
    const startX = cx;
    const startY = cy - r;
    const endX = cx + r * Math.sin(angle);
    const endY = cy - r * Math.cos(angle);
    const large = pct > 50 ? 1 : 0;
    if (pct >= 100) {
      return `M ${cx} ${cy - r} A ${r} ${r} 0 1 1 ${cx - 0.001} ${cy - r} Z`;
    }
    return `M ${startX} ${startY} A ${r} ${r} 0 ${large} 1 ${endX} ${endY}`;
  });

  let arcColor = $derived(
    contextPct >= 75 ? 'var(--ctp-red)' :
    contextPct >= 50 ? 'var(--ctp-yellow)' :
    'var(--ctp-green)'
  );

  function autoResize() {
    if (!textareaEl) return;
    textareaEl.style.height = 'auto';
    textareaEl.style.height = Math.min(textareaEl.scrollHeight, 200) + 'px';
  }

  function handleKeydown(e: KeyboardEvent) {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      if (value.trim()) onSend?.();
    }
    if (e.key === 'Escape') openPopup = null;
  }

  function handleInput(e: Event) {
    onInput?.((e.target as HTMLTextAreaElement).value);
    autoResize();
  }

  function togglePopup(name: string) {
    openPopup = openPopup === name ? null : name;
  }

  function closePopup() { openPopup = null; }

  function handleOuterKeydown(e: KeyboardEvent) {
    if (e.key === 'Escape') openPopup = null;
  }

  const UPLOAD_ITEMS   = ['Upload from computer', 'Paste from clipboard'];
  const CONTEXT_ITEMS  = ['Add file', 'Add folder', 'Add URL', 'Add image'];
  const WEB_ITEMS      = ['Search the web', 'Fetch URL'];
  const SLASH_COMMANDS = ['/help', '/clear', '/compact', '/review', '/test', '/commit'];
</script>

<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
  class="chat-input-outer"
  onkeydown={handleOuterKeydown}
>
  <textarea
    bind:this={textareaEl}
    class="chat-textarea"
    {placeholder}
    rows="1"
    {value}
    oninput={handleInput}
    onkeydown={handleKeydown}
    aria-label="Message input"
  ></textarea>

  <div class="footer-strip">
    <!-- Upload file -->
    {#if caps.upload}
      <div class="popup-wrap">
        <button
          class="footer-btn"
          class:active={openPopup === 'upload'}
          aria-label="Upload file"
          title="Upload"
          onclick={() => togglePopup('upload')}
        >
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
            <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/>
          </svg>
        </button>
        {#if openPopup === 'upload'}
          <!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
          <div class="popup-menu" role="menu" tabindex="-1" onkeydown={e => e.key === 'Escape' && closePopup()}>
            {#each UPLOAD_ITEMS as item}
              <button class="popup-item" role="menuitem" onclick={closePopup}>{item}</button>
            {/each}
          </div>
        {/if}
      </div>
    {/if}

    <!-- Add context -->
    {#if caps.context}
      <div class="popup-wrap">
        <button
          class="footer-btn"
          class:active={openPopup === 'context'}
          aria-label="Add context"
          title="Add context"
          onclick={() => togglePopup('context')}
        >
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
            <rect x="3" y="3" width="18" height="18" rx="2"/><line x1="12" y1="8" x2="12" y2="16"/><line x1="8" y1="12" x2="16" y2="12"/>
          </svg>
        </button>
        {#if openPopup === 'context'}
          <!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
          <div class="popup-menu" role="menu" tabindex="-1" onkeydown={e => e.key === 'Escape' && closePopup()}>
            {#each CONTEXT_ITEMS as item}
              <button class="popup-item" role="menuitem" onclick={closePopup}
                class:disabled-item={item === 'Add image' && !caps.images}
              >{item}</button>
            {/each}
          </div>
        {/if}
      </div>
    {/if}

    <!-- Browse web -->
    {#if caps.web}
      <div class="popup-wrap">
        <button
          class="footer-btn"
          class:active={openPopup === 'web'}
          aria-label="Browse the web"
          title="Browse the web"
          onclick={() => togglePopup('web')}
        >
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
            <circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/>
          </svg>
        </button>
        {#if openPopup === 'web'}
          <!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
          <div class="popup-menu" role="menu" tabindex="-1" onkeydown={e => e.key === 'Escape' && closePopup()}>
            {#each WEB_ITEMS as item}
              <button class="popup-item" role="menuitem" onclick={closePopup}>{item}</button>
            {/each}
          </div>
        {/if}
      </div>
    {/if}

    <!-- Slash commands -->
    {#if caps.slash}
      <div class="popup-wrap">
        <button
          class="footer-btn"
          class:active={openPopup === 'slash'}
          aria-label="Slash commands"
          title="Slash commands (/)"
          onclick={() => togglePopup('slash')}
        >
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true">
            <line x1="7" y1="20" x2="17" y2="4"/>
          </svg>
        </button>
        {#if openPopup === 'slash'}
          <!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
          <div class="popup-menu" role="menu" tabindex="-1" onkeydown={e => e.key === 'Escape' && closePopup()}>
            {#each SLASH_COMMANDS as cmd}
              <button class="popup-item popup-slash" role="menuitem" onclick={closePopup}>{cmd}</button>
            {/each}
          </div>
        {/if}
      </div>
    {/if}

    <!-- Context radial progress indicator -->
    <div class="context-indicator" title="Context window: {contextPct}% used">
      <svg width="20" height="20" viewBox="0 0 20 20" aria-hidden="true">
        <!-- Track ring -->
        <circle cx="10" cy="10" r="8" fill="none" stroke="var(--ctp-surface1)" stroke-width="2"/>
        <!-- Progress arc -->
        <path
          d={arcPath}
          fill="none"
          stroke={arcColor}
          stroke-width="2"
          stroke-linecap="round"
        />
      </svg>
      <span class="ctx-pct" style="color: {arcColor}">{contextPct}%</span>
    </div>

    <span class="footer-spacer"></span>
    <span class="model-label">{model}</span>
    <span class="footer-divider" aria-hidden="true"></span>

    <!-- Send button -->
    <button
      class="send-btn"
      onclick={onSend}
      disabled={disabled || !value.trim()}
      aria-label="Send message"
      title="Send (Enter)"
    >
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" aria-hidden="true">
        <path d="M22 2L11 13" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
        <path d="M22 2L15 22L11 13L2 9L22 2Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
      </svg>
    </button>
  </div>
</div>

<!-- Fix #11: display toggle for popup backdrop -->
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
  class="popup-backdrop"
  style:display={openPopup !== null ? 'block' : 'none'}
  onclick={closePopup}
  onkeydown={e => e.key === 'Escape' && closePopup()}
></div>

<style>
  .chat-input-outer {
    background: var(--ctp-crust);
    border: 1px solid var(--ctp-surface1);
    border-radius: 0.5rem;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
    display: flex;
    flex-direction: column;
    overflow: visible;
    position: relative;
    z-index: 30;
  }

  .chat-textarea {
    background: transparent;
    border: none;
    outline: none;
    resize: none;
    color: var(--ctp-text);
    font-family: var(--ui-font-family);
    font-size: 0.8125rem;
    line-height: 1.5;
    padding: 0.625rem 0.875rem;
    min-height: 2.5rem;
    max-height: 12.5rem;
    overflow-y: auto;
    width: 100%;
    box-sizing: border-box;
  }

  .chat-textarea:focus {
    box-shadow: 0 0 0 3px color-mix(in srgb, var(--ctp-peach) 12%, transparent);
  }

  .chat-textarea::placeholder { color: var(--ctp-subtext0); }
  .chat-textarea::-webkit-scrollbar { width: 0.25rem; }
  .chat-textarea::-webkit-scrollbar-thumb { background: var(--ctp-surface1); border-radius: 0.25rem; }

  /* Footer strip */
  .footer-strip {
    display: flex;
    align-items: center;
    gap: 0.125rem;
    padding: 0.3125rem;
    border-top: 0.5px solid var(--ctp-surface1);
    position: relative;
  }

  /* Popup anchor */
  .popup-wrap {
    position: relative;
  }

  .footer-btn {
    background: transparent;
    border: none;
    color: var(--ctp-overlay1);
    cursor: pointer;
    padding: 0.25rem;
    border-radius: 0.25rem;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: color 0.12s, background 0.12s;
  }

  .footer-btn:hover {
    color: var(--ctp-text);
    background: var(--ctp-surface0);
  }

  .footer-btn.active {
    color: var(--ctp-blue);
    background: color-mix(in srgb, var(--ctp-blue) 12%, transparent);
  }

  /* Popup menu */
  .popup-menu {
    position: absolute;
    bottom: calc(100% + 0.375rem);
    left: 0;
    z-index: 100;
    background: var(--ctp-surface0);
    border: 1px solid var(--ctp-surface1);
    border-radius: 0.375rem;
    box-shadow: 0 0.5rem 1.25rem color-mix(in srgb, var(--ctp-crust) 70%, transparent);
    min-width: 10rem;
    padding: 0.25rem;
    display: flex;
    flex-direction: column;
    gap: 0.0625rem;
  }

  .popup-item {
    width: 100%;
    background: transparent;
    border: none;
    color: var(--ctp-text);
    font-family: var(--ui-font-family);
    font-size: 0.8125rem;
    padding: 0.35rem 0.625rem;
    border-radius: 0.25rem;
    text-align: left;
    cursor: pointer;
    transition: background 0.08s, color 0.08s;
  }

  .popup-item:hover { background: var(--ctp-surface1); }

  .popup-slash {
    font-family: var(--term-font-family);
    color: var(--ctp-blue);
  }

  .popup-slash:hover { color: var(--ctp-text); }

  .disabled-item { opacity: 0.4; cursor: not-allowed; }

  /* Popup click-outside backdrop */
  .popup-backdrop {
    position: fixed;
    inset: 0;
    z-index: 29;
  }

  /* Radial context indicator */
  .context-indicator {
    display: flex;
    align-items: center;
    gap: 0.25rem;
    padding: 0.125rem 0.25rem;
    cursor: default;
  }

  .ctx-pct {
    font-size: 0.6875rem;
    font-weight: 600;
    min-width: 2rem;
    letter-spacing: -0.01em;
  }

  .model-label {
    font-size: 0.85em;
    color: var(--ctp-overlay1);
    padding: 0 0.25rem;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 8rem;
  }

  .footer-spacer { flex: 1; }

  .footer-divider {
    width: 1px;
    height: 1rem;
    background: var(--ctp-surface1);
    margin: 0 0.25rem;
    flex-shrink: 0;
  }

  .send-btn {
    width: 26px;
    height: 26px;
    background: var(--ctp-peach);
    border: none;
    border-radius: 5px;
    color: #f5efe6;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    transition: filter 0.12s;
  }

  .send-btn:hover:not(:disabled) { filter: brightness(1.1); }

  .send-btn:disabled {
    opacity: 0.4;
    cursor: not-allowed;
  }
</style>
