<script lang="ts">
  import { onMount } from 'svelte';
  import { getSetting, setSetting } from '../../adapters/settings-bridge';
  import { ANCHOR_BUDGET_SCALES, ANCHOR_BUDGET_SCALE_LABELS, type AnchorBudgetScale } from '../../types/anchors';
  import { WAKE_STRATEGIES, WAKE_STRATEGY_LABELS, WAKE_STRATEGY_DESCRIPTIONS, type WakeStrategy } from '../../types/wake';
  import { handleError, handleInfraError } from '../../utils/handle-error';

  let stallThreshold = $state(15);
  let anchorBudget = $state<AnchorBudgetScale>('medium');
  let autoAnchor = $state(true);
  let wakeStrategy = $state<WakeStrategy>('persistent');
  let wakeThreshold = $state(50);
  let notifDesktop = $state(true);
  let notifTypes = $state<Set<string>>(new Set(['complete', 'error', 'crash', 'stall']));
  let memoryTtl = $state('');
  let memoryExtract = $state(false);
  let loadError = $state('');

  const NOTIF_TYPE_OPTIONS = ['complete', 'error', 'crash', 'stall'] as const;

  onMount(async () => {
    const results = await Promise.allSettled([
      getSetting('stall_threshold'), getSetting('anchor_budget_scale'), getSetting('auto_anchor'),
      getSetting('wake_strategy'), getSetting('wake_threshold'), getSetting('notif_desktop'),
      getSetting('notif_types'), getSetting('memory_ttl'), getSetting('memory_extract'),
    ]);
    let failCount = 0;
    if (results[0].status === 'fulfilled') { const v = results[0].value; if (v) { const n = parseInt(v, 10); if (!isNaN(n)) stallThreshold = n; } } else failCount++;
    if (results[1].status === 'fulfilled') { const v = results[1].value; if (v && ANCHOR_BUDGET_SCALES.includes(v as AnchorBudgetScale)) anchorBudget = v as AnchorBudgetScale; } else failCount++;
    if (results[2].status === 'fulfilled') autoAnchor = results[2].value !== 'false'; else failCount++;
    if (results[3].status === 'fulfilled') { const v = results[3].value; if (v && WAKE_STRATEGIES.includes(v as WakeStrategy)) wakeStrategy = v as WakeStrategy; } else failCount++;
    if (results[4].status === 'fulfilled') { const v = results[4].value; if (v) { const n = parseInt(v, 10); if (!isNaN(n)) wakeThreshold = n; } } else failCount++;
    if (results[5].status === 'fulfilled') notifDesktop = results[5].value !== 'false'; else failCount++;
    if (results[6].status === 'fulfilled') {
      const v = results[6].value;
      if (v) { try { const arr = JSON.parse(v); if (Array.isArray(arr)) notifTypes = new Set(arr); } catch (e) { handleInfraError(e, 'settings.parse.notif_types'); /* keep default */ } }
    } else failCount++;
    if (results[7].status === 'fulfilled') memoryTtl = results[7].value ?? ''; else failCount++;
    if (results[8].status === 'fulfilled') memoryExtract = results[8].value === 'true'; 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 toggleNotifType(type: string) {
    const next = new Set(notifTypes);
    if (next.has(type)) next.delete(type); else next.add(type);
    notifTypes = next;
    save('notif_types', JSON.stringify([...notifTypes]));
  }
</script>

{#if loadError}<p class="load-error">{loadError}</p>{/if}
<section class="section">
  <h2>Health Monitoring</h2>
  <div class="fields">
    <div class="field" id="setting-stall-threshold">
      <label for="orch-stall" class="lbl">Stall threshold</label>
      <div class="slider-row">
        <input id="orch-stall" type="range" min="5" max="60" step="5" bind:value={stallThreshold}
          onchange={() => save('stall_threshold', String(stallThreshold))} />
        <span class="slider-val">{stallThreshold} min</span>
      </div>
      <span class="hint">Agent marked as stalled after this idle duration</span>
    </div>
    <div class="field">
      <span class="lbl">Context pressure thresholds</span>
      <span class="hint">Configure warning and critical % in Agent Settings</span>
    </div>
  </div>
</section>

<section class="section">
  <h2>Session Anchors</h2>
  <div class="fields">
    <div class="field" id="setting-anchor-budget">
      <span class="lbl">Anchor budget scale</span>
      <div class="seg-group">
        {#each ANCHOR_BUDGET_SCALES as scale}
          <button class="seg-btn" class:active={anchorBudget === scale}
            onclick={() => { anchorBudget = scale; save('anchor_budget_scale', scale); }}>
            {ANCHOR_BUDGET_SCALE_LABELS[scale]}
          </button>
        {/each}
      </div>
      <span class="hint">Token budget reserved for re-injected anchor turns</span>
    </div>
    <div class="field" id="setting-auto-anchor">
      <label class="lbl toggle-row">
        <span>Auto-anchor on compaction</span>
        <button class="toggle" class:on={autoAnchor} role="switch" aria-checked={autoAnchor}
          onclick={() => { autoAnchor = !autoAnchor; save('auto_anchor', String(autoAnchor)); }}>
          <span class="thumb"></span>
        </button>
      </label>
      <span class="hint">Automatically anchor top turns when context compacts</span>
    </div>
  </div>
</section>

<section class="section">
  <h2>Wake Scheduler</h2>
  <div class="fields">
    <div class="field" id="setting-wake-strategy">
      <span class="lbl">Wake strategy</span>
      <div class="seg-group">
        {#each WAKE_STRATEGIES as strategy}
          <button class="seg-btn" class:active={wakeStrategy === strategy}
            onclick={() => { wakeStrategy = strategy; save('wake_strategy', strategy); }}>
            {WAKE_STRATEGY_LABELS[strategy]}
          </button>
        {/each}
      </div>
      <span class="hint">{WAKE_STRATEGY_DESCRIPTIONS[wakeStrategy]}</span>
    </div>
    {#if wakeStrategy === 'smart'}
      <div class="field" id="setting-wake-threshold">
        <label for="orch-wake-thresh" class="lbl">Wake threshold</label>
        <div class="slider-row">
          <input id="orch-wake-thresh" type="range" min="0" max="100" step="1" bind:value={wakeThreshold}
            onchange={() => save('wake_threshold', String(wakeThreshold))} />
          <span class="slider-val">{wakeThreshold}%</span>
        </div>
        <span class="hint">Manager only wakes when signal score exceeds this threshold</span>
      </div>
    {/if}
  </div>
</section>

<section class="section">
  <h2>Notifications</h2>
  <div class="fields">
    <div class="field" id="setting-notif-desktop">
      <label class="lbl toggle-row">
        <span>Desktop notifications</span>
        <button class="toggle" class:on={notifDesktop} role="switch" aria-checked={notifDesktop}
          onclick={() => { notifDesktop = !notifDesktop; save('notif_desktop', String(notifDesktop)); }}>
          <span class="thumb"></span>
        </button>
      </label>
      <span class="hint">Show OS-level notifications for agent events</span>
    </div>
    <div class="field" id="setting-notif-types">
      <span class="lbl">Notification types</span>
      <div class="chip-group">
        {#each NOTIF_TYPE_OPTIONS as type}
          <button class="chip" class:selected={notifTypes.has(type)} onclick={() => toggleNotifType(type)}>
            {type}
          </button>
        {/each}
      </div>
      <span class="hint">Which agent events trigger notifications</span>
    </div>
  </div>
</section>

<section class="section">
  <h2>Agent Memory</h2>
  <div class="fields">
    <div class="field" id="setting-memory-ttl">
      <label for="orch-ttl" class="lbl">Memory TTL <span class="pro">Pro</span></label>
      <div class="num-row">
        <input id="orch-ttl" type="number" min="1" max="365" value={memoryTtl} class="num" placeholder="30"
          onchange={e => { memoryTtl = (e.target as HTMLInputElement).value; save('memory_ttl', memoryTtl); }} />
        <span class="unit">days</span>
      </div>
      <span class="hint">Auto-expire extracted memories after this duration</span>
    </div>
    <div class="field" id="setting-memory-extract">
      <label class="lbl toggle-row">
        <span>Auto-extract insights <span class="pro">Pro</span></span>
        <button class="toggle" class:on={memoryExtract} role="switch" aria-checked={memoryExtract}
          onclick={() => { memoryExtract = !memoryExtract; save('memory_extract', String(memoryExtract)); }}>
          <span class="thumb"></span>
        </button>
      </label>
      <span class="hint">Automatically extract reusable insights from agent sessions</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); }

  .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; }

  .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); }

  .slider-row { display: flex; align-items: center; gap: 0.5rem; }
  .slider-row input[type="range"] {
    flex: 1; height: 0.25rem; -webkit-appearance: none; appearance: none;
    background: var(--ctp-surface1); border-radius: 0.125rem; outline: none;
  }
  .slider-row input[type="range"]::-webkit-slider-thumb {
    -webkit-appearance: none; width: 0.875rem; height: 0.875rem; border-radius: 50%;
    background: var(--ctp-blue); cursor: pointer; border: none;
  }
  .slider-val { font-size: 0.7rem; color: var(--ctp-text); font-weight: 600; min-width: 3rem; text-align: right; }

  .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); }

  .chip-group { display: flex; flex-wrap: wrap; gap: 0.25rem; }
  .chip {
    padding: 0.1875rem 0.5rem; border: 1px solid var(--ctp-surface1); border-radius: 0.75rem;
    background: var(--ctp-surface0); color: var(--ctp-overlay1); font-size: 0.65rem; font-weight: 500;
    cursor: pointer; transition: background 0.12s, color 0.12s, border-color 0.12s; text-transform: capitalize;
  }
  .chip:hover { background: var(--ctp-surface1); color: var(--ctp-subtext1); }
  .chip.selected { background: color-mix(in srgb, var(--ctp-blue) 15%, var(--ctp-surface0)); color: var(--ctp-blue); border-color: var(--ctp-blue); }

  .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;
  }
</style>
