// Auteur : Simon-Pierre Boucher — contact@spboucher.ai
"use client";

import { useState } from "react";
import { ROLES } from "@/lib/roles";

const ERRORS: Record<string, string> = {
  "google-non-configure":
    "La connexion Google n'est pas encore activée sur ce serveur.",
  "etat-oauth-invalide":
    "La session Google a expiré — réessayez.",
  "echange-google-refuse": "Google a refusé l'échange — réessayez.",
  "id-token-absent": "Réponse Google incomplète — réessayez.",
  "id-token-invalide": "Réponse Google invalide — réessayez.",
  "profil-google-incomplet":
    "Votre compte Google n'a pas de courriel vérifié.",
  "apple-non-configure":
    "La connexion Apple n'est pas encore activée sur ce serveur.",
  "apple-refuse": "La connexion Apple a été annulée — réessayez.",
  "echange-apple-refuse": "Apple a refusé l'échange — réessayez.",
  "profil-apple-incomplet":
    "Votre compte Apple n'a pas de courriel vérifié.",
};

export default function AuthForm({
  next,
  error,
  via,
}: {
  next: string;
  error?: string;
  via?: string;
}) {
  const [mode, setMode] = useState<"login" | "register">("login");
  const [msg, setMsg] = useState<string | null>(
    error ? (ERRORS[error] ?? "Une erreur est survenue — réessayez.") : null,
  );
  const [busy, setBusy] = useState(false);

  async function submit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setBusy(true);
    setMsg(null);
    const fd = new FormData(e.currentTarget);
    const body = Object.fromEntries(fd.entries());
    const res = await fetch(`/api/auth/${mode}`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(body),
    });
    const data = await res.json().catch(() => ({}));
    if (res.ok) {
      window.location.href = next;
    } else {
      setMsg(data.error ?? "Une erreur est survenue — réessayez.");
      setBusy(false);
    }
  }

  return (
    <div className="gk-card p-6 sm:p-8">
      {via && (
        <p className="stat-chip mb-5 !text-[11px]">
          <span className="pulse-dot" aria-hidden="true" />
          Connexion demandée par {via} — vous y retournerez automatiquement
        </p>
      )}

      <a
        href={`/api/auth/google?next=${encodeURIComponent(next)}`}
        className="btn btn-google w-full"
      >
        {/* « G » officiel Google — couleurs de marque */}
        <svg width="18" height="18" viewBox="0 0 48 48" aria-hidden="true">
          <path
            fill="#EA4335"
            d="M24 9.5c3.54 0 6.71 1.22 9.21 3.6l6.85-6.85C35.9 2.38 30.47 0 24 0 14.62 0 6.51 5.38 2.56 13.22l7.98 6.19C12.43 13.72 17.74 9.5 24 9.5z"
          />
          <path
            fill="#4285F4"
            d="M46.98 24.55c0-1.57-.15-3.09-.38-4.55H24v9.02h12.94c-.58 2.96-2.26 5.48-4.78 7.18l7.73 6c4.51-4.18 7.09-10.36 7.09-17.65z"
          />
          <path
            fill="#FBBC05"
            d="M10.53 28.59c-.48-1.45-.76-2.99-.76-4.59s.27-3.14.76-4.59l-7.98-6.19C.92 16.46 0 20.12 0 24c0 3.88.92 7.54 2.56 10.78l7.97-6.19z"
          />
          <path
            fill="#34A853"
            d="M24 48c6.48 0 11.93-2.13 15.89-5.81l-7.73-6c-2.15 1.45-4.92 2.3-8.16 2.3-6.26 0-11.57-4.22-13.47-9.91l-7.98 6.19C6.51 42.62 14.62 48 24 48z"
          />
        </svg>
        Continuer avec Google
      </a>

      <a
        href={`/api/auth/apple?next=${encodeURIComponent(next)}`}
        className="btn btn-apple mt-3 w-full"
      >
        {/* Pomme Apple — blanche sur noir, style officiel */}
        <svg width="18" height="18" viewBox="0 0 24 24" aria-hidden="true">
          <path
            fill="currentColor"
            d="M16.36 12.76c-.03-2.62 2.14-3.88 2.24-3.94-1.22-1.79-3.12-2.03-3.8-2.06-1.61-.16-3.15.95-3.97.95-.82 0-2.09-.93-3.43-.9-1.77.03-3.4 1.03-4.31 2.6-1.84 3.19-.47 7.9 1.32 10.49.88 1.27 1.92 2.69 3.29 2.64 1.32-.05 1.82-.85 3.42-.85 1.6 0 2.05.85 3.44.82 1.42-.02 2.32-1.29 3.19-2.56 1-1.46 1.41-2.87 1.44-2.95-.03-.01-2.76-1.06-2.83-4.24ZM13.75 4.99c.73-.88 1.22-2.11 1.08-3.33-1.05.04-2.31.7-3.06 1.58-.67.78-1.26 2.02-1.1 3.22 1.17.09 2.36-.6 3.08-1.47Z"
          />
        </svg>
        Continuer avec Apple
      </a>

      <div className="my-6 flex items-center gap-4">
        <span className="h-[1.5px] flex-1 bg-[rgba(20,24,20,0.18)]" />
        <span className="klabel">ou par courriel</span>
        <span className="h-[1.5px] flex-1 bg-[rgba(20,24,20,0.18)]" />
      </div>

      <div className="mb-5 grid grid-cols-2 gap-2" role="tablist">
        {(
          [
            ["login", "Se connecter"],
            ["register", "Créer un compte"],
          ] as const
        ).map(([m, label]) => (
          <button
            key={m}
            role="tab"
            aria-selected={mode === m}
            onClick={() => {
              setMode(m);
              setMsg(null);
            }}
            className={`btn ${mode === m ? "btn-lime" : "btn-ghost"} !min-h-[40px] !text-[13px]`}
            type="button"
          >
            {label}
          </button>
        ))}
      </div>

      <form onSubmit={submit} className="space-y-4">
        {mode === "register" && (
          <>
            <label className="block">
              <span className="klabel">Votre nom</span>
              <input
                name="name"
                type="text"
                required
                minLength={2}
                autoComplete="name"
                className="field mt-[6px]"
                placeholder="Prénom Nom"
              />
            </label>
            <fieldset>
              <legend className="klabel">Vous êtes…</legend>
              <div className="mt-[6px] space-y-2">
                {Object.entries(ROLES).map(([value, r]) => (
                  <label
                    key={value}
                    className="flex cursor-pointer items-start gap-3 rounded-md border-[1.5px] border-[rgba(20,24,20,0.3)] bg-surface px-4 py-3 transition-colors has-[:checked]:border-ink has-[:checked]:bg-lime-soft has-[:checked]:shadow-[3px_3px_0_rgba(20,24,20,0.15)]"
                  >
                    <input
                      type="radio"
                      name="role"
                      value={value}
                      required
                      className="mt-[3px] accent-[#1c5c41]"
                    />
                    <span>
                      <span className="gk-display block text-[14px] font-bold">
                        {r.label}
                      </span>
                      <span className="mt-[2px] block text-[12px] leading-snug text-ink-2">
                        {r.desc}
                      </span>
                    </span>
                  </label>
                ))}
              </div>
              <p className="gk-mono mt-2 text-[10.5px] text-ink-3">
                Ce statut sera affiché sur votre carte de membre.
              </p>
            </fieldset>
          </>
        )}
        <label className="block">
          <span className="klabel">Courriel</span>
          <input
            name="email"
            type="email"
            required
            autoComplete="email"
            className="field mt-[6px]"
            placeholder="vous@exemple.com"
          />
        </label>
        <label className="block">
          <span className="klabel">
            Mot de passe{mode === "register" ? " (8 caractères min.)" : ""}
          </span>
          <input
            name="password"
            type="password"
            required
            minLength={8}
            autoComplete={mode === "register" ? "new-password" : "current-password"}
            className="field mt-[6px]"
            placeholder="••••••••"
          />
        </label>

        {msg && (
          <p className="rounded-md border-[1.5px] border-[#b3423a] bg-[#fbe9e7] px-4 py-3 text-[13px] font-medium text-[#7c2f2a]">
            {msg}
          </p>
        )}

        <button type="submit" disabled={busy} className="btn btn-primary w-full">
          {busy
            ? "Un instant…"
            : mode === "login"
              ? "Se connecter"
              : "Créer mon KA ID"}
        </button>
      </form>

      <p className="mt-6 border-t-[1.5px] border-dashed border-[rgba(20,24,20,0.25)] pt-4 text-[12px] leading-relaxed text-ink-2">
        Un seul compte — le <strong className="gk-display">KA ID</strong> —
        pour toutes les plateformes du groupe. En continuant, vous acceptez
        les{" "}
        <a href="/conditions" className="underline underline-offset-4">
          conditions d&apos;utilisation
        </a>{" "}
        et la{" "}
        <a href="/confidentialite" className="underline underline-offset-4">
          politique de confidentialité
        </a>
        .
      </p>
    </div>
  );
}
