<script lang="ts">
  import { onMount } from 'svelte';
  import { appRpc } from '../rpc.ts';
  import CustomDropdown from '../ui/CustomDropdown.svelte';

  const KNOWN_KEYS: Record<string, string> = {
    ANTHROPIC_API_KEY:  'Anthropic API Key',
    OPENAI_API_KEY:     'OpenAI API Key',
    GITHUB_TOKEN:       'GitHub Token',
    OLLAMA_API_KEY:     'Ollama API Key',
  };

  // Demo state — no real keyring in prototype
  let keyringAvailable = $state(true);
  let storedKeys = $state<string[]>(['ANTHROPIC_API_KEY']);
  let revealedKey = $state<string | null>(null);

  let newKey   = $state('');
  let newValue = $state('');
  // Dropdown state managed by CustomDropdown
  let saving = $state(false);

  interface BranchPolicy { pattern: string; action: 'block' | 'warn'; }
  let branchPolicies = $state<BranchPolicy[]>([
    { pattern: 'main', action: 'block' },
    { pattern: 'prod*', action: 'warn' },
  ]);
  let newPattern = $state('');
  let newAction  = $state<'block' | 'warn'>('warn');

  let availableKeys = $derived(Object.keys(KNOWN_KEYS).filter(k => !storedKeys.includes(k)));
  let keyDropItems = $derived(availableKeys.map(k => ({ value: k, label: KNOWN_KEYS[k] ?? k })));

  function persistPolicies() {
    appRpc?.request['settings.set']({ key: 'branch_policies', value: JSON.stringify(branchPolicies) }).catch(console.error);
  }

  function handleSaveSecret() {
    if (!newKey || !newValue) return;
    saving = true;
    setTimeout(() => {
      storedKeys = [...storedKeys, newKey];
      newKey = ''; newValue = '';
      saving = false;
    }, 400);
  }

  function deleteSecret(key: string) {
    storedKeys = storedKeys.filter(k => k !== key);
    if (revealedKey === key) revealedKey = null;
  }

  function addBranchPolicy() {
    if (!newPattern.trim()) return;
    branchPolicies = [...branchPolicies, { pattern: newPattern.trim(), action: newAction }];
    newPattern = ''; newAction = 'warn';
    persistPolicies();
  }

  function removeBranchPolicy(idx: number) {
    branchPolicies = branchPolicies.filter((_, i) => i !== idx);
    persistPolicies();
  }

  // CustomDropdown handles its own outside click

  onMount(async () => {
    if (!appRpc) return;
    const res = await appRpc.request['settings.get']({ key: 'branch_policies' }).catch(() => ({ value: null }));
    if (res.value) {
      try { branchPolicies = JSON.parse(res.value); } catch { /* ignore */ }
    }
  });
</script>

