<script>
  import { onMount } from 'svelte';
  import { ensureSession } from '../lib/api.js';

  const PHASES = ['normal_work', 'unease', 'suspicion', 'investigation', 'conflict', 'resolution'];

  let snapshot = null;
  let ending = null;
  let phaseInput = 'normal_work';
  let behaviorInput = { curiosity: 50, obedience: 50, risk: 50, suspicion: 0 };
  let status = '';

  async function dbgGet(path) {
    const token = await ensureSession();
    const res = await fetch(path, { headers: { Authorization: `Bearer ${token}` } });
    if (!res.ok) throw new Error(`${res.status}`);
    return res.json();
  }

  async function dbgPost(path, body) {
    const token = await ensureSession();
    const res = await fetch(path, {
      method: 'POST',
      headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
      body: JSON.stringify(body)
    });
    if (!res.ok) throw new Error(`${res.status}`);
    return res.json();
  }

  async function refresh() {
    try {
      const [raw, e] = await Promise.all([
        dbgGet('/api/debug/state'),
        dbgGet('/api/debug/ending')
      ]);
      snapshot = raw;
      ending = e;
      if (raw.behavior) behaviorInput = { ...raw.behavior };
      phaseInput = raw.narrative_phase ?? 'normal_work';
      status = '';
    } catch (err) {
      status = err.message;
    }
  }

  async function overrideBehavior() {
    try {
      await dbgPost('/api/debug/behavior', {
        curiosity: Number(behaviorInput.curiosity),
        obedience: Number(behaviorInput.obedience),
        risk:      Number(behaviorInput.risk),
        suspicion: Number(behaviorInput.suspicion)
      });
      await refresh();
      status = 'Behavior updated.';
    } catch (err) {
      status = err.message;
    }
  }

  async function forcePhase() {
    try {
      await dbgPost('/api/debug/phase', { phase: phaseInput });
      await refresh();
      status = `Phase set to ${phaseInput}.`;
    } catch (err) {
      status = err.message;
    }
  }

  onMount(refresh);
</script>

<aside class="dbg">
  <h3>Debug</h3>
  <button on:click={refresh}>Refresh</button>
  {#if status}<p class="st">{status}</p>{/if}

  {#if snapshot}
    <section>
      <h4>Phase</h4>
      <p>{snapshot.narrative_phase}</p>
      <select bind:value={phaseInput}>
        {#each PHASES as p}<option value={p}>{p}</option>{/each}
      </select>
      <button on:click={forcePhase}>Force</button>
    </section>

    <section>
      <h4>Behavior</h4>
      {#each ['curiosity', 'obedience', 'risk', 'suspicion'] as field}
        <label>{field}<input type="number" min="0" max="100" bind:value={behaviorInput[field]} /></label>
      {/each}
      <button on:click={overrideBehavior}>Apply</button>
    </section>

    <section>
      <h4>Ending</h4>
      <p>active: <strong>{ending?.active}</strong></p>
      <p>candidates: {ending?.candidates?.join(', ') || 'none'}</p>
    </section>

    <section>
      <h4>Hooks</h4>
      <p>{snapshot.hidden_hooks_discovered?.join(', ') || 'none'}</p>
    </section>
  {/if}
</aside>

<style>
  .dbg {
    position: fixed;
    bottom: 1rem;
    right: 1rem;
    width: 260px;
    background: #111;
    border: 1px solid #444;
    border-radius: 8px;
    padding: 1rem;
    font-size: 0.78rem;
    color: #ccc;
    z-index: 9999;
    max-height: 80vh;
    overflow-y: auto;
  }
  h3, h4 { margin: 0.4rem 0 0.2rem; color: #fff; }
  section { margin-bottom: 0.75rem; }
  label { display: block; margin-bottom: 0.2rem; }
  input { width: 55px; margin-left: 0.4rem; }
  select { width: 100%; margin-bottom: 0.4rem; }
  button { margin-right: 0.25rem; margin-top: 0.25rem; }
  .st { color: #8f8; margin: 0.2rem 0; }
</style>
