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

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

export default function RolePicker({ current }: { current: string | null }) {
  const [busy, setBusy] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  async function pick(role: string) {
    setBusy(role);
    setError(null);
    const res = await fetch("/api/profile/role", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ role }),
    });
    if (res.ok) window.location.reload();
    else {
      setError("Impossible d'enregistrer — réessayez.");
      setBusy(null);
    }
  }

  return (
    <div>
      <div className="grid gap-2 sm:grid-cols-3">
        {Object.entries(ROLES).map(([value, r]) => (
          <button
            key={value}
            type="button"
            disabled={busy !== null}
            onClick={() => pick(value)}
            className={`rounded-md border-[1.5px] px-4 py-3 text-left transition-all ${
              current === value
                ? "border-ink bg-lime-soft shadow-[3px_3px_0_rgba(20,24,20,0.15)]"
                : "border-[rgba(20,24,20,0.3)] bg-surface hover:border-ink"
            }`}
          >
            <span className="gk-display block text-[13.5px] font-bold">
              {busy === value ? "Un instant…" : r.label}
            </span>
            <span className="mt-[2px] block text-[11.5px] leading-snug text-ink-2">
              {r.desc}
            </span>
          </button>
        ))}
      </div>
      {error && (
        <p className="mt-2 rounded-md border-[1.5px] border-[#b3423a] bg-[#fbe9e7] px-3 py-2 text-[12.5px] font-medium text-[#7c2f2a]">
          {error}
        </p>
      )}
    </div>
  );
}
