<script lang="ts">
  import { createEventDispatcher, onDestroy, onMount } from 'svelte';
  import { preferences } from '$lib/stores/preferencesStore';

  const dispatch = createEventDispatcher<{ done: void }>();

  let stage: 'identity' | 'system' = 'identity';
  let reducedMotion = false;
  let progress = 0;
  let statusIndex = 0;
  let statusTimer: number | undefined;
  let stageTimer: number | undefined;

  const bootLines = [
    'load professional history',
    'mount creative projects',
    'initialise charity mode',
    'index questionable decisions',
    'suppress unnecessary corporate adjectives',
    'warn user: opinions detected'
  ];

  const identityWords = [
    { text: 'backed by evidence.', className: 'word-a' },
    { text: 'verifiable.', className: 'word-b' },
    { text: 'proven on record.', className: 'word-c' },
    { text: 'authenticated.', className: 'word-d' },
    { text: 'trust comes from what can be checked.', className: 'word-e' },
    { text: 'independently.', className: 'word-f' },
    { text: 'nothing else matters.', className: 'word-g' },
    { text: 'proof beats promises.', className: 'word-h' },
    { text: 'everything else fades.', className: 'word-i' }
  ];

  function goNext() {
    if (stage === 'identity') {
      stage = 'system';
      runSystemBoot();
      return;
    }

    finish();
  }

  function finish() {
    preferences.markBootSeen();
    dispatch('done');
  }

  function onKeydown(event: KeyboardEvent) {
    if (event.key === 'Enter' || event.key === ' ') {
      event.preventDefault();
      goNext();
    }
  }

  function runSystemBoot() {
    if (statusTimer) window.clearInterval(statusTimer);
    progress = reducedMotion ? 100 : 12;
    statusIndex = 0;

    if (reducedMotion) {
      statusIndex = bootLines.length - 1;
      return;
    }

    statusTimer = window.setInterval(() => {
      statusIndex = Math.min(statusIndex + 1, bootLines.length - 1);
      progress = Math.min(progress + 16, 100);
      if (progress >= 100 && statusTimer) window.clearInterval(statusTimer);
    }, 520);
  }

  onMount(() => {
    reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    window.addEventListener('keydown', onKeydown);

    if (!reducedMotion) {
      stageTimer = window.setTimeout(() => {
        stage = 'system';
        runSystemBoot();
      }, 2600);
    }
  });

  onDestroy(() => {
    if (typeof window === 'undefined') return;
    window.removeEventListener('keydown', onKeydown);
    if (statusTimer) window.clearInterval(statusTimer);
    if (stageTimer) window.clearTimeout(stageTimer);
  });
</script>

<section class="boot-screen" aria-label="ianOS boot screen">
  {#if stage === 'identity'}
    <div class="boot-identity" aria-live="polite">
      <h1>Hi, I'm <strong>Ian.</strong></h1>
      <div class="identity-grid" aria-label="Identity proof points">
        {#each identityWords as word}
          <span class={word.className}>{word.text}</span>
        {/each}
      </div>
      <p class="identity-footnote">
        Apologies, but cold approaches are filtered. Trust comes from established channels,
        context and things that can be checked.
      </p>
      <div class="boot-actions">
        <button type="button" on:click={goNext}>Continue boot</button>
        <a href="/simple">Simple Mode</a>
      </div>
    </div>
  {:else}
    <div class="boot-console" aria-live="polite">
      <p class="boot-ascii" aria-hidden="true">
        +-----------------------------+<br />
        | ianOS                       |<br />
        | useful systems // mischief  |<br />
        +-----------------------------+
      </p>
      <h1>ianOS</h1>
      <p>Ian Barrs<br />useful systems // useful mischief</p>
      <ol>
        {#each bootLines as line, index}
          <li class:active={index <= statusIndex}>[{index <= statusIndex ? 'ok' : '..'}] {line}</li>
        {/each}
      </ol>
      <div class="progress" aria-label="Boot progress" aria-valuemin="0" aria-valuemax="100" aria-valuenow={progress}>
        <span style={`width: ${progress}%`}></span>
      </div>
      <p class="boot-footer">No tracking. No autoplay. No beige.</p>
      <div class="boot-actions">
        <button type="button" on:click={finish}>Enter ianOS</button>
        <a href="/simple">Simple Mode</a>
      </div>
    </div>
  {/if}
</section>
