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

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

  const WAKE_OPTIONS = [
    { value: 'persistent', label: 'Persistent' },
    { value: 'on-demand',  label: 'On-demand' },
    { value: 'smart',      label: '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_OPTIONS = [
    { value: 'small', label: 'Small' },
    { value: 'medium', label: 'Medium' },
    { value: 'large', label: 'Large' },
    { value: 'full', label: '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: string) {
    wakeStrategy = v as WakeStrategy;
    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: string) {
    anchorBudget = v as AnchorScale;
    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>

<Section heading="Wake Strategy">
  <SegmentedControl options={WAKE_OPTIONS} selected={wakeStrategy} onSelect={setWakeStrategy} />
  <p class="desc">{WAKE_DESCS[wakeStrategy]}</p>

  {#if wakeStrategy === 'smart'}
    <SliderInput
      label="Wake threshold"
      id="wake-thresh"
      min={0} max={100} step={5}
      value={wakeThreshold}
      onChange={setWakeThreshold}
      format={v => `${v}%`}
    />
  {/if}
</Section>

<Section heading="Session Anchors" spaced>
  <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>
  <SegmentedControl options={ANCHOR_OPTIONS} selected={anchorBudget} onSelect={setAnchorBudget} />
</Section>

<Section heading="Health Monitoring" spaced>
  <SliderInput
    label="Stall threshold"
    id="stall-thresh"
    min={5} max={60} step={5}
    value={stallThreshold}
    onChange={setStallThreshold}
    format={v => `${v} min`}
  />
</Section>

<Section heading="Notifications" spaced>
  <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 nt}
      <CustomCheckbox
        checked={notifTypes.has(nt)}
        label={nt}
        onChange={() => toggleNotif(nt)}
      />
    {/each}
  </div>
</Section>

<style>
  .lbl { font-size: 0.8rem; color: var(--ctp-subtext0); }
  .desc { font-size: 0.75rem; color: var(--ctp-overlay1); margin: 0; font-style: italic; }

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