"use client";

import { useState, type FormEvent } from "react";
import Link from "next/link";

function detectIdentifierType(value: string): "EMAIL" | "PHONE" {
  return value.includes("@") ? "EMAIL" : "PHONE";
}

export default function RequestPasswordResetPage() {
  const [identifierValue, setIdentifierValue] = useState("");
  const [submitted, setSubmitted] = useState(false);
  const [submitting, setSubmitting] = useState(false);

  async function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setSubmitting(true);

    try {
      await fetch("/api/auth/reset/request", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          identifierType: detectIdentifierType(identifierValue),
          identifierValue,
        }),
      });
    } finally {
      // Always show the same "check your inbox" message regardless of
      // outcome — the endpoint itself never reveals whether the
      // identifier matched an account (anti-enumeration, REQ-ACC-004).
      setSubmitting(false);
      setSubmitted(true);
    }
  }

  if (submitted) {
    return (
      <main style={{ maxWidth: 420, margin: "0 auto", padding: "2rem 1rem" }}>
        <h1>Check your email or phone</h1>
        <p>
          If that identifier matches an account, a 6-digit reset code has
          been sent. It expires in 15 minutes.
        </p>
        <p>
          <Link href="/reset/confirm">Enter the code</Link>
        </p>
      </main>
    );
  }

  return (
    <main style={{ maxWidth: 420, margin: "0 auto", padding: "2rem 1rem" }}>
      <h1>Reset your password</h1>
      <form onSubmit={handleSubmit}>
        <div style={{ marginBottom: "1rem" }}>
          <label htmlFor="identifier">Email or phone number</label>
          <input
            id="identifier"
            name="identifier"
            type="text"
            required
            autoComplete="username"
            value={identifierValue}
            onChange={(e) => setIdentifierValue(e.target.value)}
            style={{ display: "block", width: "100%" }}
          />
        </div>
        <button type="submit" disabled={submitting}>
          {submitting ? "Sending…" : "Send reset code"}
        </button>
      </form>
      <p>
        <Link href="/login">Back to log in</Link>
      </p>
    </main>
  );
}
