---
import { cn } from '../lib/cn'
import { includeDevUsers, USER_SECRET_TOKEN_REGEX_STRING } from '../lib/userSecretToken'

import InputText from './InputText.astro'

type Props = {
  name: string
  autofocus?: boolean
}

const { name, autofocus } = Astro.props
---

<input
  type="hidden"
  name="username"
  id="username"
  value=""
  autocomplete="username"
  data-keep-in-sync-with="#token"
  autocorrect="off"
  spellcheck="false"
  autocapitalize="off"
/>

<InputText
  label="Login Key"
  name={name}
  inputIcon="ri:key-2-line"
  inputIconClass="size-6"
  inputProps={{
    type: 'password',
    id: 'token',
    placeholder: 'ABCD-EFGH-IJKL-MNOP-1234',
    required: true,
    autofocus,
    pattern: USER_SECRET_TOKEN_REGEX_STRING,
    title: 'LLLL-LLLL-LLLL-LLLL-DDDD (L: letter, D: digit, dashes are optional)',
    minlength: includeDevUsers ? undefined : 24,
    maxlength: 24,
    autocomplete: 'current-password',
    autocorrect: 'off',
    spellcheck: 'false',
    autocapitalize: 'off',
    class: cn('2xs:text-lg h-10 font-mono text-sm uppercase'),
    'data-input-type-text-hack': true,
    'data-enable-token-autoformat': true,
    'data-bwautofill': true,
  }}
/>

<script>
  ////////////////////////////////////////////////////////////
  // Optional script for keeping username in sync.          //
  // This way the password manager detects the credentials. //
  ////////////////////////////////////////////////////////////

  document.addEventListener('astro:page-load', () => {
    const inputs = document.querySelectorAll<HTMLInputElement>('input[data-keep-in-sync-with]')
    inputs.forEach((input) => {
      const inputId = input.getAttribute('data-keep-in-sync-with')
      if (!inputId) throw new Error('Username input ID not found')

      const tokenInput = document.querySelector<HTMLInputElement>(inputId)
      if (!tokenInput) throw new Error('Token input not found')

      tokenInput.addEventListener('input', () => {
        input.value = tokenInput.value
        input.dispatchEvent(new Event('input', { bubbles: true }))
      })
    })
  })
</script>

<script>
  /////////////////////////////////////////////////////
  // Optional script for token input autoformatting //
  ////////////////////////////////////////////////////

  document.addEventListener('astro:page-load', () => {
    const tokenInputs = document.querySelectorAll<HTMLInputElement>('input[data-enable-token-autoformat]')

    tokenInputs.forEach((tokenInput) => {
      tokenInput.addEventListener('keydown', (e) => {
        const cursor = tokenInput.selectionStart
        if (tokenInput.selectionEnd !== cursor) return
        if (e.key === 'Delete') {
          if (cursor !== null && tokenInput.value[cursor] === '-') {
            tokenInput.selectionStart = cursor + 1
          }
        } else if (e.key === 'Backspace') {
          if (cursor !== null && cursor > 0 && tokenInput.value[cursor - 1] === '-') {
            tokenInput.selectionEnd = cursor - 1
          }
        }
      })

      tokenInput.addEventListener('input', () => {
        const value = tokenInput.value
        const cursor = tokenInput.selectionStart || 0

        // Count dashes before cursor to adjust position
        const dashesBeforeCursor = (value.substring(0, cursor).match(/-/g) || []).length

        // Remove all non-alphanumeric characters
        let cleaned = value.replace(/[^A-Za-z0-9]/g, '').toUpperCase()
        cleaned = cleaned.substring(0, 20) // Limit to 20 chars (24 with dashes)

        // Format with dashes
        let formatted = ''
        for (let i = 0; i < cleaned.length; i++) {
          if (i > 0 && i % 4 === 0) {
            formatted += '-'
          }
          formatted += cleaned[i]
        }

        // Only update if value changed
        if (formatted === value) return

        // Calculate new cursor position
        let newCursor = cursor
        const dashesBeforeNew = (formatted.substring(0, cursor).match(/-/g) || []).length
        newCursor += dashesBeforeNew - dashesBeforeCursor

        // Update input
        tokenInput.value = formatted
        tokenInput.setSelectionRange(newCursor, newCursor)
      })
    })
  })
</script>

<script>
  //////////////////////////////////////////////////////////////////////
  // Optional script for making the password visible.                 //
  // Otherwise the password manager will not detect it as a passowrd. //
  //////////////////////////////////////////////////////////////////////

  document.addEventListener('astro:page-load', () => {
    const inputs = document.querySelectorAll<HTMLInputElement>('input[data-input-type-text-hack]')
    inputs.forEach((input) => {
      input.addEventListener('input', () => {
        input.type = 'text'
      })
    })
  })
</script>
