<script lang="ts">
  import { onMount } from 'svelte';
  import { getSetting, setSetting } from '../../stores/settings-store.svelte';
  import { getBackend } from '../../backend/backend';
  const SECRET_KEY_LABELS: Record<string, string> = {
    anthropic_api_key: 'Anthropic API Key',
    openai_api_key: 'OpenAI API Key',
    openrouter_api_key: 'OpenRouter API Key',
    github_token: 'GitHub Token',
    relay_token: 'Relay Token',
  };
  import { handleError, handleInfraError } from '../../utils/handle-error';

  let keyringAvailable = $state(false);
  let storedKeys = $state<string[]>([]);
  let knownKeys = $state<string[]>([]);
  let revealedKey = $state<string | null>(null);
  let revealedValue = $state('');
  let newSecretKey = $state('');
  let newSecretValue = $state('');
  let secretsKeyDropdownOpen = $state(false);
  let secretsSaving = $state(false);
  let branchPolicies = $state<{ pattern: string; action: 'block' | 'warn' }[]>([]);
  let newBranchPattern = $state('');
  let newBranchAction = $state<'block' | 'warn'>('warn');
  let telemetryEnabled = $state(false);
  let retentionDays = $state(90);
  let loadError = $state('');

  let availableKeysForAdd = $derived(knownKeys.filter(k => !storedKeys.includes(k)));
  let newSecretKeyLabel = $derived(newSecretKey ? getSecretKeyLabel(newSecretKey) : 'Select key...');

  onMount(async () => {
    try {
      keyringAvailable = await getBackend().hasKeyring();
      if (keyringAvailable) { storedKeys = await getBackend().listSecrets(); knownKeys = await getBackend().knownSecretKeys(); }
    } catch (e) {
      // Keyring unavailable is expected on some systems — set state explicitly
      handleInfraError(e, 'settings.keyring.init');
      keyringAvailable = false;
    }
    const results = await Promise.allSettled([
      getSetting('branch_policies'), getSetting('telemetry_enabled'), getSetting('data_retention_days'),
    ]);
    let failCount = 0;
    if (results[0].status === 'fulfilled') {
      const v = results[0].value;
      if (v) { try { branchPolicies = JSON.parse(v); } catch (e) { handleInfraError(e, 'settings.parse.branch_policies'); branchPolicies = []; } }
    } else failCount++;
    if (results[1].status === 'fulfilled') telemetryEnabled = results[1].value === 'true'; else failCount++;
    if (results[2].status === 'fulfilled') retentionDays = results[2].value ? parseInt(results[2].value, 10) : 90; else failCount++;
    if (failCount === results.length) loadError = 'Could not load settings. Displaying defaults.';
  });

  async function save(key: string, value: string) {
    try { await setSetting(key, value); } catch (e) { handleError(e, `settings.save.${key}`, 'save your settings'); }
  }
  function getSecretKeyLabel(key: string): string { return SECRET_KEY_LABELS[key] ?? key; }

  async function handleRevealSecret(key: string) {
    if (revealedKey === key) { revealedKey = null; revealedValue = ''; return; }
    try { const val = await getBackend().getSecret(key); revealedKey = key; revealedValue = val ?? ''; }
    catch (e) { handleError(e, `settings.secrets.reveal.${key}`, 'reveal the secret'); }
  }
  async function handleSaveSecret() {
    if (!newSecretKey || !newSecretValue) return;
    secretsSaving = true;
    try { await getBackend().storeSecret(newSecretKey, newSecretValue); storedKeys = await getBackend().listSecrets(); newSecretKey = ''; newSecretValue = ''; revealedKey = null; revealedValue = ''; }
    catch (e) { handleError(e, 'settings.secrets.store', 'store the secret'); }
    finally { secretsSaving = false; }
  }
  async function handleDeleteSecret(key: string) {
    try { await getBackend().deleteSecret(key); storedKeys = await getBackend().listSecrets(); if (revealedKey === key) { revealedKey = null; revealedValue = ''; } }
    catch (e) { handleError(e, `settings.secrets.delete.${key}`, 'delete the secret'); }
  }
  function addBranchPolicy() {
    if (!newBranchPattern.trim()) return;
    branchPolicies = [...branchPolicies, { pattern: newBranchPattern.trim(), action: newBranchAction }];
    newBranchPattern = ''; newBranchAction = 'warn';
    save('branch_policies', JSON.stringify(branchPolicies));
  }
  function removeBranchPolicy(idx: number) {
    branchPolicies = branchPolicies.filter((_, i) => i !== idx);
    save('branch_policies', JSON.stringify(branchPolicies));
  }
  function handleClickOutside(e: MouseEvent) { if (!(e.target as HTMLElement).closest('.custom-dropdown')) secretsKeyDropdownOpen = false; }
  function handleKeydown(e: KeyboardEvent) { if (e.key === 'Escape') secretsKeyDropdownOpen = false; }
