<script>
  import { post } from "../lib/api.js";

  let currentPassword = $state("");
  let newPassword = $state("");
  let confirmPassword = $state("");
  let message = $state("");
  let error = $state("");
  let saving = $state(false);

  async function changePassword() {
    error = "";
    message = "";
    if (newPassword !== confirmPassword) { error = "Passwords do not match"; return; }
    if (newPassword.length < 8) { error = "Password must be at least 8 characters"; return; }
    saving = true;
    try {
      await post("/auth/change-password", { current_password: currentPassword, new_password: newPassword });
      message = "Password changed successfully";
      currentPassword = ""; newPassword = ""; confirmPassword = "";
    } catch (e) {
      error = e.body?.detail || "Failed to change password";
    }
    saving = false;
  }
</script>

<div class="space-y-6">
  <div>
    <h1 class="text-2xl font-bold text-surface-900 tracking-tight">Settings</h1>
    <p class="text-sm text-surface-400 mt-1">Account and security settings</p>
  </div>

  <div class="bg-white rounded-xl border border-surface-200 p-6 shadow-sm max-w-md">
    <h3 class="text-sm font-semibold text-surface-700 mb-4">Change Password</h3>

    {#if message}
      <div class="text-sm text-emerald-600 bg-emerald-50 px-3 py-2 rounded-lg mb-4">{message}</div>
    {/if}
    {#if error}
      <div class="text-sm text-rose-600 bg-rose-50 px-3 py-2 rounded-lg mb-4">{error}</div>
    {/if}

    <form onsubmit={(e) => { e.preventDefault(); changePassword(); }} class="space-y-3">
      <div>
        <label class="block text-xs font-medium text-surface-500 mb-1">Current Password</label>
        <input type="password" bind:value={currentPassword} required class="w-full px-3 py-2 text-sm border border-surface-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500" />
      </div>
      <div>
        <label class="block text-xs font-medium text-surface-500 mb-1">New Password</label>
        <input type="password" bind:value={newPassword} required class="w-full px-3 py-2 text-sm border border-surface-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500" />
      </div>
      <div>
        <label class="block text-xs font-medium text-surface-500 mb-1">Confirm New Password</label>
        <input type="password" bind:value={confirmPassword} required class="w-full px-3 py-2 text-sm border border-surface-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500" />
      </div>
      <button type="submit" disabled={saving} class="w-full px-4 py-2 text-sm font-medium text-white bg-primary-600 hover:bg-primary-700 rounded-lg transition-colors disabled:opacity-50">
        {saving ? "Saving..." : "Change Password"}
      </button>
    </form>
  </div>
</div>
