"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { CheckCircle2, ChevronLeft, Gift, Loader2, Mail, ShieldCheck, Trophy, X } from "lucide-react";

const priorityCountries = [
  ["FR", "France"],
  ["BE", "Belgique"],
  ["CH", "Suisse"]
] as const;

const countryOptions = [
  ["AF", "Afghanistan"],
  ["ZA", "Afrique du Sud"],
  ["AL", "Albanie"],
  ["DZ", "Algérie"],
  ["DE", "Allemagne"],
  ["AD", "Andorre"],
  ["AO", "Angola"],
  ["AG", "Antigua-et-Barbuda"],
  ["SA", "Arabie saoudite"],
  ["AR", "Argentine"],
  ["AM", "Arménie"],
  ["AU", "Australie"],
  ["AT", "Autriche"],
  ["AZ", "Azerbaïdjan"],
  ["BS", "Bahamas"],
  ["BH", "Bahreïn"],
  ["BD", "Bangladesh"],
  ["BB", "Barbade"],
  ["BZ", "Belize"],
  ["BJ", "Bénin"],
  ["BT", "Bhoutan"],
  ["BY", "Biélorussie"],
  ["BO", "Bolivie"],
  ["BA", "Bosnie-Herzégovine"],
  ["BW", "Botswana"],
  ["BR", "Brésil"],
  ["BN", "Brunei"],
  ["BG", "Bulgarie"],
  ["BF", "Burkina Faso"],
  ["BI", "Burundi"],
  ["KH", "Cambodge"],
  ["CM", "Cameroun"],
  ["CA", "Canada"],
  ["CV", "Cap-Vert"],
  ["CL", "Chili"],
  ["CN", "Chine"],
  ["CY", "Chypre"],
  ["CO", "Colombie"],
  ["KM", "Comores"],
  ["CG", "Congo"],
  ["KP", "Corée du Nord"],
  ["KR", "Corée du Sud"],
  ["CR", "Costa Rica"],
  ["CI", "Côte d'Ivoire"],
  ["HR", "Croatie"],
  ["CU", "Cuba"],
  ["DK", "Danemark"],
  ["DJ", "Djibouti"],
  ["DM", "Dominique"],
  ["EG", "Égypte"],
  ["AE", "Émirats arabes unis"],
  ["EC", "Équateur"],
  ["ER", "Érythrée"],
  ["ES", "Espagne"],
  ["EE", "Estonie"],
  ["SZ", "Eswatini"],
  ["US", "États-Unis"],
  ["ET", "Éthiopie"],
  ["FJ", "Fidji"],
  ["FI", "Finlande"],
  ["GA", "Gabon"],
  ["GM", "Gambie"],
  ["GE", "Géorgie"],
  ["GH", "Ghana"],
  ["GR", "Grèce"],
  ["GD", "Grenade"],
  ["GT", "Guatemala"],
  ["GN", "Guinée"],
  ["GQ", "Guinée équatoriale"],
  ["GW", "Guinée-Bissau"],
  ["GY", "Guyana"],
  ["HT", "Haïti"],
  ["HN", "Honduras"],
  ["HU", "Hongrie"],
  ["CK", "Îles Cook"],
  ["MH", "Îles Marshall"],
  ["SB", "Îles Salomon"],
  ["IN", "Inde"],
  ["ID", "Indonésie"],
  ["IQ", "Irak"],
  ["IR", "Iran"],
  ["IE", "Irlande"],
  ["IS", "Islande"],
  ["IL", "Israël"],
  ["IT", "Italie"],
  ["JM", "Jamaïque"],
  ["JP", "Japon"],
  ["JO", "Jordanie"],
  ["KZ", "Kazakhstan"],
  ["KE", "Kenya"],
  ["KG", "Kirghizistan"],
  ["KI", "Kiribati"],
  ["XK", "Kosovo"],
  ["KW", "Koweït"],
  ["LA", "Laos"],
  ["LS", "Lesotho"],
  ["LV", "Lettonie"],
  ["LB", "Liban"],
  ["LR", "Liberia"],
  ["LY", "Libye"],
  ["LI", "Liechtenstein"],
  ["LT", "Lituanie"],
  ["LU", "Luxembourg"],
  ["MK", "Macédoine du Nord"],
  ["MG", "Madagascar"],
  ["MY", "Malaisie"],
  ["MW", "Malawi"],
  ["MV", "Maldives"],
  ["ML", "Mali"],
  ["MT", "Malte"],
  ["MA", "Maroc"],
  ["MU", "Maurice"],
  ["MR", "Mauritanie"],
  ["MX", "Mexique"],
  ["FM", "Micronésie"],
  ["MD", "Moldavie"],
  ["MC", "Monaco"],
  ["MN", "Mongolie"],
  ["ME", "Monténégro"],
  ["MZ", "Mozambique"],
  ["MM", "Myanmar"],
  ["NA", "Namibie"],
  ["NR", "Nauru"],
  ["NP", "Népal"],
  ["NI", "Nicaragua"],
  ["NE", "Niger"],
  ["NG", "Nigeria"],
  ["NU", "Niue"],
  ["NO", "Norvège"],
  ["NZ", "Nouvelle-Zélande"],
  ["OM", "Oman"],
  ["UG", "Ouganda"],
  ["UZ", "Ouzbékistan"],
  ["PK", "Pakistan"],
  ["PW", "Palaos"],
  ["PS", "Palestine"],
  ["PA", "Panama"],
  ["PG", "Papouasie-Nouvelle-Guinée"],
  ["PY", "Paraguay"],
  ["NL", "Pays-Bas"],
  ["PE", "Pérou"],
  ["PH", "Philippines"],
  ["PL", "Pologne"],
  ["PT", "Portugal"],
  ["QA", "Qatar"],
  ["CF", "République centrafricaine"],
  ["CD", "République démocratique du Congo"],
  ["DO", "République dominicaine"],
  ["CZ", "République tchèque"],
  ["RO", "Roumanie"],
  ["GB", "Royaume-Uni"],
  ["RU", "Russie"],
  ["RW", "Rwanda"],
  ["KN", "Saint-Kitts-et-Nevis"],
  ["SM", "Saint-Marin"],
  ["VC", "Saint-Vincent-et-les-Grenadines"],
  ["LC", "Sainte-Lucie"],
  ["SV", "Salvador"],
  ["WS", "Samoa"],
  ["ST", "Sao Tomé-et-Principe"],
  ["SN", "Sénégal"],
  ["RS", "Serbie"],
  ["SC", "Seychelles"],
  ["SL", "Sierra Leone"],
  ["SG", "Singapour"],
  ["SK", "Slovaquie"],
  ["SI", "Slovénie"],
  ["SO", "Somalie"],
  ["SD", "Soudan"],
  ["SS", "Soudan du Sud"],
  ["LK", "Sri Lanka"],
  ["SE", "Suède"],
  ["SR", "Suriname"],
  ["SY", "Syrie"],
  ["TJ", "Tadjikistan"],
  ["TZ", "Tanzanie"],
  ["TD", "Tchad"],
  ["TH", "Thaïlande"],
  ["TL", "Timor oriental"],
  ["TG", "Togo"],
  ["TO", "Tonga"],
  ["TT", "Trinité-et-Tobago"],
  ["TN", "Tunisie"],
  ["TM", "Turkménistan"],
  ["TR", "Turquie"],
  ["TV", "Tuvalu"],
  ["UA", "Ukraine"],
  ["UY", "Uruguay"],
  ["VU", "Vanuatu"],
  ["VA", "Vatican"],
  ["VE", "Venezuela"],
  ["VN", "Vietnam"],
  ["YE", "Yémen"],
  ["ZM", "Zambie"],
  ["ZW", "Zimbabwe"]
] as const;

