// BEGIN CHANGE: Lost Account (paridade lostaccount.php)
"use client";

import { useEffect, useState, FormEvent } from "react";
import Link from "next/link";
import { useI18n } from "@/i18n/LanguageProvider";
import { Navbar } from "@/components/Navbar";
import { Footer } from "@/components/Footer";
import { apiUrl } from "@/lib/api";

type Mode = "pick" | "email" | "reckey" | "code";

export default function LostAccountPage() {
  const { t } = useI18n();
  const [mode, setMode] = useState<Mode>("pick");
  const [character, setCharacter] = useState("");
  const [email, setEmail] = useState("");
  const [key, setKey] = useState("");
  const [code, setCode] = useState("");
  const [pass, setPass] = useState("");
  const [pass2, setPass2] = useState("");
  const [busy, setBusy] = useState(false);
  const [msg, setMsg] = useState("");
  const [err, setErr] = useState("");

  useEffect(() => {
    const q = new URLSearchParams(window.location.search);
    if (q.get("action") === "checkcode") {
      setMode("code");
      setCode(q.get("code") || "");
      setCharacter(q.get("character") || "");
    }
  }, []);

  async function post(body: Record<string, unknown>) {
    setBusy(true);
    setMsg("");
    setErr("");
    try {
      const r = await fetch(apiUrl("lost-account.php"), {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });
      const j = await r.json().catch(() => ({}));
      if (!r.ok || !j.ok) {
        const code = j?.errors ? String(Object.values(j.errors)[0] ?? "") : "";
        if (code === "send_failed") setErr(t.auth.lostMailFailed);
        else if (code === "rate_limit") setErr(t.auth.lostMailRate);
        else if (code === "mismatch") setErr(t.auth.lostMailMismatch);
        else if (code === "invalid" || code === "pass_format" || code === "email_invalid")
          setErr(t.auth.lostInvalid);
        else setErr(t.auth.accountFailed);
        return false;
      }
      setMsg(j.sent ? t.auth.lostMailSent : t.auth.accountSaved);
      return true;
    } catch {
      setErr(t.auth.accountFailed);
      return false;
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="flex min-h-screen flex-col">
      <Navbar />
      <main className="mx-auto w-full max-w-lg flex-1 px-6 py-14">
        <h1 className="text-3xl font-semibold tracking-tight">{t.auth.lostAccount}</h1>
        <p className="mt-2 text-sm text-muted">
          <Link href="/login" className="text-brand hover:underline">
            {t.auth.loginNow}
          </Link>
        </p>

        {(msg || err) && (
          <p className={`mt-4 text-sm ${err ? "text-red-400" : "text-brand"}`}>{err || msg}</p>
        )}

        {mode === "pick" && (
          <div className="mt-8 space-y-4 rounded-xl border border-border bg-panel p-6">
            <label className="block text-sm">
              {t.auth.charName}
              <input
                value={character}
                onChange={(e) => setCharacter(e.target.value)}
                className="mt-1 w-full rounded border border-border bg-background px-3 py-2 text-sm"
              />
            </label>
            <div className="flex flex-col gap-2">
              <button
                type="button"
                disabled={!character.trim()}
                className="rounded-lg bg-brand px-4 py-2 text-sm font-medium text-background disabled:opacity-50"
                onClick={() => setMode("email")}
              >
                {t.auth.email}
              </button>
              <button
                type="button"
                disabled={!character.trim()}
                className="rounded-lg border border-border px-4 py-2 text-sm disabled:opacity-50"
                onClick={() => setMode("reckey")}
              >
                {t.auth.recoveryKey}
              </button>
            </div>
          </div>
        )}

        {mode === "email" && (
          <form
            className="mt-8 space-y-3 rounded-xl border border-border bg-panel p-6"
            onSubmit={async (e: FormEvent) => {
              e.preventDefault();
              await post({ action: "send_code", character, email });
            }}
          >
            <p className="text-sm text-muted">{character}</p>
            <input
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder={t.auth.email}
              className="w-full rounded border border-border bg-background px-3 py-2 text-sm"
            />
            <button
              type="submit"
              disabled={busy}
              className="rounded-lg bg-brand px-4 py-2 text-sm font-medium text-background disabled:opacity-50"
            >
              {t.auth.email}
            </button>
            <button type="button" className="block text-xs text-muted" onClick={() => setMode("pick")}>
              {t.guilds.back}
            </button>
          </form>
        )}

        {mode === "reckey" && (
          <form
            className="mt-8 space-y-3 rounded-xl border border-border bg-panel p-6"
            onSubmit={async (e: FormEvent) => {
              e.preventDefault();
              const ok = await post({
                action: "recover_by_key",
                character,
                key,
                email,
                newPassword: pass,
                newPassword2: pass2,
              });
              if (ok) window.location.href = "/login";
            }}
          >
            <p className="text-sm text-muted">{character}</p>
            <input
              value={key}
              onChange={(e) => setKey(e.target.value)}
              placeholder={t.auth.recoveryKey}
              className="w-full rounded border border-border bg-background px-3 py-2 text-sm"
            />
            <input
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder={t.auth.email}
              className="w-full rounded border border-border bg-background px-3 py-2 text-sm"
            />
            <input
              type="password"
              value={pass}
              onChange={(e) => setPass(e.target.value)}
              placeholder={t.auth.newPassword}
              className="w-full rounded border border-border bg-background px-3 py-2 text-sm"
            />
            <input
              type="password"
              value={pass2}
              onChange={(e) => setPass2(e.target.value)}
              placeholder={t.auth.confirmPassword}
              className="w-full rounded border border-border bg-background px-3 py-2 text-sm"
            />
            <button
              type="submit"
              disabled={busy}
              className="rounded-lg bg-brand px-4 py-2 text-sm font-medium text-background disabled:opacity-50"
            >
              {t.auth.changePassword}
            </button>
          </form>
        )}

        {mode === "code" && (
          <form
            className="mt-8 space-y-3 rounded-xl border border-border bg-panel p-6"
            onSubmit={async (e: FormEvent) => {
              e.preventDefault();
              const ok = await post({
                action: "set_password_by_code",
                character,
                code,
                newPassword: pass,
                newPassword2: pass2,
              });
              if (ok) window.location.href = "/login";
            }}
          >
            <input
              value={character}
              onChange={(e) => setCharacter(e.target.value)}
              placeholder={t.auth.charName}
              className="w-full rounded border border-border bg-background px-3 py-2 text-sm"
            />
            <input
              value={code}
              onChange={(e) => setCode(e.target.value)}
              placeholder="code"
              className="w-full rounded border border-border bg-background px-3 py-2 text-sm"
            />
            <input
              type="password"
              value={pass}
              onChange={(e) => setPass(e.target.value)}
              placeholder={t.auth.newPassword}
              className="w-full rounded border border-border bg-background px-3 py-2 text-sm"
            />
            <input
              type="password"
              value={pass2}
              onChange={(e) => setPass2(e.target.value)}
              placeholder={t.auth.confirmPassword}
              className="w-full rounded border border-border bg-background px-3 py-2 text-sm"
            />
            <button
              type="submit"
              disabled={busy}
              className="rounded-lg bg-brand px-4 py-2 text-sm font-medium text-background disabled:opacity-50"
            >
              {t.auth.changePassword}
            </button>
          </form>
        )}
      </main>
      <Footer />
    </div>
  );
}
// END CHANGE
