<script>
  import { link } from 'svelte-spa-router';
  import { onMount } from 'svelte';
  import Layout from '$/client/Layout.svelte';
  import api from "$/client/api.js";
  import Spinner from "$/client/components/Spinner.svelte";
  import { support_email } from "$/client/config.js";
  import { log } from "$/client/logging.js";

  export let params = {};
  let success;
  let reason;

  onMount(async () => {
    const [status, data] = await api.get('/api/email', {unsubkey: params.unsubkey});
    log.debug("failed result is", status, data);

    if(status === 200) {
      success = true;
    } else {
      success = false;
      reason = data.message || data._errors.unsubkey;
    }
  });
</script>

<style>
  card top {
    background-color: var(--color-bg-secondary);
    text-align: center;
  }

  card {
    width: 600px;
  }
</style>

<Layout testid="page-unsubscribe" centered={ true }>
  <card>
  <top>
    {#if success === true}
      <h1>You Are Now Unsubscribed</h1>
    {:else if success === false}
      <h1>Unsubscribe FAILED</h1>
    {/if}
  </top>

  <middle>
  {#if success === true}
    <p data-testid="unsubscribe-good">Your unsubscribe request will prevent this site from sending you marketing
      emails but system emails will still be delivered. System emails are:</p>
    <ol>
      <li>Password Reset Emails</li>
      <li>Password Change Notifications</li>
      <li>System Outage Notices</li>
      <li>Security Related Requests</li>
    </ol>
    <p>You don't need to do anything else, but if you change your mind go to <a href="/user/profile/" use:link>your User Profile</a> and click the checkbox to enable emails again.</p>
  {:else if success === false}
    <p data-testid="unsubscribe-fail">Your unsubscribe failed. The reason given is <code>{ reason }</code> If you think this is an error then please contact <a href="mailto:{support_email}">{ support_email }</a> with your email and the unsubscribe code <code>{ params.unsubkey }</code> so we can figure out what went wrong.
    </p>

    <p>You can also log in and unsubscribe in your User Profile.</p>
  {:else}
    <Spinner aspect_ratio="16/9" />
  {/if}
  </middle>
  <bottom>
  <button-group>
    <button><a href="/login" use:link>Login</a></button>
  </button-group>
  </bottom>
</Layout>
