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

  type WakeStrategy = 'persistent' | 'on-demand' | 'smart';
  type AnchorScale  = 'small' | 'medium' | 'large' | 'full';

  const WAKE_LABELS: Record<WakeStrategy, string> = {
    'persistent': 'Persistent',
    'on-demand':  'On-demand',
    'smart':      'Smart',
  };
  const WAKE_DESCS: Record<WakeStrategy, string> = {
    'persistent': 'Resume prompt whenever manager wakes',
    'on-demand':  'Fresh session on each wake',
    'smart':      'Threshold-gated on-demand',
  };

  const NOTIF_TYPES = ['complete', 'error', 'crash', 'stall'] as const;
  const ANCHOR_SCALES: AnchorScale[] = ['small', 'medium', 'large', 'full'];

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

  function persist(key: string, value: string) {
    appRpc?.request['settings.set']({ key, value }).catch(console.error);
  }

  function setWakeStrategy(v: WakeStrategy) {
    wakeStrategy = v;
    persist('wake_strategy', v);
  }

  function setWakeThreshold(v: number) {
    wakeThreshold = v;
    persist('wake_threshold', String(v));
  }

  function setAutoAnchor(v: boolean) {
    autoAnchor = v;
    persist('auto_anchor', String(v));
  }

  function setAnchorBudget(v: AnchorScale) {
    anchorBudget = v;
    persist('anchor_budget', v);
  }

  function setStallThreshold(v: number) {
    stallThreshold = v;
    persist('stall_threshold_global', String(v));
  }

  function setNotifDesktop(v: boolean) {
    notifDesktop = v;
    persist('notification_desktop', String(v));
  }

  function toggleNotif(t: string) {
    const next = new Set(notifTypes);
    next.has(t) ? next.delete(t) : next.add(t);
    notifTypes = next;
    persist('notification_types', JSON.stringify([...next]));
  }

  onMount(async () => {
    if (!appRpc) return;
    const { settings } = await appRpc.request['settings.getAll']({}).catch(() => ({ settings: {} }));
    if (settings['wake_strategy'])         wakeStrategy   = settings['wake_strategy'] as WakeStrategy;
    if (settings['wake_threshold'])        wakeThreshold  = parseInt(settings['wake_threshold'], 10) || 50;
    if (settings['auto_anchor'])           autoAnchor     = settings['auto_anchor'] !== 'false';
    if (settings['anchor_budget'])         anchorBudget   = settings['anchor_budget'] as AnchorScale;
    if (settings['stall_threshold_global']) stallThreshold = parseInt(settings['stall_threshold_global'], 10) || 15;
    if (settings['notification_desktop'])  notifDesktop   = settings['notification_desktop'] !== 'false';
    if (settings['notification_types']) {
      try { notifTypes = new Set(JSON.parse(settings['notification_types'])); } catch { /* ignore */ }
    }
  });
</script>

