---
import { Icon } from 'astro-icon/components'
import { actions } from 'astro:actions'

import Button from '../../components/Button.astro'
import CopyButton from '../../components/CopyButton.astro'
import { SUPPORT_EMAIL } from '../../constants/project'
import MiniLayout from '../../layouts/MiniLayout.astro'
import { prettifyUserSecretToken } from '../../lib/userSecretToken'

const result = Astro.getActionResult(actions.account.generate)
if (result?.error) return Astro.redirect('/account/generate')

const prettyToken = result ? prettifyUserSecretToken(result.data.token) : null
---

<MiniLayout
  pageTitle="Welcome"
  description="New account welcome page"
  ogImage={{
    template: 'generic',
    title: 'Welcome',
    description: 'New account welcome page',
    icon: 'ri:key-2-line',
  }}
  layoutHeader={{
    icon: 'ri:key-2-line',
    title: 'Save your Login Key',
    subtitle: 'You need it to login to your account',
  }}
  breadcrumbs={[
    {
      name: 'Accounts',
      url: '/account',
    },
    {
      name: 'Welcome',
    },
  ]}
>
  {
    prettyToken ? (
      <>
        <div class="mb-2 flex items-center gap-3 rounded-md bg-red-900/80 p-2 text-red-200">
          <Icon name="ri:delete-bin-line" class="size-5 flex-shrink-0" />
          <p class="text-sm text-pretty">Won't show again and can't be recovered!</p>
        </div>
        <div class="border-day-800 js:pr-24 bg-night-800 relative rounded-md border p-3 font-mono break-all text-white">
          {prettyToken}
          <div class="absolute inset-y-0 right-2 flex items-center">
            <CopyButton copyText={prettyToken} size="sm" color="success" />
          </div>
        </div>

        <p class="text-day-500 mt-1 text-center text-sm text-balance">
          Save it in a <span class="text-day-200 font-medium">password manager</span>
          or <span class="text-day-200 font-medium">secure location</span>
        </p>

        <form method="GET" action="/" class="mt-8 space-y-4">
          <div class="flex items-center gap-4">
            <input type="checkbox" id="confirm-saved" required />
            <label for="confirm-saved" class="text-day-400 text-sm text-pretty">
              I saved my Login Key
            </label>
          </div>

          <Button type="submit" class="w-full" color="gray" label="Continue" />
        </form>
      </>
    ) : (
      <>
        <div class="mt-12 flex items-center justify-center gap-3 rounded-md bg-red-900/80 p-3 text-red-200">
          <Icon name="ri:alert-line" class="size-5 flex-shrink-0" />
          <p class="text-sm text-pretty">Your Login Key can't be shown again</p>
        </div>

        <p class="text-day-300 mt-2 text-center text-sm text-balance">
          If you lost it, contact us at
          <a href={`mailto:${SUPPORT_EMAIL}`} class="text-green-400 hover:underline focus-visible:underline">
            {SUPPORT_EMAIL}
          </a>
        </p>
      </>
    )
  }
</MiniLayout>

<script>
  ////////////////////////////////////////////////////////////
  // Optional script for preventing accidental navigation.  //
  // Shows a warning if the user tries to leave without    //
  // confirming they saved their token.                    //
  ////////////////////////////////////////////////////////////

  const beforeUnloadHandler = (event: BeforeUnloadEvent) => {
    event.preventDefault()
    // Included for legacy support, e.g. Chrome/Edge < 119
    event.returnValue = true
  }
  window.addEventListener('beforeunload', beforeUnloadHandler)

  document.addEventListener('astro:after-swap', () => {
    window.removeEventListener('beforeunload', beforeUnloadHandler)
  })

  document.addEventListener('astro:page-load', () => {
    const confirmSavedInput = document.querySelectorAll<HTMLInputElement>('#confirm-saved')
    confirmSavedInput.forEach((input) => {
      input.addEventListener('input', () => {
        if (input.checked) {
          window.addEventListener('beforeunload', beforeUnloadHandler)
        } else {
          window.removeEventListener('beforeunload', beforeUnloadHandler)
        }
      })
    })
  })
</script>
