<div class="space-y-6 min-w-[300px] max-w-md">
  <!-- Page Heading -->
  <h1 class="text-2xl font-semibold text-foreground tracking-tight">
    <%= intent === magicLinkResetIntent ? 'Reset password' : 'Create password' %>
  </h1>
  <% if (errorMessage) { %>
    <div class="rounded-md border border-red-200 bg-red-50 text-red-700 px-4 py-3 text-sm">
      <%= errorMessage %>
    </div>
  <% } %>
  <% if (infoMessage) { %>
    <div class="rounded-md border border-emerald-200 bg-emerald-50 text-emerald-700 px-4 py-3 text-sm">
      <%= infoMessage %>
    </div>
  <% } %>

  <p class="text-sm text-muted-foreground">
    <%= intent === magicLinkResetIntent
      ? 'Set a new password to secure your account.'
      : 'Set a strong password to finish. Use at least 8 characters, with upper & lower case letters and a number.' %>
  </p>

  <form id="password-setup-form" class="space-y-4" novalidate>
    <div class="space-y-1">
      <label for="new-password" class="block text-sm font-medium text-foreground">New password</label>
      <div class="relative">
        <input
          id="new-password"
          name="password"
          type="password"
          autocomplete="new-password"
          required
          minlength="8"
          class="w-full rounded-md border border-border bg-background px-3 py-2 text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-primary focus:border-primary pr-10"
          placeholder="••••••••"
        />
        <button
          type="button"
          id="toggle-password"
          class="absolute inset-y-0 right-0 px-3 text-muted-foreground hover:text-foreground transition-colors"
          aria-label="Toggle password visibility"
        >
          <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path id="eye-open" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
            <path id="eye-open-2" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path>
            <path id="eye-closed" class="hidden" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21"></path>
          </svg>
        </button>
      </div>
    </div>
    <div class="space-y-1">
      <label for="confirm-password" class="block text-sm font-medium text-foreground">Confirm password</label>
      <div class="relative">
        <input
          id="confirm-password"
          name="confirmPassword"
          type="password"
          autocomplete="new-password"
          required
          minlength="8"
          class="w-full rounded-md border border-border bg-background px-3 py-2 text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-primary focus:border-primary pr-10"
          placeholder="••••••••"
        />
        <button
          type="button"
          id="toggle-confirm-password"
          class="absolute inset-y-0 right-0 px-3 text-muted-foreground hover:text-foreground transition-colors"
          aria-label="Toggle password confirmation visibility"
        >
          <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path id="eye-confirm-open" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
            <path id="eye-confirm-open-2" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path>
            <path id="eye-confirm-closed" class="hidden" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21"></path>
          </svg>
        </button>
      </div>
    </div>

    <div class="rounded-md border border-border bg-muted/40 px-3 py-2 text-sm space-y-1" id="requirements">
      <div class="flex items-center gap-2 text-muted-foreground" id="req-length">• At least 8 characters</div>
      <div class="flex items-center gap-2 text-muted-foreground" id="req-upper">• Contains uppercase letter</div>
      <div class="flex items-center gap-2 text-muted-foreground" id="req-lower">• Contains lowercase letter</div>
      <div class="flex items-center gap-2 text-muted-foreground" id="req-digit">• Contains a number</div>
      <div class="flex items-center gap-2 text-muted-foreground" id="req-match">• Passwords match</div>
    </div>
    <button
      id="password-setup-submit"
      type="submit"
      class="w-full inline-flex justify-center items-center gap-2 py-2 px-4 rounded-md text-sm font-medium text-white bg-primary hover:bg-primary/90 transition-colors disabled:opacity-60"
    >
      Save password
    </button>
    <p id="password-setup-status" class="text-sm min-h-[20px]" aria-live="polite"></p>
  </form>
</div>

