<script lang="ts">
  import { onMount } from 'svelte';
  import { appRpc } from '../rpc.ts';
  import { PROVIDER_CAPABILITIES, type ProviderId } from '../provider-capabilities';
  import { setRetentionConfig } from '../agent-store.svelte.ts';

  const ANCHOR_SCALES = ['small', 'medium', 'large', 'full'] as const;
  type AnchorScale = typeof ANCHOR_SCALES[number];

  const PROVIDERS = Object.keys(PROVIDER_CAPABILITIES) as ProviderId[];

  interface ProjectConfig {
    id: string;
    name: string;
    provider: ProviderId;
    model: string;
    useWorktrees: boolean;
    useSandbox: boolean;
    stallThreshold: number;
    anchorScale: AnchorScale;
    customContext: string;
  }

  let projects = $state<ProjectConfig[]>([
    {
      id: 'p1', name: 'agent-orchestrator', provider: 'claude', model: 'claude-opus-4-5',
      useWorktrees: false, useSandbox: false, stallThreshold: 15, anchorScale: 'medium', customContext: '',
    },
    {
      id: 'p2', name: 'quanta-discord-bot', provider: 'claude', model: 'claude-sonnet-4-5',
      useWorktrees: false, useSandbox: false, stallThreshold: 15, anchorScale: 'medium', customContext: '',
    },
  ]);

  let selectedId = $state('p1');
  let proj = $derived(projects.find(p => p.id === selectedId)!);

  // Feature 6: Retention settings
  let sessionRetentionCount = $state(5);
  let sessionRetentionDays = $state(30);

  function updateProj(patch: Partial<ProjectConfig>) {
    projects = projects.map(p => p.id === selectedId ? { ...p, ...patch } : p);
    const updated = projects.find(p => p.id === selectedId)!;
    appRpc?.request['settings.setProject']({
      id: selectedId,
      config: JSON.stringify(updated),
    }).catch(console.error);
  }

  // Feature 6: Save retention settings
  function updateRetention(key: string, value: number) {
    if (key === 'count') sessionRetentionCount = value;
    else sessionRetentionDays = value;
    setRetentionConfig(sessionRetentionCount, sessionRetentionDays);
    appRpc?.request['settings.set']({
      key: key === 'count' ? 'session_retention_count' : 'session_retention_days',
      value: String(value),
    }).catch(console.error);
  }

  onMount(async () => {
    if (!appRpc) return;
    const res = await appRpc.request['settings.getProjects']({}).catch(() => ({ projects: [] }));
    if (res.projects.length > 0) {
      const loaded: ProjectConfig[] = res.projects.flatMap(({ config }) => {
        try { return [JSON.parse(config) as ProjectConfig]; } catch { return []; }
      });
      if (loaded.length > 0) projects = loaded;
    }
    // Feature 6: Load retention settings
    try {
      const { settings } = await appRpc.request['settings.getAll']({});
      if (settings['session_retention_count']) sessionRetentionCount = parseInt(settings['session_retention_count'], 10) || 5;
      if (settings['session_retention_days']) sessionRetentionDays = parseInt(settings['session_retention_days'], 10) || 30;
    } catch { /* use defaults */ }
  });
</script>