</script>

<svelte:window onclick={handleClickOutside} onkeydown={handleKeydown} />

{#if loadError}<p class="load-error">{loadError}</p>{/if}
<section class="section">
  <h2>Secrets</h2>
  <div class="secrets-status">
    <span class="dot" class:available={keyringAvailable} class:unavailable={!keyringAvailable}></span>
    <span class="keyring-label">{keyringAvailable ? 'System keyring available' : 'System keyring unavailable'}</span>
  </div>
  {#if !keyringAvailable}
    <div class="warning-box">
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>
      <span>System keyring not available. Secrets cannot be stored securely.</span>
    </div>
  {:else}
    {#if storedKeys.length > 0}
      <div class="item-list">
        {#each storedKeys as key}
          <div class="item-row">
            <div class="secret-info">
              <span class="item-name">{getSecretKeyLabel(key)}</span>
              <span class="item-sub">{key}</span>
            </div>
            <div class="secret-val">
              {#if revealedKey === key}<input type="text" class="val-input" value={revealedValue} readonly />
              {:else}<span class="masked">{'\u25CF'.repeat(8)}</span>{/if}
            </div>
            <div class="row-actions">
              <button class="icon-btn" title={revealedKey === key ? 'Hide' : 'Reveal'} onclick={() => handleRevealSecret(key)}>
                {#if revealedKey === key}
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/></svg>
                {:else}
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
                {/if}
              </button>
              <button class="icon-btn danger" title="Delete" onclick={() => handleDeleteSecret(key)}>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18"/><path d="M8 6V4h8v2"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"/></svg>
              </button>
            </div>
          </div>
        {/each}
      </div>
    {/if}
    <div class="add-form">
      <div class="add-row">
        <div class="custom-dropdown key-dropdown">
          <button class="dd-trigger" onclick={() => { secretsKeyDropdownOpen = !secretsKeyDropdownOpen; }} aria-haspopup="listbox" aria-expanded={secretsKeyDropdownOpen}>
            <span class="dd-label">{newSecretKeyLabel}</span>
            <span class="dd-arrow">{secretsKeyDropdownOpen ? '\u25B4' : '\u25BE'}</span>
          </button>
          {#if secretsKeyDropdownOpen}
            <div class="dd-menu" role="listbox">
              {#each availableKeysForAdd as key}
                <button class="dd-opt" class:active={newSecretKey === key} role="option" aria-selected={newSecretKey === key}
                  onclick={() => { newSecretKey = key; secretsKeyDropdownOpen = false; }}>
                  <span class="dd-opt-label">{getSecretKeyLabel(key)}</span>
                  <span class="dd-opt-hint">{key}</span>
                </button>
              {/each}
              {#if availableKeysForAdd.length === 0}<span class="dd-empty">All keys configured</span>{/if}
            </div>
          {/if}
        </div>
        <input type="password" class="text-input flex-fill" bind:value={newSecretValue} placeholder="Secret value" disabled={!newSecretKey} />
        <button class="btn-primary" onclick={handleSaveSecret} disabled={!newSecretKey || !newSecretValue || secretsSaving}>{secretsSaving ? 'Saving...' : 'Save'}</button>
      </div>
    </div>
  {/if}
</section>

<section class="section" id="setting-branch-policies">
  <h2>Branch Policies <span class="pro">Pro</span></h2>
  <div class="fields">
    {#if branchPolicies.length > 0}
      <div class="item-list">
        {#each branchPolicies as policy, idx}
          <div class="item-row">
            <span class="item-mono">{policy.pattern}</span>
            <span class="badge" class:block={policy.action === 'block'} class:warn={policy.action === 'warn'}>{policy.action}</span>
            <button class="icon-btn danger" title="Remove" onclick={() => removeBranchPolicy(idx)}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18"/><path d="M8 6V4h8v2"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"/></svg>
            </button>
          </div>
        {/each}
      </div>
    {/if}
    <div class="add-form">
      <div class="add-row">
        <input class="text-input flex-fill mono" value={newBranchPattern} placeholder="e.g. main, release/*"
          oninput={e => { newBranchPattern = (e.target as HTMLInputElement).value; }} />
        <div class="seg-group">
          <button class="seg-btn" class:active={newBranchAction === 'warn'} onclick={() => { newBranchAction = 'warn'; }}>Warn</button>
          <button class="seg-btn" class:active={newBranchAction === 'block'} onclick={() => { newBranchAction = 'block'; }}>Block</button>
        </div>
        <button class="btn-primary" onclick={addBranchPolicy} disabled={!newBranchPattern.trim()}>Add</button>
      </div>
    </div>
  </div>
</section>

<section class="section">
  <h2>Privacy &amp; Telemetry</h2>
  <div class="fields">
    <div class="field" id="setting-telemetry">
      <label class="lbl toggle-row">
        <span>Enable telemetry</span>
        <button class="toggle" class:on={telemetryEnabled} role="switch" aria-checked={telemetryEnabled}
          onclick={() => { telemetryEnabled = !telemetryEnabled; save('telemetry_enabled', String(telemetryEnabled)); }}>
          <span class="thumb"></span>
        </button>
      </label>
      <span class="hint">Send anonymous usage data to help improve BTerminal</span>
    </div>
    <div class="field" id="setting-retention">
      <label for="sec-retention" class="lbl">Data retention</label>
      <div class="num-row">
        <input id="sec-retention" type="number" min="1" max="365" value={retentionDays} class="num"
          onchange={e => { const n = parseInt((e.target as HTMLInputElement).value, 10); if (!isNaN(n) && n >= 1 && n <= 365) { retentionDays = n; save('data_retention_days', String(n)); } }} />
        <span class="unit">days</span>
      </div>
      <span class="hint">How long to keep session history and logs</span>
    </div>
  </div>
</section>

<style>
  .load-error { font-size: 0.75rem; color: var(--ctp-peach); margin: 0 0 0.25rem; }
  h2 { font-size: 0.875rem; font-weight: 600; color: var(--ctp-text); margin: 0 0 0.625rem; padding-bottom: 0.375rem; border-bottom: 1px solid var(--ctp-surface0); }
  .section { margin-bottom: 1.25rem; }
  .fields { display: flex; flex-direction: column; gap: 0.625rem; }
  .field { display: flex; flex-direction: column; gap: 0.25rem; }
  .lbl { font-size: 0.7rem; color: var(--ctp-subtext0); text-transform: uppercase; letter-spacing: 0.03em; }
  .hint { font-size: 0.625rem; color: var(--ctp-overlay0); }

  .toggle-row { display: flex; align-items: center; justify-content: space-between; cursor: pointer; }
  .toggle { position: relative; width: 2rem; height: 1.125rem; border: none; border-radius: 0.5625rem; background: var(--ctp-surface1); cursor: pointer; transition: background 0.2s; padding: 0; flex-shrink: 0; }
  .toggle.on { background: var(--ctp-blue); }
  .thumb { position: absolute; top: 0.125rem; left: 0.125rem; width: 0.875rem; height: 0.875rem; border-radius: 50%; background: var(--ctp-text); transition: transform 0.2s; }
  .toggle.on .thumb { transform: translateX(0.875rem); }

  .num-row { display: flex; align-items: center; gap: 0.25rem; }
  .num { width: 4.5rem; padding: 0.375rem 0.625rem; background: var(--ctp-surface0); border: 1px solid var(--ctp-surface1); border-radius: 0.25rem; color: var(--ctp-text); font-size: 0.8rem; -moz-appearance: textfield; }
  .num::-webkit-inner-spin-button, .num::-webkit-outer-spin-button { -webkit-appearance: none; }
  .unit { font-size: 0.7rem; color: var(--ctp-overlay0); }

  .pro { display: inline-block; font-size: 0.5625rem; padding: 0.0625rem 0.3125rem; background: var(--ctp-peach); color: var(--ctp-base); border-radius: 0.125rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.04em; vertical-align: middle; margin-left: 0.375rem; }
  .seg-group { display: flex; border-radius: 0.25rem; overflow: hidden; border: 1px solid var(--ctp-surface1); }
  .seg-btn { flex: 1; padding: 0.25rem 0.5rem; border: none; background: var(--ctp-surface0); color: var(--ctp-overlay1); font-size: 0.7rem; font-weight: 500; cursor: pointer; transition: background 0.12s, color 0.12s; }
  .seg-btn:not(:last-child) { border-right: 1px solid var(--ctp-surface1); }
  .seg-btn:hover { background: var(--ctp-surface1); color: var(--ctp-subtext1); }
  .seg-btn.active { background: color-mix(in srgb, var(--ctp-blue) 20%, var(--ctp-surface0)); color: var(--ctp-blue); font-weight: 600; }
  .btn-primary { padding: 0.3125rem 0.875rem; background: var(--ctp-blue); color: var(--ctp-base); border: none; border-radius: 0.25rem; font-size: 0.78rem; font-weight: 600; cursor: pointer; white-space: nowrap; transition: opacity 0.15s; }
  .btn-primary:hover { opacity: 0.9; }
  .btn-primary:disabled { opacity: 0.4; cursor: not-allowed; }

  /* Shared row patterns */
  .text-input { padding: 0.375rem 0.625rem; background: var(--ctp-surface0); border: 1px solid var(--ctp-surface1); border-radius: 0.25rem; color: var(--ctp-text); font-size: 0.8rem; }
  .text-input:focus { border-color: var(--ctp-blue); outline: none; }
  .text-input:disabled { opacity: 0.4; cursor: not-allowed; }
  .text-input.mono { font-family: var(--term-font-family, monospace); }
  .flex-fill { flex: 1; min-width: 0; }
  .item-list { display: flex; flex-direction: column; gap: 0.375rem; margin-bottom: 0.625rem; }
  .item-row { display: flex; align-items: center; gap: 0.5rem; padding: 0.375rem 0.625rem; background: var(--ctp-surface0); border: 1px solid var(--ctp-surface1); border-radius: 0.375rem; transition: border-color 0.15s; }
  .item-row:hover { border-color: var(--ctp-surface2); }
  .item-name { font-size: 0.78rem; font-weight: 600; color: var(--ctp-text); white-space: nowrap; }
  .item-sub { font-size: 0.625rem; color: var(--ctp-overlay0); font-family: var(--term-font-family, monospace); }
  .item-mono { flex: 1; font-size: 0.78rem; font-family: var(--term-font-family, monospace); color: var(--ctp-text); }
  .row-actions { display: flex; gap: 0.25rem; flex-shrink: 0; }
  .icon-btn { display: flex; align-items: center; justify-content: center; width: 1.75rem; height: 1.75rem; background: transparent; border: 1px solid var(--ctp-surface1); border-radius: 0.25rem; color: var(--ctp-overlay1); cursor: pointer; transition: color 0.15s, background 0.15s, border-color 0.15s; }
  .icon-btn:hover { color: var(--ctp-text); background: var(--ctp-surface0); border-color: var(--ctp-surface2); }
  .icon-btn.danger:hover { color: var(--ctp-red); background: color-mix(in srgb, var(--ctp-red) 8%, transparent); border-color: color-mix(in srgb, var(--ctp-red) 30%, var(--ctp-surface1)); }
  .add-form { padding: 0.5rem 0.625rem; background: var(--ctp-mantle); border: 1px dashed var(--ctp-surface1); border-radius: 0.375rem; }
  .add-row { display: flex; gap: 0.375rem; align-items: stretch; }

  /* Secrets-specific */
  .secrets-status { display: flex; align-items: center; gap: 0.5rem; margin-bottom: 0.625rem; }
  .dot { width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0; }
  .dot.available { background: var(--ctp-green); box-shadow: 0 0 4px color-mix(in srgb, var(--ctp-green) 50%, transparent); }
  .dot.unavailable { background: var(--ctp-red); box-shadow: 0 0 4px color-mix(in srgb, var(--ctp-red) 50%, transparent); }
  .keyring-label { font-size: 0.75rem; color: var(--ctp-subtext0); }
  .warning-box { display: flex; align-items: center; gap: 0.5rem; padding: 0.5rem 0.625rem; background: color-mix(in srgb, var(--ctp-red) 8%, var(--ctp-surface0)); border: 1px solid color-mix(in srgb, var(--ctp-red) 30%, var(--ctp-surface1)); border-radius: 0.375rem; color: var(--ctp-red); font-size: 0.75rem; line-height: 1.4; }
  .warning-box svg { flex-shrink: 0; }
  .secret-info { display: flex; flex-direction: column; gap: 0.0625rem; min-width: 0; flex-shrink: 0; }
  .secret-val { flex: 1; min-width: 0; display: flex; align-items: center; }
  .masked { color: var(--ctp-overlay0); font-size: 0.75rem; letter-spacing: 0.1em; }
  .val-input { width: 100%; padding: 0.25rem 0.5rem; background: var(--ctp-base); border: 1px solid var(--ctp-surface1); border-radius: 0.25rem; color: var(--ctp-text); font-size: 0.75rem; font-family: var(--term-font-family, monospace); }

  /* Dropdown */
  .custom-dropdown { position: relative; }
  .key-dropdown { min-width: 10rem; flex-shrink: 0; }
  .dd-trigger { display: flex; align-items: center; gap: 0.5rem; width: 100%; padding: 0.375rem 0.625rem; background: var(--ctp-surface0); border: 1px solid var(--ctp-surface1); border-radius: 0.25rem; color: var(--ctp-text); font-size: 0.8rem; cursor: pointer; text-align: left; height: 100%; }
  .dd-trigger:hover { border-color: var(--ctp-surface2); }
  .dd-label { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
  .dd-arrow { color: var(--ctp-overlay0); font-size: 0.7rem; flex-shrink: 0; }
  .dd-menu { position: absolute; top: calc(100% + 0.25rem); left: 0; min-width: 100%; width: max-content; max-height: 22.5rem; overflow-y: auto; background: var(--ctp-mantle); border: 1px solid var(--ctp-surface1); border-radius: 0.25rem; box-shadow: 0 0.5rem 1.5rem rgba(0, 0, 0, 0.4); z-index: 100; padding: 0.25rem 0; }
  .dd-opt { display: flex; align-items: center; gap: 0.5rem; width: 100%; padding: 0.3125rem 0.625rem; background: transparent; border: none; color: var(--ctp-subtext1); font-size: 0.8rem; cursor: pointer; text-align: left; white-space: nowrap; }
  .dd-opt:hover { background: var(--ctp-surface0); color: var(--ctp-text); }
  .dd-opt.active { background: var(--ctp-surface0); color: var(--ctp-text); font-weight: 600; }
  .dd-opt-label { flex: 1; }
  .dd-opt-hint { font-size: 0.625rem; color: var(--ctp-overlay0); font-family: var(--term-font-family, monospace); margin-left: auto; padding-left: 0.5rem; }
  .dd-empty { display: block; padding: 0.375rem 0.625rem; font-size: 0.75rem; color: var(--ctp-overlay0); font-style: italic; }

  /* Branch policy badge */
  .badge { font-size: 0.625rem; font-weight: 600; text-transform: uppercase; letter-spacing: 0.04em; padding: 0.125rem 0.375rem; border-radius: 0.125rem; }
  .badge.warn { background: color-mix(in srgb, var(--ctp-yellow) 15%, transparent); color: var(--ctp-yellow); }
  .badge.block { background: color-mix(in srgb, var(--ctp-red) 15%, transparent); color: var(--ctp-red); }
</style>