type WelcomePromotion = {
  code: string;
  name: string;
  matchPercent: number;
  maxBonusAmount: string;
  wageringMultiplier: string;
  terms: string;
};

type BonusChoice = "sport" | "promo" | "none";

type AuthFormProps = {
  onClose?: () => void;
};

export function LoginForm({ onClose }: AuthFormProps = {}) {
  const [message, setMessage] = useState("");
  const [loading, setLoading] = useState(false);

  async function submit(formData: FormData) {
    setLoading(true);
    setMessage("");
    const response = await fetch("/api/auth/login", {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({
        email: formData.get("email"),
        password: formData.get("password")
      })
    });
    const payload = await response.json();
    setLoading(false);
    if (!response.ok || !payload.ok) {
      setMessage(payload.error?.message ?? "Connexion refusée");
      return;
    }
    window.location.href = "/";
  }

  return (
    <section className="relative mx-auto w-full max-w-[420px] overflow-hidden rounded-lg border border-felt/25 bg-[#101521] shadow-panel">
      <AuthGlow />
      <ModalHeader icon={ShieldCheck} eyebrow="Connexion sécurisée" title="Se connecter" closeHref="/" onClose={onClose} />
      <div className="relative p-4">
        <form action={submit} className="space-y-3">
          <label className={modalLabelClass}>
            E-mail
            <input name="email" type="email" required placeholder="vous@email.com" className={modalInputClass} />
          </label>
          <label className={modalLabelClass}>
            Mot de passe
            <input name="password" type="password" required placeholder="Votre mot de passe" className={modalInputClass} />
          </label>
          <button className="flex h-10 w-full items-center justify-center gap-2 rounded-lg bg-felt text-sm font-extrabold text-ink-950">
            {loading ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
            Se connecter
          </button>
          {message ? <p className="rounded-lg border border-ember/25 bg-ember/10 p-2.5 text-xs font-semibold text-ember">{message}</p> : null}
        </form>
        <p className="mt-4 text-center text-xs font-semibold text-slate-400">
          Pas encore de compte ?{" "}
          <Link href="/register" className="text-felt">
            S'inscrire
          </Link>
        </p>
      </div>
    </section>
  );
}

export function RegisterForm({ onClose }: AuthFormProps = {}) {
  const [message, setMessage] = useState("");
  const [loading, setLoading] = useState(false);
  const [step, setStep] = useState<1 | 2 | 3>(1);
  const [bonusChoice, setBonusChoice] = useState<BonusChoice>("sport");
  const [sportOffer, setSportOffer] = useState<WelcomePromotion | null>(null);
  const [promoOffer, setPromoOffer] = useState<WelcomePromotion | null>(null);
  const [promoCode, setPromoCode] = useState("");
  const [promoChecking, setPromoChecking] = useState(false);
  const [acceptedTerms, setAcceptedTerms] = useState(false);
  const [marketingConsent, setMarketingConsent] = useState(false);
  const [form, setForm] = useState({
    username: "",
    email: "",
    password: "",
    firstName: "",
    lastName: "",
    dateOfBirth: "",
    gender: "M",
    country: "FR",
    currency: "EUR"
  });

  useEffect(() => {
    fetch("/api/promotions/welcome", { cache: "no-store" })
      .then((response) => response.json())
      .then((payload) => {
        if (payload.ok) setSportOffer(payload.data.sport);
      })
      .catch(() => setSportOffer(null));
  }, []);

  function updateField(name: keyof typeof form, value: string) {
    setForm((current) => {
      const next = { ...current, [name]: value };
      if (name === "email" && !current.username) {
        const username = value.split("@")[0]?.replace(/[^a-zA-Z0-9_]/g, "_").slice(0, 24) ?? "";
        if (username.length >= 3) next.username = username;
      }
      return next;
    });
  }

  async function validatePromo() {
    const normalized = promoCode.trim().toUpperCase();
    if (!normalized) {
      setPromoOffer(null);
      setMessage("Saisissez votre code promotionnel.");
      return null;
    }

    setPromoChecking(true);
    setMessage("");
    const response = await fetch(`/api/promotions/welcome?code=${encodeURIComponent(normalized)}`, { cache: "no-store" });
    const payload = await response.json();
    setPromoChecking(false);

    if (!payload.ok || !payload.data.promo) {
      setPromoOffer(null);
      setMessage("Code promotionnel invalide ou expiré.");
      return null;
    }

    setPromoOffer(payload.data.promo);
    return payload.data.promo as WelcomePromotion;
  }

  async function goNext() {
    setMessage("");
    if (step === 1) {
      if (bonusChoice === "promo" && !promoOffer) {
        const checked = await validatePromo();
        if (!checked) return;
      }
      setStep(2);
      return;
    }

    if (!form.email || !form.password || !form.username || !acceptedTerms) {
      setMessage("Renseignez l'email, le pseudo, le mot de passe et acceptez les conditions.");
      return;
    }

    if (form.password.length < 12) {
      setMessage("Le mot de passe doit contenir au moins 12 caractères.");
      return;
    }

    setStep(3);
  }

  async function submit() {
    if (!form.firstName || !form.lastName || !form.dateOfBirth || !form.country || !form.currency) {
      setMessage("Complétez vos informations personnelles.");
      return;
    }

    setLoading(true);
    setMessage("");
    const response = await fetch("/api/auth/register", {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({
        username: form.username,
        email: form.email,
        password: form.password,
        firstName: form.firstName,
        lastName: form.lastName,
        dateOfBirth: form.dateOfBirth,
        country: form.country,
        currency: form.currency,
        acceptedTerms,
        welcomeBonusCode: selectedWelcomeCode(bonusChoice, sportOffer, promoOffer)
      })
    });
    const payload = await response.json();
    setLoading(false);
    if (!response.ok || !payload.ok) {
      setMessage(payload.error?.message ?? "Inscription refusée");
      return;
    }
    window.location.href = "/";
  }

  return (
    <section className="relative mx-auto w-full max-w-[420px] overflow-hidden rounded-lg border border-felt/25 bg-[#101521] shadow-panel">
      <AuthGlow />
      <div className="relative border-b border-white/10 px-4 py-3">
        <div className="flex items-center justify-between gap-3">
          {step > 1 ? (
            <button onClick={() => setStep((current) => (current === 3 ? 2 : 1))} className="grid h-9 w-9 place-items-center rounded-lg bg-white/[0.06] text-slate-200" aria-label="Retour">
              <ChevronLeft className="h-4 w-4" />
            </button>
          ) : (
            <span className="grid h-9 w-9 place-items-center rounded-lg bg-felt/10 text-felt">
              <Trophy className="h-4 w-4" />
            </span>
          )}
          <div className="min-w-0 flex-1 text-center">
            <div className="text-[11px] font-bold uppercase text-felt">Inscription {step}/3</div>
            <h1 className="mt-0.5 truncate text-lg font-extrabold text-white">{step === 1 ? "Bonus de bienvenue" : step === 2 ? "Votre accès" : "Informations personnelles"}</h1>
          </div>
          {onClose ? (
            <button onClick={onClose} className="grid h-9 w-9 place-items-center rounded-lg bg-ember/15 text-ember" aria-label="Fermer">
              <X className="h-4 w-4" />
            </button>
          ) : (
            <Link href="/" className="grid h-9 w-9 place-items-center rounded-lg bg-ember/15 text-ember" aria-label="Fermer">
              <X className="h-4 w-4" />
            </Link>
          )}
        </div>
        <div className="mt-3 grid grid-cols-3 gap-1.5">
          {[1, 2, 3].map((item) => (
            <span key={item} className={item <= step ? "h-1 rounded-full bg-felt" : "h-1 rounded-full bg-white/10"} />
          ))}
        </div>
      </div>

      <div className="relative p-4">
        {step === 1 ? (
          <div className="space-y-2.5">
            <BonusOption
              active={bonusChoice === "sport"}
              icon={Trophy}
              title="Sport"
              value={sportOffer ? offerText(sportOffer) : "300% jusqu'à 1 000€"}
              onClick={() => setBonusChoice("sport")}
            />
            <BonusOption
              active={bonusChoice === "promo"}
              icon={Gift}
              title="Code promotionnel"
              value={promoOffer ? offerText(promoOffer) : "Saisissez votre code"}
              onClick={() => setBonusChoice("promo")}
            />
            {bonusChoice === "promo" ? (
              <div className="grid gap-2 rounded-lg border border-white/10 bg-white/[0.035] p-2.5 sm:grid-cols-[1fr_auto]">
                <input
                  value={promoCode}
                  onChange={(event) => {
                    setPromoCode(event.target.value.toUpperCase());
                    setPromoOffer(null);
                  }}
                  placeholder="AZIA"
                  className="h-9 rounded-lg border-white/10 bg-white px-3 text-sm font-extrabold uppercase text-ink-950 placeholder:text-slate-400"
                />
                <button onClick={() => void validatePromo()} className="h-9 rounded-lg bg-white/[0.08] px-3 text-xs font-extrabold text-white">
                  {promoChecking ? <Loader2 className="mx-auto h-4 w-4 animate-spin" /> : "Valider"}
                </button>
              </div>
            ) : null}
            <BonusOption
              active={bonusChoice === "none"}
              icon={Mail}
              title="Sans bonus"
              value="Continuer sans bonus"
              onClick={() => setBonusChoice("none")}
            />
            <button onClick={() => void goNext()} className="mt-2 flex h-10 w-full items-center justify-center rounded-lg bg-felt text-sm font-extrabold text-ink-950">
              Choisir
            </button>
          </div>
        ) : null}

        {step === 2 ? (
          <div className="space-y-3">
            <SelectedBonus choice={bonusChoice} sportOffer={sportOffer} promoOffer={promoOffer} />
            <label className={modalLabelClass}>
              E-mail
              <input value={form.email} onChange={(event) => updateField("email", event.target.value)} type="email" placeholder="vous@email.com" className={modalInputClass} />
            </label>
            <label className={modalLabelClass}>
              Pseudo
              <input value={form.username} onChange={(event) => updateField("username", event.target.value)} placeholder="ziraplayer" className={modalInputClass} />
            </label>
            <label className={modalLabelClass}>
              Mot de passe
              <input value={form.password} onChange={(event) => updateField("password", event.target.value)} type="password" placeholder="12 caractères minimum" className={modalInputClass} />
            </label>
            <label className="flex items-start gap-2.5 text-xs leading-5 text-slate-300">
              <input checked={acceptedTerms} onChange={(event) => setAcceptedTerms(event.target.checked)} type="checkbox" className="mt-1 rounded border-white/10 bg-ink-900 text-felt" />
              J'ai 18 ans et j'accepte les conditions, la confidentialité et le jeu responsable.
            </label>
            <label className="flex items-start gap-2.5 text-xs leading-5 text-slate-400">
              <input checked={marketingConsent} onChange={(event) => setMarketingConsent(event.target.checked)} type="checkbox" className="mt-1 rounded border-white/10 bg-ink-900 text-felt" />
              Je souhaite recevoir les offres et communications bonus.
            </label>
            <button onClick={() => void goNext()} className="flex h-10 w-full items-center justify-center rounded-lg bg-felt text-sm font-extrabold text-ink-950">
              Étape suivante
            </button>
          </div>
        ) : null}

        {step === 3 ? (
          <div className="space-y-3">
            <SelectedBonus choice={bonusChoice} sportOffer={sportOffer} promoOffer={promoOffer} />
            <div className="grid grid-cols-2 gap-2">
              <label className={modalLabelClass}>
                Prénom
                <input value={form.firstName} onChange={(event) => updateField("firstName", event.target.value)} placeholder="Prénom" className={modalInputClass} />
              </label>
              <label className={modalLabelClass}>
                Nom
                <input value={form.lastName} onChange={(event) => updateField("lastName", event.target.value)} placeholder="Nom" className={modalInputClass} />
              </label>
            </div>
            <label className={modalLabelClass}>
              Date de naissance
              <input value={form.dateOfBirth} onChange={(event) => updateField("dateOfBirth", event.target.value)} type="date" className={modalInputClass} />
            </label>
            <div className="grid grid-cols-2 gap-2">
              {[
                ["M", "Homme"],
                ["F", "Femme"]
              ].map(([value, label]) => (
                <button key={value} onClick={() => updateField("gender", value)} className={form.gender === value ? "flex h-10 items-center justify-between rounded-lg border border-felt bg-felt/10 px-3 text-sm font-semibold text-white" : "flex h-10 items-center justify-between rounded-lg border border-white/10 bg-white/[0.04] px-3 text-sm font-semibold text-slate-300"}>
                  {label}
                  {form.gender === value ? <CheckCircle2 className="h-4 w-4 text-felt" /> : <span className="h-4 w-4 rounded-full border border-white/20" />}
                </button>
              ))}
            </div>
            <label className={modalLabelClass}>
              Pays
              <select value={form.country} onChange={(event) => updateField("country", event.target.value)} className={modalInputClass}>
                <optgroup label="Pays principaux">
                  {priorityCountries.map(([code, label]) => (
                    <option key={code} value={code}>
                      {label}
                    </option>
                  ))}
                </optgroup>
                <optgroup label="Tous les pays">
                  {countryOptions.map(([code, label]) => (
                    <option key={code} value={code}>
                      {label}
                    </option>
                  ))}
                </optgroup>
              </select>
            </label>
            <label className={modalLabelClass}>
              Devise
              <select value={form.currency} onChange={(event) => updateField("currency", event.target.value)} className={modalInputClass}>
                <option value="EUR">Euro</option>
                <option value="CHF">Franc suisse</option>
                <option value="USD">Dollar US</option>
              </select>
            </label>
            <button onClick={() => void submit()} disabled={loading} className="flex h-10 w-full items-center justify-center gap-2 rounded-lg bg-felt text-sm font-extrabold text-ink-950 disabled:bg-slate-700 disabled:text-slate-400">
              {loading ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
              Créer le compte
            </button>
          </div>
        ) : null}

        {message ? <p className="mt-3 rounded-lg border border-ember/25 bg-ember/10 p-2.5 text-xs font-semibold text-ember">{message}</p> : null}
        <p className="mt-4 text-center text-xs font-semibold text-slate-400">
          Vous avez déjà un compte ?{" "}
          <Link href="/login" className="text-felt">
            Se connecter
          </Link>
        </p>
      </div>
    </section>
  );
}

const modalInputClass =
  "mt-1 h-10 w-full rounded-lg border border-white/10 bg-white px-3 text-sm font-semibold text-ink-950 placeholder:text-slate-400 focus:border-felt focus:ring-felt";
const modalLabelClass = "block text-[11px] font-bold uppercase text-slate-300";

function AuthGlow() {
  return <div className="absolute inset-x-0 top-0 h-28 bg-[linear-gradient(135deg,rgba(15,191,143,0.24),rgba(63,200,239,0.16),rgba(245,189,71,0.12),transparent)]" />;
}

function ModalHeader({ icon: Icon, eyebrow, title, closeHref, onClose }: { icon: typeof ShieldCheck; eyebrow: string; title: string; closeHref: string; onClose?: () => void }) {
  return (
    <div className="relative border-b border-white/10 px-4 py-3">
      <div className="flex items-center justify-between gap-3">
        <span className="grid h-9 w-9 place-items-center rounded-lg bg-felt/10 text-felt">
          <Icon className="h-4 w-4" />
        </span>
        <div className="min-w-0 flex-1 text-center">
          <div className="text-[11px] font-bold uppercase text-felt">{eyebrow}</div>
          <h1 className="mt-0.5 truncate text-lg font-extrabold text-white">{title}</h1>
        </div>
        {onClose ? (
          <button onClick={onClose} className="grid h-9 w-9 place-items-center rounded-lg bg-ember/15 text-ember" aria-label="Fermer">
            <X className="h-4 w-4" />
          </button>
        ) : (
          <Link href={closeHref} className="grid h-9 w-9 place-items-center rounded-lg bg-ember/15 text-ember" aria-label="Fermer">
            <X className="h-4 w-4" />
          </Link>
        )}
      </div>
    </div>
  );
}

function BonusOption({ active, icon: Icon, title, value, onClick }: { active: boolean; icon: typeof Trophy; title: string; value: string; onClick: () => void }) {
  return (
    <button
      onClick={onClick}
      className={active ? "flex w-full items-center gap-3 rounded-lg border border-felt bg-felt/10 p-3 text-left" : "flex w-full items-center gap-3 rounded-lg border border-white/10 bg-white/[0.04] p-3 text-left"}
    >
      <span className={active ? "grid h-10 w-10 shrink-0 place-items-center rounded-lg bg-felt text-ink-950" : "grid h-10 w-10 shrink-0 place-items-center rounded-lg bg-white/[0.06] text-slate-300"}>
        <Icon className="h-5 w-5" />
      </span>
      <span className="min-w-0 flex-1">
        <span className="block text-sm font-semibold text-white">{title}</span>
        <span className={active ? "mt-0.5 block truncate text-xs font-extrabold text-felt" : "mt-0.5 block truncate text-xs font-semibold text-slate-400"}>{value}</span>
      </span>
      {active ? <CheckCircle2 className="h-5 w-5 text-felt" /> : <span className="h-5 w-5 rounded-full border border-white/20" />}
    </button>
  );
}

function SelectedBonus({ choice, sportOffer, promoOffer }: { choice: BonusChoice; sportOffer: WelcomePromotion | null; promoOffer: WelcomePromotion | null }) {
  const Icon = choice === "promo" ? Gift : choice === "none" ? Mail : Trophy;
  const title = choice === "promo" ? "Code promotionnel" : choice === "none" ? "Sans bonus" : "Sport";
  const value = choice === "promo" ? (promoOffer ? offerText(promoOffer) : "Code à valider") : choice === "none" ? "Aucun bonus appliqué" : sportOffer ? offerText(sportOffer) : "300% jusqu'à 1 000€";
  return (
    <div className="flex items-center gap-3 rounded-lg border border-felt/25 bg-felt/10 p-2.5">
      <span className="grid h-8 w-8 place-items-center rounded-lg bg-felt text-ink-950">
        <Icon className="h-4 w-4" />
      </span>
      <span className="min-w-0">
        <span className="block truncate text-xs font-semibold text-white">{title}</span>
        <span className="block truncate text-xs font-bold text-felt">{value}</span>
      </span>
    </div>
  );
}

function selectedWelcomeCode(choice: BonusChoice, sportOffer: WelcomePromotion | null, promoOffer: WelcomePromotion | null) {
  if (choice === "none") return "NONE";
  if (choice === "promo") return promoOffer?.code ?? "NONE";
  return sportOffer?.code ?? "WELCOME_SPORT";
}

function offerText(offer: WelcomePromotion) {
  return `${offer.matchPercent}% jusqu'à ${formatEuro(offer.maxBonusAmount)}`;
}

function formatEuro(value: string) {
  return new Intl.NumberFormat("fr-FR", {
    style: "currency",
    currency: "EUR",
    maximumFractionDigits: 0
  }).format(Number(value));
}