<div class="section">

  <div class="prototype-notice">
    Prototype — secrets are stored locally in plain SQLite, not in the system keyring.
    Do not store production credentials here.
  </div>

  <h3 class="sh">Keyring Status</h3>
  <div class="keyring-status" class:ok={keyringAvailable} class:unavail={!keyringAvailable}>
    <span class="ks-dot"></span>
    <span>{keyringAvailable ? 'System keyring available' : 'System keyring unavailable — secrets stored in plain config'}</span>
  </div>

  <h3 class="sh">Stored Secrets</h3>
  {#if storedKeys.length === 0}
    <p class="empty-hint">No secrets stored.</p>
  {:else}
    <div class="secret-list">
      {#each storedKeys as key}
        <div class="secret-row">
          <span class="secret-key">{KNOWN_KEYS[key] ?? key}</span>
          <span class="secret-val">{revealedKey === key ? '••••••• (revealed)' : '•••••••'}</span>
          <button class="icon-btn" onclick={() => revealedKey = revealedKey === key ? null : key} title="Toggle reveal">
            {revealedKey === key ? '🙈' : '👁'}
          </button>
          <button class="icon-btn danger" onclick={() => deleteSecret(key)} title="Delete">✕</button>
        </div>
      {/each}
    </div>
  {/if}

  <div class="add-secret">
    <div class="dd-key-wrap">
      <CustomDropdown
        items={keyDropItems}
        selected={newKey}
        placeholder="Select key..."
        onSelect={v => newKey = v}
      />
    </div>
    <input class="text-in flex1" type="password" bind:value={newValue} placeholder="Value" aria-label="Secret value" />
    <button class="save-btn" onclick={handleSaveSecret} disabled={!newKey || !newValue || saving}>
      {saving ? '…' : 'Save'}
    </button>
  </div>

  <h3 class="sh" style="margin-top: 0.875rem;">Branch Policies</h3>
  <div class="policy-list">
    {#each branchPolicies as pol, i}
      <div class="policy-row">
        <code class="pol-pattern">{pol.pattern}</code>
        <span class="pol-action" class:block={pol.action === 'block'} class:warn={pol.action === 'warn'}>{pol.action}</span>
        <button class="icon-btn danger" onclick={() => removeBranchPolicy(i)} title="Remove">✕</button>
      </div>
    {/each}
  </div>
  <div class="add-policy">
    <input class="text-in flex1" bind:value={newPattern} placeholder="e.g. main, prod*" aria-label="Branch pattern" />
    <div class="seg">
      <button class:active={newAction === 'warn'}  onclick={() => newAction = 'warn'}>Warn</button>
      <button class:active={newAction === 'block'} onclick={() => newAction = 'block'}>Block</button>
    </div>
    <button class="save-btn" onclick={addBranchPolicy} disabled={!newPattern.trim()}>Add</button>
  </div>
</div>

<style>
  .prototype-notice {
    padding: 0.5rem 0.625rem;
    background: color-mix(in srgb, var(--ctp-peach) 12%, transparent);
    border: 1px solid color-mix(in srgb, var(--ctp-peach) 30%, transparent);
    border-radius: 0.25rem;
    color: var(--ctp-peach);
    font-size: 0.75rem;
    line-height: 1.4;
  }
  .section { display: flex; flex-direction: column; gap: 0.5rem; }
  .sh { margin: 0.375rem 0 0.125rem; font-size: 0.6875rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.06em; color: var(--ctp-overlay0); }

  .keyring-status { display: flex; align-items: center; gap: 0.5rem; font-size: 0.8rem; padding: 0.375rem 0.5rem; border-radius: 0.25rem; background: var(--ctp-surface0); }
  .ks-dot { width: 0.5rem; height: 0.5rem; border-radius: 50%; flex-shrink: 0; background: var(--ctp-overlay0); }
  .keyring-status.ok .ks-dot { background: var(--ctp-green); }
  .keyring-status.unavail .ks-dot { background: var(--ctp-peach); }
  .keyring-status.ok { color: var(--ctp-subtext1); }
  .keyring-status.unavail { color: var(--ctp-peach); }

  .empty-hint { font-size: 0.8rem; color: var(--ctp-overlay0); margin: 0; font-style: italic; }

  .secret-list { display: flex; flex-direction: column; gap: 0.25rem; }
  .secret-row { display: flex; align-items: center; gap: 0.375rem; padding: 0.3rem 0.5rem; background: var(--ctp-surface0); border: 1px solid var(--ctp-surface1); border-radius: 0.25rem; }
  .secret-key { font-size: 0.8rem; color: var(--ctp-text); font-weight: 500; flex: 1; }
  .secret-val { font-family: var(--term-font-family, monospace); font-size: 0.75rem; color: var(--ctp-overlay1); min-width: 7rem; }

  .add-secret { display: flex; align-items: center; gap: 0.375rem; margin-top: 0.25rem; }
  .add-policy { display: flex; align-items: center; gap: 0.375rem; margin-top: 0.25rem; }
  .flex1 { flex: 1; min-width: 0; }

  .dd-key-wrap { flex-shrink: 0; min-width: 10rem; }

  .text-in { padding: 0.275rem 0.5rem; background: var(--ctp-surface0); border: 1px solid var(--ctp-surface1); border-radius: 0.25rem; color: var(--ctp-text); font-size: 0.8rem; font-family: var(--ui-font-family); }
  .text-in:focus { outline: none; border-color: var(--ctp-blue); }

  .save-btn { padding: 0.275rem 0.625rem; background: var(--ctp-blue); border: none; border-radius: 0.25rem; color: var(--ctp-base); font-size: 0.75rem; font-weight: 600; cursor: pointer; font-family: var(--ui-font-family); flex-shrink: 0; }
  .save-btn:hover:not(:disabled) { filter: brightness(1.1); }
  .save-btn:disabled { opacity: 0.4; cursor: not-allowed; }

  .policy-list { display: flex; flex-direction: column; gap: 0.25rem; }
  .policy-row { display: flex; align-items: center; gap: 0.375rem; padding: 0.3rem 0.5rem; background: var(--ctp-surface0); border: 1px solid var(--ctp-surface1); border-radius: 0.25rem; }
  .pol-pattern { font-family: var(--term-font-family, monospace); font-size: 0.8rem; color: var(--ctp-text); flex: 1; }
  .pol-action { font-size: 0.7rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.04em; padding: 0.1rem 0.375rem; border-radius: 0.2rem; }
  .pol-action.block { background: color-mix(in srgb, var(--ctp-red) 15%, transparent); color: var(--ctp-red); }
  .pol-action.warn  { background: color-mix(in srgb, var(--ctp-yellow) 15%, transparent); color: var(--ctp-yellow); }

  .icon-btn { background: none; border: none; color: var(--ctp-overlay0); cursor: pointer; font-size: 0.85rem; padding: 0.2rem; border-radius: 0.15rem; }
  .icon-btn:hover { color: var(--ctp-text); background: var(--ctp-surface1); }
  .icon-btn.danger:hover { color: var(--ctp-red); }

  .seg { display: flex; border-radius: 0.25rem; overflow: hidden; border: 1px solid var(--ctp-surface1); flex-shrink: 0; }
  .seg button { padding: 0.25rem 0.5rem; background: var(--ctp-surface0); border: none; color: var(--ctp-overlay1); font-size: 0.75rem; cursor: pointer; font-family: var(--ui-font-family); }
  .seg button:not(:last-child) { border-right: 1px solid var(--ctp-surface1); }
  .seg button.active { background: color-mix(in srgb, var(--ctp-blue) 20%, var(--ctp-surface0)); color: var(--ctp-blue); font-weight: 600; }
</style>