<div class="section">
  <h3 class="sh">Project</h3>
  <div class="proj-tabs">
    {#each projects as p}
      <button class="proj-tab" class:active={selectedId === p.id} onclick={() => selectedId = p.id}>{p.name}</button>
    {/each}
  </div>

  {#if proj}
    <h3 class="sh" style="margin-top: 0.75rem;">Provider</h3>
    <div class="seg">
      {#each PROVIDERS as prov}
        <button class:active={proj.provider === prov} onclick={() => updateProj({ provider: prov })}>{PROVIDER_CAPABILITIES[prov].label}</button>
      {/each}
    </div>

    <h3 class="sh" style="margin-top: 0.625rem;">Model</h3>
    <input
      class="text-in"
      value={proj.model}
      placeholder={PROVIDER_CAPABILITIES[proj.provider].defaultModel}
      onchange={e => updateProj({ model: (e.target as HTMLInputElement).value })}
    />

    <h3 class="sh" style="margin-top: 0.625rem;">Options</h3>
    <div class="toggle-fields">
      <label class="toggle-row">
        <span class="lbl">Worktree isolation</span>
        <button class="toggle" class:on={proj.useWorktrees} role="switch" aria-checked={proj.useWorktrees}
          aria-label="Toggle worktree isolation"
          onclick={() => updateProj({ useWorktrees: !proj.useWorktrees })}><span class="thumb"></span></button>
      </label>
      <label class="toggle-row">
        <span class="lbl">Landlock sandbox</span>
        <button class="toggle" class:on={proj.useSandbox} role="switch" aria-checked={proj.useSandbox}
          aria-label="Toggle Landlock sandbox"
          onclick={() => updateProj({ useSandbox: !proj.useSandbox })}><span class="thumb"></span></button>
      </label>
    </div>

    <h3 class="sh" style="margin-top: 0.625rem;">Stall threshold</h3>
    <div class="slider-row">
      <input type="range" min="5" max="60" step="5" value={proj.stallThreshold}
        oninput={e => updateProj({ stallThreshold: parseInt((e.target as HTMLInputElement).value, 10) })}
      />
      <span class="slider-val">{proj.stallThreshold} min</span>
    </div>

    <h3 class="sh" style="margin-top: 0.625rem;">Anchor budget</h3>
    <div class="seg">
      {#each ANCHOR_SCALES as s}
        <button class:active={proj.anchorScale === s} onclick={() => updateProj({ anchorScale: s })}>{s[0].toUpperCase() + s.slice(1)}</button>
      {/each}
    </div>

    <!-- Feature 6: Session retention controls -->
    <h3 class="sh" style="margin-top: 0.625rem;">Session retention</h3>
    <div class="slider-row">
      <span class="lbl">Keep last</span>
      <input type="range" min="1" max="20" step="1" value={sessionRetentionCount}
        oninput={e => updateRetention('count', parseInt((e.target as HTMLInputElement).value, 10))}
      />
      <span class="slider-val">{sessionRetentionCount}</span>
    </div>
    <div class="slider-row">
      <span class="lbl">Max age</span>
      <input type="range" min="1" max="90" step="1" value={sessionRetentionDays}
        oninput={e => updateRetention('days', parseInt((e.target as HTMLInputElement).value, 10))}
      />
      <span class="slider-val">{sessionRetentionDays}d</span>
    </div>

    <h3 class="sh" style="margin-top: 0.625rem;">Custom context</h3>
    <textarea
      class="prompt"
      rows="3"
      value={proj.customContext}
      placeholder="Custom system prompt context for this project..."
      onchange={e => updateProj({ customContext: (e.target as HTMLTextAreaElement).value })}
    ></textarea>
  {/if}
</div>

<style>
  .section { display: flex; flex-direction: column; gap: 0.4rem; }
  .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); }

  .proj-tabs { display: flex; gap: 0.25rem; flex-wrap: wrap; }
  .proj-tab { padding: 0.25rem 0.625rem; background: var(--ctp-surface0); border: 1px solid var(--ctp-surface1); border-radius: 0.25rem; color: var(--ctp-subtext0); font-size: 0.75rem; cursor: pointer; font-family: var(--ui-font-family); }
  .proj-tab:hover { color: var(--ctp-text); border-color: var(--ctp-surface2); }
  .proj-tab.active { border-color: var(--ctp-mauve); color: var(--ctp-mauve); background: color-mix(in srgb, var(--ctp-mauve) 10%, var(--ctp-surface0)); }

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

  .prompt { padding: 0.375rem 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(--term-font-family, monospace); resize: vertical; line-height: 1.4; }
  .prompt:focus { outline: none; border-color: var(--ctp-blue); }
  .prompt::placeholder { color: var(--ctp-overlay0); }

  .seg { display: flex; border-radius: 0.25rem; overflow: hidden; border: 1px solid var(--ctp-surface1); }
  .seg button { flex: 1; padding: 0.25rem 0.375rem; 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; }

  .toggle-fields { display: flex; flex-direction: column; gap: 0.375rem; }
  .toggle-row { display: flex; align-items: center; justify-content: space-between; cursor: pointer; padding: 0.25rem 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); }

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