<script>
  import { DateTime } from 'luxon';

  import PushSubscription from '$lib/components/PushSubscription.svelte';
  import { makeDeriver } from '$lib/swatch/derive.js';
  import EventLog from '$lib/components/swatch/EventLog.svelte';
  import EventCapture from '$lib/swatch/event-capture.svelte.js';
  import * as json from '$lib/swatch/json.js';

  function fromBase64(str) {
    if (str.trim().length === 0) {
      return null;
    }
    const bytes = Uint8Array.fromBase64(str, { alphabet: 'base64url' });
    return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
  }

  const base64Deriver = makeDeriver(fromBase64);

  // This is a "real" key, but it's not a key that's in use anywhere. I generated it for this
  // purpose. -o
  const testVapidKey =
    'BJXUH-WxM8BoxntTsrLufxc2Zlbwk-A1wsF01-ykUyh9pSUZG1Ymk3R-FOxJTGApQeJWIYTW9j-1sLQFIL8cGBU=';

  let vapidInput = $state('');
  let vapid = $derived(base64Deriver(vapidInput));

  // See <> for schema. This is an approximation of the browser subscription object.
  const testSubscription = json.encode({
    endpoint: 'https://push.example.com/1234',
    expirationTime: performance.now() + 86400 /* sec */ * 1000 /* millisec */,
    options: {
      userVisibleOnly: true,
      applicationServerKey: null,
    },
  });

  let subscriptionInput = $state('');
  let subscription = $derived(json.decode(subscriptionInput));

  let capture = $state(new EventCapture());
  const subscribe = capture.on('subscribe');
  const ping = capture.on('ping');
</script>

<h1><code>PushSubscription</code></h1>

<nav><p><a href=".">Back to swatches</a></p></nav>

<h2>properties</h2>

<div class="component-properties">
  <label>vapid key <input type="text" bind:value={vapidInput} /></label>
  <div class="suggestion">
    interesting values:
    <button onclick={() => (vapidInput = '')}>(none)</button>
    <button onclick={() => (vapidInput = testVapidKey)}>test key</button>
  </div>

  <label
    ><p>subscription (json)</p>
    <textarea bind:value={subscriptionInput}></textarea>
    <div class="suggestion">
      interesting values:
      <button onclick={() => (subscriptionInput = '')}>(none)</button>
      <button onclick={() => (subscriptionInput = testSubscription)}>example</button>
    </div>
  </label>
</div>

<h2>rendered</h2>

<div class="component-preview">
  <PushSubscription {vapid} {subscription} {subscribe} {ping} />
</div>

<h2>events</h2>

<EventLog events={capture.events} clear={capture.clear.bind(capture)} />
