---
import BaseLayout from '../../layouts/BaseLayout.astro';
import {
  verifyInviteTokenFormat, hashToken, createSession, hashPassword,
} from '../../lib/auth';
import { getInviteByTokenHash, redeemInvite, createUserFromInvite } from '../../lib/db';

const { token } = Astro.params;

// Validate token format before any DB work
if (!token || !verifyInviteTokenFormat(token)) {
  return Astro.redirect('/login');
}

const tokenHash = hashToken(token);
const invite = getInviteByTokenHash(tokenHash);

const isExpired = invite ? new Date(invite.expires_at) < new Date() : false;
const isUsed = invite ? invite.used_at !== null : false;
const isInvalid = !invite || isExpired || isUsed;

let error: string | null = null;

if (!isInvalid && Astro.request.method === 'POST') {
  const data = await Astro.request.formData();
  const password  = String(data.get('password') ?? '');
  const password2 = String(data.get('password2') ?? '');

  if (password.length < 8) {
    error = 'Password must be at least 8 characters.';
  } else if (password !== password2) {
    error = 'Passwords do not match.';
  } else {
    const hash = hashPassword(password);
    const user = createUserFromInvite(invite!, hash);
    redeemInvite(invite!.id);
    createSession(user.id, Astro.cookies);
    return Astro.redirect('/');
  }
}
---
<BaseLayout title="Accept invitation">
  <div class="page">
    <div class="card">
      <img src="/logo.svg" alt="Fenja AI" class="wordmark" />
      <h1 class="headline-md title">You have been invited.</h1>

      {isInvalid ? (
        <div>
          <p class="body-md error-msg">
            {!invite
              ? 'This invitation link is not valid.'
              : isUsed
                ? 'This invitation has already been used.'
                : 'This invitation has expired.'
            }
          </p>
          <a href="/login" class="body-sm back-link">Go to sign in</a>
        </div>
      ) : (
        <div class="invite-body">
          <p class="body-md welcome">
            Welcome, <strong>{invite!.name}</strong> from {invite!.organisation}.
            Set a password to activate your account.
          </p>

          {error && (
            <p class="error body-sm" role="alert">{error}</p>
          )}

          <form method="POST" class="form" novalidate>
            <div class="field">
              <label for="password" class="label-sm field-label">Password</label>
              <input
                type="password"
                id="password"
                name="password"
                class="input body-md"
                autocomplete="new-password"
                required
                minlength="8"
                autofocus
              />
            </div>

            <div class="field">
              <label for="password2" class="label-sm field-label">Confirm password</label>
              <input
                type="password"
                id="password2"
                name="password2"
                class="input body-md"
                autocomplete="new-password"
                required
              />
            </div>

            <button type="submit" class="btn-primary body-md">Activate account</button>
          </form>
        </div>
      )}
    </div>
  </div>
</BaseLayout>

<style>
  .page {
    min-height: 100vh;
    background: var(--background);
    display: flex;
    align-items: center;
    justify-content: center;
    padding: var(--space-8);
  }

  .card {
    width: 100%;
    max-width: 28rem;
    background: var(--surface-container-lowest);
    border-radius: var(--radius-lg);
    padding: var(--space-10) var(--space-8);
    display: flex;
    flex-direction: column;
    gap: var(--space-4);
  }

  .wordmark {
    height: 22px;
    width: auto;
    display: block;
    margin-bottom: var(--space-2);
  }

  .title {
    font-family: var(--font-serif);
    letter-spacing: var(--tracking-snug);
    margin: 0;
  }

  .error-msg {
    color: var(--pigment-terracotta);
    margin: 0 0 var(--space-4);
  }

  .back-link {
    color: var(--on-surface-variant);
  }

  .invite-body {
    display: flex;
    flex-direction: column;
    gap: var(--space-4);
  }

  .welcome {
    color: var(--on-surface-variant);
    margin: 0;
  }

  .error {
    padding: var(--space-3) var(--space-4);
    background: rgba(185, 107, 88, 0.08);
    border-radius: var(--radius-sm);
    color: var(--pigment-terracotta);
    margin: 0;
  }

  .form {
    display: flex;
    flex-direction: column;
    gap: var(--space-5);
  }

  .field {
    display: flex;
    flex-direction: column;
    gap: var(--space-2);
  }

  .field-label {
    letter-spacing: var(--tracking-wide);
    text-transform: uppercase;
    color: var(--on-surface-variant);
  }

  .input {
    width: 100%;
    padding: var(--space-3) var(--space-4);
    background: var(--background);
    border: var(--ghost-border);
    border-radius: var(--radius-sm);
    font-family: var(--font-sans);
    font-size: var(--text-body-md);
    color: var(--on-surface);
    outline: none;
    transition: border-color var(--duration-fast) var(--ease-standard),
                box-shadow var(--duration-fast) var(--ease-standard);
    box-sizing: border-box;
  }
  .input:focus {
    border-color: var(--secondary);
    box-shadow: 0 0 0 3px rgba(120, 95, 83, 0.12);
  }

  .btn-primary {
    display: block;
    width: 100%;
    padding: var(--space-3) var(--space-5);
    background: linear-gradient(180deg, var(--secondary) 0%, var(--secondary-dim) 100%);
    color: var(--on-secondary);
    border: none;
    border-radius: var(--radius-md);
    font-family: var(--font-sans);
    font-size: var(--text-body-md);
    font-weight: 600;
    letter-spacing: var(--tracking-snug);
    cursor: pointer;
    transition: opacity var(--duration-fast) var(--ease-standard);
  }
  .btn-primary:hover {
    opacity: 0.9;
  }
</style>