<div class="section">
  <h3 class="sh">Wake Strategy</h3>
  <div class="seg">
    {#each Object.keys(WAKE_LABELS) as s}
      <button class:active={wakeStrategy === s} onclick={() => setWakeStrategy(s as WakeStrategy)}>{WAKE_LABELS[s as WakeStrategy]}</button>
    {/each}
  </div>
  <p class="desc">{WAKE_DESCS[wakeStrategy]}</p>

  {#if wakeStrategy === 'smart'}
    <div class="slider-row">
      <label class="lbl" for="wake-thresh">Wake threshold</label>
      <input id="wake-thresh" type="range" min="0" max="100" step="5" value={wakeThreshold}
        oninput={e => setWakeThreshold(parseInt((e.target as HTMLInputElement).value, 10))} />
      <span class="slider-val">{wakeThreshold}%</span>
    </div>
  {/if}

  <h3 class="sh" style="margin-top: 0.875rem;">Session Anchors</h3>
  <label class="toggle-row">
    <span class="lbl">Auto-anchor on first compaction</span>
    <button class="toggle" class:on={autoAnchor} role="switch" aria-checked={autoAnchor}
      aria-label="Toggle auto-anchor"
      onclick={() => setAutoAnchor(!autoAnchor)}><span class="thumb"></span></button>
  </label>

  <span class="lbl" style="margin-top: 0.375rem;">Anchor budget scale</span>
  <div class="seg" style="margin-top: 0.25rem;">
    {#each ANCHOR_SCALES as s}
      <button class:active={anchorBudget === s} onclick={() => setAnchorBudget(s)}>
        {s[0].toUpperCase() + s.slice(1)}
      </button>
    {/each}
  </div>

  <h3 class="sh" style="margin-top: 0.875rem;">Health Monitoring</h3>
  <div class="slider-row">
    <label class="lbl" for="stall-thresh">Stall threshold</label>
    <input id="stall-thresh" type="range" min="5" max="60" step="5" value={stallThreshold}
      oninput={e => setStallThreshold(parseInt((e.target as HTMLInputElement).value, 10))} />
    <span class="slider-val">{stallThreshold} min</span>
  </div>

  <h3 class="sh" style="margin-top: 0.875rem;">Notifications</h3>
  <label class="toggle-row">
    <span class="lbl">Desktop notifications</span>
    <button class="toggle" class:on={notifDesktop} role="switch" aria-checked={notifDesktop}
      aria-label="Toggle desktop notifications"
      onclick={() => setNotifDesktop(!notifDesktop)}><span class="thumb"></span></button>
  </label>

  <div class="notif-types" style="margin-top: 0.375rem;">
    {#each NOTIF_TYPES as t}
      <label class="notif-chip" class:active={notifTypes.has(t)}>
        <input type="checkbox" checked={notifTypes.has(t)} onchange={() => toggleNotif(t)} aria-label="Notify on {t}" />
        {t}
      </label>
    {/each}
  </div>
</div>

<style>
  .section { display: flex; flex-direction: column; gap: 0.5rem; }
  .sh { margin: 0.125rem 0; font-size: 0.6875rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.06em; color: var(--ctp-overlay0); }
  .lbl { font-size: 0.8rem; color: var(--ctp-subtext0); }
  .desc { font-size: 0.75rem; color: var(--ctp-overlay1); margin: 0; font-style: italic; }

  .seg { display: flex; border-radius: 0.25rem; overflow: hidden; border: 1px solid var(--ctp-surface1); }
  .seg button { flex: 1; 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:hover { background: var(--ctp-surface1); color: var(--ctp-subtext1); }
  .seg button.active { background: color-mix(in srgb, var(--ctp-blue) 20%, var(--ctp-surface0)); color: var(--ctp-blue); font-weight: 600; }

  .slider-row { display: flex; align-items: center; gap: 0.5rem; }
  .slider-row input[type="range"] { flex: 1; accent-color: var(--ctp-blue); }
  .slider-val { font-size: 0.8rem; color: var(--ctp-text); min-width: 3rem; text-align: right; }

  .toggle-row { display: flex; align-items: center; justify-content: space-between; cursor: pointer; padding: 0.125rem 0; }
  .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; display: block; }
  .toggle.on .thumb { transform: translateX(0.875rem); }

  .notif-types { display: flex; flex-wrap: wrap; gap: 0.375rem; }
  .notif-chip { display: flex; align-items: center; gap: 0.25rem; padding: 0.2rem 0.5rem; border-radius: 0.25rem; font-size: 0.75rem; cursor: pointer; background: var(--ctp-surface0); border: 1px solid var(--ctp-surface1); color: var(--ctp-subtext0); transition: all 0.12s; }
  .notif-chip input { display: none; }
  .notif-chip.active { background: color-mix(in srgb, var(--ctp-blue) 15%, var(--ctp-surface0)); border-color: var(--ctp-blue); color: var(--ctp-blue); }
  .notif-chip:hover { border-color: var(--ctp-surface2); color: var(--ctp-subtext1); }
</style>