<script>
  const form = document.getElementById('password-setup-form');
  const submitBtn = document.getElementById('password-setup-submit');
  const statusEl = document.getElementById('password-setup-status');
  const passwordInput = document.getElementById('new-password');
  const confirmInput = document.getElementById('confirm-password');
  const togglePassword = document.getElementById('toggle-password');
  const toggleConfirm = document.getElementById('toggle-confirm-password');
  const resetIntent = '<%= intent || "" %>';
  const resetToken = '<%= resetToken || "" %>';

  const reqLength = document.getElementById('req-length');
  const reqUpper = document.getElementById('req-upper');
  const reqLower = document.getElementById('req-lower');
  const reqDigit = document.getElementById('req-digit');
  const reqMatch = document.getElementById('req-match');

  function setStatus(message, type = 'error') {
    if (!statusEl) return;
    statusEl.textContent = message || '';
    statusEl.classList.remove('text-red-600', 'text-emerald-700');
    statusEl.classList.add(type === 'success' ? 'text-emerald-700' : 'text-red-600');
  }

  function markRequirement(el, ok) {
    if (!el) return;
    el.classList.remove('text-muted-foreground', 'text-red-600', 'text-emerald-700');
    el.classList.add(ok ? 'text-emerald-700' : 'text-red-600');
  }

  function validate() {
    const pwd = passwordInput?.value || '';
    const conf = confirmInput?.value || '';
    const lengthOk = pwd.length >= 8;
    const upperOk = /[A-Z]/.test(pwd);
    const lowerOk = /[a-z]/.test(pwd);
    const digitOk = /\d/.test(pwd);
    const matchOk = pwd.length > 0 && pwd === conf;

    markRequirement(reqLength, lengthOk);
    markRequirement(reqUpper, upperOk);
    markRequirement(reqLower, lowerOk);
    markRequirement(reqDigit, digitOk);
    markRequirement(reqMatch, matchOk);

    if (submitBtn) {
      submitBtn.disabled = !(lengthOk && upperOk && lowerOk && digitOk && matchOk);
    }
  }

  function toggleInput(input, button) {
    if (!input || !button) return;
    const isPassword = input.type === 'password';
    input.type = isPassword ? 'text' : 'password';
    
    // Toggle SVG paths visibility
    const buttonId = button.id;
    const prefix = buttonId === 'toggle-password' ? 'eye' : 'eye-confirm';
    const openPaths = button.querySelectorAll(`#${prefix}-open, #${prefix}-open-2`);
    const closedPath = button.querySelector(`#${prefix}-closed`);
    
    if (isPassword) {
      // Showing password - show closed eye
      openPaths.forEach(path => path.classList.add('hidden'));
      closedPath?.classList.remove('hidden');
    } else {
      // Hiding password - show open eye
      openPaths.forEach(path => path.classList.remove('hidden'));
      closedPath?.classList.add('hidden');
    }
  }

  async function handlePasswordSubmit(event) {
    event.preventDefault();
    if (!form || !submitBtn) return;

    const password = form.password?.value;
    const confirmPassword = form.confirmPassword?.value;

    if (!password || !confirmPassword) {
      setStatus('Password and confirmation are required.');
      return;
    }
    if (password !== confirmPassword) {
      setStatus('Passwords do not match.');
      return;
    }
    if (password.length < 8) {
      setStatus('Password must be at least 8 characters.');
      return;
    }
    if (!/[A-Z]/.test(password) || !/[a-z]/.test(password) || !/\d/.test(password)) {
      setStatus('Password must include uppercase, lowercase letters and a number.');
      return;
    }

    submitBtn.disabled = true;
    setStatus('');

    try {
      const payload = { password };
      if (resetIntent) payload.intent = resetIntent;
      if (resetToken) payload.token = resetToken;

      const response = await fetch('/auth/password/setup', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
        redirect: 'follow',
      });

      if (response.redirected) {
        window.location.href = response.url;
        return;
      }

      const contentType = response.headers.get('content-type') || '';
      if (response.ok) {
        window.location.href = '/auth/password/success';
        return;
      }

      let message = 'Failed to set password. Please try again.';
      if (contentType.includes('application/json')) {
        const data = await response.json().catch(() => null);
        if (data?.error) message = data.error;
      } else {
        const text = await response.text().catch(() => '');
        if (text) message = text;
      }
      setStatus(message);
    } catch (error) {
      console.error('Password setup failed', error);
      setStatus('Unable to set password. Please try again.');
    } finally {
      submitBtn.disabled = false;
    }
  }

  form?.addEventListener('submit', handlePasswordSubmit);
  passwordInput?.addEventListener('input', validate);
  confirmInput?.addEventListener('input', validate);
  togglePassword?.addEventListener('click', () => toggleInput(passwordInput, togglePassword));
  toggleConfirm?.addEventListener('click', () => toggleInput(confirmInput, toggleConfirm));
  validate();
</script>
