// BEGIN CHANGE: Criar Conta + personagem com outfits das vocacoes (como createaccount.php)
"use client";

import { useEffect, useState, FormEvent } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useI18n } from "@/i18n/LanguageProvider";
import { useAuth } from "@/auth/AuthProvider";
import { Navbar } from "@/components/Navbar";
import { Footer } from "@/components/Footer";
import { Outfit } from "@/components/Outfit";
import { VocationMatcher } from "@/components/VocationMatcher";
import { apiUrl, type Look } from "@/lib/api";

type VocPreview = { id: number; name: string; look: Look };

export default function CreateAccountPage() {
  const { t } = useI18n();
  const router = useRouter();
  const { ready, account: sessionAccount, setSession } = useAuth();
  const [account, setAccount] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [password2, setPassword2] = useState("");
  const [charName, setCharName] = useState("");
  const [sex, setSex] = useState<"male" | "female">("male");
  const [vocation, setVocation] = useState(1);
  const [agree, setAgree] = useState(false);
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [generic, setGeneric] = useState("");
  const [loading, setLoading] = useState(false);
  const [vocs, setVocs] = useState<VocPreview[]>([]);

  const labels: Record<number, string> = {
    1: t.auth.vocSorcerer,
    2: t.auth.vocDruid,
    3: t.auth.vocPaladin,
    4: t.auth.vocKnight,
  };

  // BEGIN CHANGE: ja logado -> redireciona para /account
  useEffect(() => {
    if (ready && sessionAccount) {
      router.replace("/account");
    }
  }, [ready, sessionAccount, router]);
  // END CHANGE

  useEffect(() => {
    fetch(apiUrl("vocations.php"))
      .then((r) => (r.ok ? r.json() : null))
      .then((json) => {
        if (json?.data) setVocs(json.data);
      })
      .catch(() => {});
  }, []);

  const tErr = (code: string) =>
    (t.auth.err as Record<string, string>)[code] ?? t.auth.genericError;

  async function onSubmit(e: FormEvent) {
    e.preventDefault();
    setErrors({});
    setGeneric("");
    setLoading(true);
    try {
      const res = await fetch(apiUrl("register.php"), {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          account,
          email,
          password,
          password2,
          agree,
          createChar: true,
          charName,
          sex,
          vocation,
        }),
      });
      if (res.status === 422) {
        const json = await res.json();
        const raw: Record<string, string> = json.errors ?? {};
        const mapped: Record<string, string> = {};
        Object.keys(raw).forEach((k) => (mapped[k] = tErr(raw[k])));
        setErrors(mapped);
        return;
      }
      if (!res.ok) throw new Error("http " + res.status);
      const json = await res.json();
      // BEGIN CHANGE: avisa na /account se o e-mail de confirmacao saiu
      try {
        const mail =
          json.emailSent === true ? "sent" : json.emailSent === false ? "fail" : "skip";
        sessionStorage.setItem(
          "waRegisterMail",
          JSON.stringify({ mail, email: typeof json.email === "string" ? json.email : email }),
        );
      } catch {
        /* ignore */
      }
      // END CHANGE
      setSession(json);
      window.location.href = "/account";
    } catch {
      setGeneric(t.auth.genericError);
    } finally {
      setLoading(false);
    }
  }

  // BEGIN CHANGE: nao renderiza formulario se ja estiver logado
  if (!ready || sessionAccount) {
    return (
      <div className="flex min-h-screen flex-col">
        <Navbar />
        <main className="mx-auto w-full max-w-lg flex-1 px-6 py-16">
          <p className="text-muted">{t.common.loading}</p>
        </main>
        <Footer />
      </div>
    );
  }
  // END CHANGE

  return (
    <div className="flex min-h-screen flex-col">
      <Navbar />
      <main className="mx-auto w-full max-w-lg flex-1 px-6 py-16">
        <h1 className="text-3xl font-semibold tracking-tight">{t.auth.registerTitle}</h1>
        <p className="mt-2 text-muted">{t.auth.registerSubtitle}</p>

        <form onSubmit={onSubmit} className="mt-8 space-y-4">
          <Field label={t.auth.account} error={errors.account}>
            <input
              value={account}
              onChange={(e) => setAccount(e.target.value)}
              autoCapitalize="off"
              autoCorrect="off"
              autoComplete="username"
              spellCheck={false}
              className="w-full rounded-lg border border-border bg-panel px-4 py-2 text-sm outline-none focus:border-brand/60"
            />
          </Field>
          <Field label={t.auth.email} error={errors.email}>
            <input
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              autoCapitalize="off"
              autoCorrect="off"
              autoComplete="email"
              spellCheck={false}
              className="w-full rounded-lg border border-border bg-panel px-4 py-2 text-sm outline-none focus:border-brand/60"
            />
          </Field>
          <Field label={t.auth.password} error={errors.password}>
            <input
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              autoCapitalize="off"
              autoCorrect="off"
              autoComplete="new-password"
              spellCheck={false}
              className="w-full rounded-lg border border-border bg-panel px-4 py-2 text-sm outline-none focus:border-brand/60"
            />
          </Field>
          <Field label={t.auth.confirmPassword}>
            <input
              type="password"
              value={password2}
              onChange={(e) => setPassword2(e.target.value)}
              autoCapitalize="off"
              autoCorrect="off"
              autoComplete="new-password"
              spellCheck={false}
              className="w-full rounded-lg border border-border bg-panel px-4 py-2 text-sm outline-none focus:border-brand/60"
            />
          </Field>

          <div className="border-t border-border pt-4">
            <h2 className="mb-3 text-sm font-semibold">{t.auth.charSection}</h2>
            <Field label={t.auth.charName} error={errors.charName}>
              <input
                value={charName}
                onChange={(e) => setCharName(e.target.value)}
                autoCapitalize="off"
                autoCorrect="off"
                spellCheck={false}
                className="w-full rounded-lg border border-border bg-panel px-4 py-2 text-sm outline-none focus:border-brand/60"
              />
            </Field>

            <div className="mt-3">
              <span className="mb-1.5 block text-sm text-muted">{t.auth.sex}</span>
              <div className="flex gap-4 text-sm">
                <label className="flex items-center gap-2">
                  <input type="radio" checked={sex === "male"} onChange={() => setSex("male")} />
                  {t.auth.male}
                </label>
                <label className="flex items-center gap-2">
                  <input type="radio" checked={sex === "female"} onChange={() => setSex("female")} />
                  {t.auth.female}
                </label>
              </div>
              {errors.sex && <p className="mt-1 text-sm text-red-400">{errors.sex}</p>}
            </div>

            {/* BEGIN CHANGE: matcher de preferencia acima do seletor de vocacao */}
            <div className="mt-4">
              <VocationMatcher value={vocation} onSuggest={setVocation} className="mb-4" />
              <span className="mb-2 block text-sm text-muted">{t.auth.vocation}</span>
              <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
                {vocs.map((v) => (
                  <label
                    key={v.id}
                    className={`flex cursor-pointer flex-col items-center rounded-xl border px-2 py-3 text-center text-sm transition-colors ${
                      vocation === v.id
                        ? "border-brand bg-brand/10"
                        : "border-border bg-panel hover:border-brand/40"
                    }`}
                  >
                    <input
                      type="radio"
                      className="sr-only"
                      checked={vocation === v.id}
                      onChange={() => setVocation(v.id)}
                    />
                    <Outfit look={v.look} size="grid" alt={labels[v.id] ?? v.name} />
                    <span className="mt-1 font-medium">{labels[v.id] ?? v.name}</span>
                  </label>
                ))}
              </div>
              {errors.vocation && <p className="mt-1 text-sm text-red-400">{errors.vocation}</p>}
              <p className="mt-3 text-sm">
                <Link href="/vocations" className="text-brand hover:underline">
                  {t.auth.compareVocations}
                </Link>
              </p>
            </div>
            {/* END CHANGE */}
          </div>

          <label className="flex items-start gap-2 text-sm text-muted">
            <input
              type="checkbox"
              checked={agree}
              onChange={(e) => setAgree(e.target.checked)}
              className="mt-0.5"
            />
            <span>{t.auth.agree}</span>
          </label>
          {errors.agree && <p className="text-sm text-red-400">{errors.agree}</p>}
          {generic && <p className="text-sm text-red-400">{generic}</p>}

          <button
            type="submit"
            disabled={loading}
            className="w-full rounded-lg bg-brand px-5 py-2.5 text-sm font-medium text-background transition-opacity hover:opacity-90 disabled:opacity-60"
          >
            {loading ? t.common.loading : t.auth.registerBtn}
          </button>
        </form>

        <p className="mt-6 text-sm text-muted">
          {t.auth.haveAccount}{" "}
          <Link href="/login" className="text-brand hover:underline">
            {t.auth.loginNow}
          </Link>
        </p>
      </main>
      <Footer />
    </div>
  );
}

function Field({
  label,
  error,
  children,
}: {
  label: string;
  error?: string;
  children: React.ReactNode;
}) {
  return (
    <label className="block">
      <span className="mb-1.5 block text-sm text-muted">{label}</span>
      {children}
      {error && <span className="mt-1 block text-sm text-red-400">{error}</span>}
    </label>
  );
}
// END CHANGE
