<?php
$page_title = 'Reset Password - Herbal Wellness';
$page_description = 'Reset your account password.';
$page_content = function () { ?>

<section class="max-w-md mx-auto my-20 p-8 bg-white rounded-2xl shadow-lg">
  <h1 class="serif text-2xl font-bold mb-2">Reset your password</h1>
  <p class="text-sm text-gray-500 mb-6">Enter a new password for your account.</p>

  <div class="flex flex-col gap-4">
    <div class="flex flex-col gap-2">
      <label for="password" class="text-sm font-semibold">New password</label>
      <input id="password" type="password" minlength="8" placeholder="At least 8 characters" required class="px-4 py-3 border rounded-lg focus:outline-none focus:ring-2 focus:ring-emerald-200">
    </div>

    <div class="flex flex-col gap-2">
      <label for="password2" class="text-sm font-semibold">Confirm password</label>
      <input id="password2" type="password" minlength="8" required class="px-4 py-3 border rounded-lg focus:outline-none focus:ring-2 focus:ring-emerald-200">
    </div>

    <div class="flex items-center gap-4 mt-2">
      <button id="btn" class="inline-flex items-center gap-2 px-5 py-3 rounded-lg bg-shining-green text-white font-bold">Reset password</button>
      <span id="status" class="text-sm text-gray-500"></span>
    </div>

    <p class="text-sm mt-4"><a href="/atasteofafricanmarketplace/index.php" class="text-shining-green underline">Back to Home</a></p>
  </div>
</section>

<script>
  const API_BASE = '/atasteofafricanmarketplace/api';
  const qs = new URLSearchParams(window.location.search);
  const selector = qs.get('selector');
  const token = qs.get('token');
  const status = document.getElementById('status');
  const btn = document.getElementById('btn');

  if (!selector || !token) {
    status.textContent = 'Invalid reset link.';
    btn.disabled = true;
    btn.classList.add('opacity-50', 'cursor-not-allowed');
  }

  btn.addEventListener('click', async () => {
    const p1 = document.getElementById('password').value;
    const p2 = document.getElementById('password2').value;
    if (p1.length < 8) { status.textContent = 'Password must be at least 8 characters.'; return; }
    if (p1 !== p2) { status.textContent = 'Passwords do not match.'; return; }
    status.textContent = 'Resetting...';
    try {
      const res = await fetch(`${API_BASE}/auth/reset_password.php`, {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ selector, token, password: p1 })
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.message || 'Failed to reset');
      status.textContent = 'Password reset successful. You can now log in.';
    } catch (e) {
      status.textContent = e.message;
    }
  });
</script>

<?php };
include __DIR__ . '/partials/layout.php';
