/* =====================================================================
 * Fiche individuelle JSP (création / modification des équipements).
 * ===================================================================== */

function JspFiche({ jsp, onClose, onSave, onDelete }) {
  const [draft, setDraft] = useState(jsp);
  const set = (key, value) => setDraft((d) => ({ ...d, [key]: value }));
  const commandes = jspCommandes([draft]);
  const { jsps, jspStock } = useApp();
  const isNew = !jsp.nom && !jsp.prenom;
  const valid = draft.nom.trim() || draft.prenom.trim();

  // Pièces disponibles proposées à la saisie (hors pièces portées par les autres JSP de l'année).
  const dispoParArticle = useMemo(() => {
    const autres = jsps.filter((j) => j.annee === draft.annee && j.id !== draft.id);
    const { attributions } = stockAttributions(autres);
    const out = {};
    jspStock
      .filter((i) => !i.hs && !attributions.has(stockKey(i.article, i.taille, i.numero)))
      .sort((x, y) => compareTailles(x.taille, y.taille) || x.numero - y.numero)
      .forEach((i) => (out[i.article] = out[i.article] || []).push(i.taille ? `${i.taille}/${i.numero}` : String(i.numero)));
    return out;
  }, [jsps, jspStock, draft.annee, draft.id]);

  const renderTextField = (f) => {
    const cmd = parseCommande(draft[f.key]);
    const dispo = dispoParArticle[f.key] || [];
    return (
      <Field
        key={f.key}
        label={f.label}
        extra={cmd ? <Badge tone="amber">À commander : {cmd.demande}</Badge> : dispo.length > 0 && <Badge tone="emerald">{dispo.length} dispo</Badge>}
      >
        <TextInput
          value={draft[f.key]}
          onChange={(v) => set(f.key, v)}
          placeholder={`ex : ${f.placeholder}`}
          list={`stock-dispo-${f.key}`}
          className={cmd ? 'border-orange-400 bg-orange-50 font-semibold text-orange-800' : ''}
        />
        <datalist id={`stock-dispo-${f.key}`}>
          {dispo.map((code) => (
            <option key={code} value={code} />
          ))}
        </datalist>
      </Field>
    );
  };

  return (
    <Modal
      open
      size="lg"
      icon={Shirt}
      title={isNew ? 'Nouveau JSP' : `Fiche JSP — ${jspFullName(jsp)}`}
      subtitle={`Année ${draft.annee}`}
      onClose={onClose}
      footer={
        <Fragment>
          {!isNew && (
            <Button variant="danger" icon={Trash2} className="mr-auto" onClick={() => onDelete(jsp)}>
              Supprimer
            </Button>
          )}
          <Button variant="secondary" onClick={onClose}>
            Annuler
          </Button>
          <Button icon={Save} disabled={!valid} onClick={() => onSave(draft)}>
            Enregistrer
          </Button>
        </Fragment>
      }
    >
      <div className="space-y-6">
        <div className="grid gap-4 sm:grid-cols-3">
          <Field label="Nom">
            <TextInput value={draft.nom} onChange={(v) => set('nom', v)} autoFocus />
          </Field>
          <Field label="Prénom">
            <TextInput value={draft.prenom} onChange={(v) => set('prenom', v)} />
          </Field>
          <Field label="Niveau">
            <div className="flex flex-wrap gap-2">
              {JSP_NIVEAUX.map((n) => (
                <button
                  key={n.value}
                  type="button"
                  onClick={() => set('niveau', n.value)}
                  className={cx('chip', draft.niveau === n.value ? n.chip + ' ring-2 ring-offset-1 ring-slate-400' : 'chip-off')}
                >
                  <span className={cx('h-2.5 w-2.5 rounded-full', n.dot)} />
                  {n.label}
                </button>
              ))}
            </div>
          </Field>
        </div>

        <section>
          <h3 className="mb-3 flex items-center gap-2 text-sm font-bold uppercase tracking-wide text-slate-700">
            <ShieldCheck className="h-4 w-4 text-red-600" /> Habillement d'intervention / opérationnel
          </h3>
          <div className="mb-4 flex flex-wrap gap-6 rounded-lg bg-slate-50 p-3">
            {JSP_CHECK_FIELDS.map((f) => (
              <Checkbox key={f.key} label={f.label} checked={draft[f.key]} onChange={(v) => set(f.key, v)} />
            ))}
          </div>
          <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">{JSP_OPS_FIELDS.map(renderTextField)}</div>
        </section>

        <section>
          <h3 className="mb-3 flex items-center gap-2 text-sm font-bold uppercase tracking-wide text-slate-700">
            <Activity className="h-4 w-4 text-red-600" /> Tenue de sport
          </h3>
          <div className="grid gap-4 sm:grid-cols-3">{JSP_SPORT_FIELDS.map(renderTextField)}</div>
        </section>

        <Field label="Notes">
          <TextArea value={draft.notes} onChange={(v) => set('notes', v)} placeholder="Remarques, échanges prévus…" />
        </Field>

        <div className="rounded-lg border border-blue-100 bg-blue-50 p-3 text-xs text-blue-800">
          <p className="flex items-center gap-1.5 font-semibold">
            <Info className="h-4 w-4" /> Astuce
          </p>
          Saisissez « Commande 164 », « 40 COMMANDE 41 » ou « Cde M » dans un champ pour l'ajouter automatiquement à l'état des besoins.
          {commandes.length > 0 && ` (${commandes.length} besoin${commandes.length > 1 ? 's' : ''} détecté${commandes.length > 1 ? 's' : ''} sur cette fiche)`}
        </div>
      </div>
    </Modal>
  );
}
