/* =====================================================================
 * Tableau récapitulatif type tableur (édition directe dans les cellules).
 * ===================================================================== */

function GridTextCell({ value, placeholder, onChange }) {
  const cmd = isCommande(value);
  return (
    <td className={cx('border-r border-slate-200 p-0', cmd && 'bg-orange-100')}>
      <input
        className={cx(
          'w-full min-w-[4.5rem] bg-transparent px-2 py-2.5 text-center text-base placeholder:text-slate-300 sm:text-sm focus:bg-white focus:outline-none focus:ring-2 focus:ring-inset focus:ring-red-500',
          cmd && 'min-w-[9rem] font-semibold text-orange-800',
        )}
        value={value || ''}
        placeholder={placeholder}
        title={cmd ? `À commander : ${parseCommande(value).demande}` : undefined}
        onChange={(e) => onChange(e.target.value)}
      />
    </td>
  );
}

function GridCheckCell({ checked, onChange }) {
  return (
    <td className="border-r border-slate-200 text-center">
      <button
        type="button"
        onClick={() => onChange(!checked)}
        className={cx(
          'mx-auto flex h-6 w-6 items-center justify-center rounded-md border transition',
          checked ? 'border-emerald-600 bg-emerald-600 text-white' : 'border-slate-300 bg-white text-transparent hover:border-slate-400',
        )}
        aria-label={checked ? 'Attribué' : 'Non attribué'}
      >
        <Check className="h-4 w-4" />
      </button>
    </td>
  );
}

function JspPhoneList({ jsps, onOpen }) {
  const { updateJspField } = useApp();

  if (jsps.length === 0) {
    return (
      <EmptyState icon={Users} title="Aucun JSP pour cette sélection">
        Ajoutez un JSP ou changez le filtre.
      </EmptyState>
    );
  }

  return (
    <div className="space-y-3">
      {jsps.map((j) => {
        const niv = niveauOf(j.niveau);
        return (
          <article key={j.id} className={cx('rounded-xl border border-slate-200 p-3 shadow-sm', niv.row)}>
            <header className="mb-3 flex items-center justify-between gap-2">
              <button type="button" onClick={() => onOpen(j)} className="text-left text-base font-semibold text-slate-900">
                {jspFullName(j)}
              </button>
              <span className={cx('inline-flex items-center rounded-full border px-2 py-0.5 text-xs font-bold', niv.chip)}>{niv.label}</span>
            </header>
            <div className="mb-3 flex flex-wrap gap-2">
              {JSP_CHECK_FIELDS.map((f) => (
                <button
                  key={f.key}
                  type="button"
                  onClick={() => updateJspField(j.id, f.key, !j[f.key])}
                  className={cx(
                    'inline-flex items-center gap-1.5 rounded-full border px-3 py-1.5 text-sm font-medium',
                    j[f.key] ? 'border-emerald-600 bg-emerald-600 text-white' : 'border-slate-300 bg-white text-slate-600',
                  )}
                >
                  {j[f.key] && <Check className="h-3.5 w-3.5" />}
                  {f.label}
                </button>
              ))}
            </div>
            <div className="grid grid-cols-2 gap-2">
              {JSP_TEXT_FIELDS.map((f) => {
                const cmd = isCommande(j[f.key]);
                return (
                  <label key={f.key} className={cx('block rounded-lg p-1', cmd && 'bg-orange-100')}>
                    <span className="mb-1 block text-[11px] font-semibold uppercase tracking-wide text-slate-500">{f.label}</span>
                    <input
                      className={cx('input', cmd && 'border-orange-300 font-semibold text-orange-800')}
                      value={j[f.key] || ''}
                      placeholder={f.placeholder}
                      onChange={(e) => updateJspField(j.id, f.key, e.target.value)}
                    />
                  </label>
                );
              })}
            </div>
          </article>
        );
      })}
    </div>
  );
}

function JspGrid({ jsps, onOpen }) {
  const { updateJspField } = useApp();

  if (jsps.length === 0) {
    return (
      <EmptyState icon={Users} title="Aucun JSP pour cette sélection">
        Ajoutez un JSP ou créez une nouvelle année en reconduisant l'effectif.
      </EmptyState>
    );
  }

  const headCls = 'border-r border-slate-200 px-2 py-2 text-center text-[11px] font-semibold uppercase tracking-wide';

  return (
    <div className="scrollbar-thin overflow-x-auto rounded-xl border border-slate-200 bg-white shadow-sm">
      <table className="w-full min-w-[1200px] border-collapse text-sm">
        <thead>
          <tr className="text-xs">
            <th colSpan={2} className="sticky left-0 z-10 border-b border-r border-slate-200 bg-slate-800 px-3 py-2 text-left text-white">
              Identité
            </th>
            <th colSpan={JSP_CHECK_FIELDS.length + JSP_OPS_FIELDS.length} className="border-b border-r border-slate-200 bg-red-700 px-3 py-2 text-white">
              Habillement d'intervention / opérationnel
            </th>
            <th colSpan={JSP_SPORT_FIELDS.length} className="border-b border-r border-slate-200 bg-blue-700 px-3 py-2 text-white">
              Tenue de sport
            </th>
            <th className="border-b border-slate-200 bg-slate-800" />
          </tr>
          <tr className="bg-slate-100 text-slate-600">
            <th className={cx(headCls, 'sticky left-0 z-10 min-w-[110px] bg-slate-100 text-left sm:min-w-[180px]')}>Nom Prénom</th>
            <th className={headCls}>Niveau</th>
            {JSP_CHECK_FIELDS.map((f) => (
              <th key={f.key} className={cx(headCls, 'bg-red-50')}>
                {f.label}
              </th>
            ))}
            {JSP_OPS_FIELDS.map((f) => (
              <th key={f.key} className={cx(headCls, 'bg-red-50')}>
                {f.label}
              </th>
            ))}
            {JSP_SPORT_FIELDS.map((f) => (
              <th key={f.key} className={cx(headCls, 'bg-blue-50')}>
                {f.label.replace(' sport', '')}
              </th>
            ))}
            <th className="px-2" />
          </tr>
        </thead>
        <tbody>
          {jsps.map((j) => {
            const niv = niveauOf(j.niveau);
            return (
              <tr key={j.id} className={cx('border-b border-slate-200', niv.row)}>
                <td className={cx('sticky left-0 z-10 max-w-[130px] border-r border-slate-200 px-2 py-2 sm:max-w-none sm:px-3', niv.row)}>
                  <button type="button" onClick={() => onOpen(j)} className="break-words text-left text-xs font-semibold text-slate-800 hover:text-red-600 hover:underline sm:text-sm">
                    {jspFullName(j)}
                  </button>
                </td>
                <td className="border-r border-slate-200 px-2 text-center">
                  <span className={cx('inline-flex items-center gap-1 whitespace-nowrap rounded-full border px-2 py-0.5 text-xs font-bold', niv.chip)}>{niv.label}</span>
                </td>
                {JSP_CHECK_FIELDS.map((f) => (
                  <GridCheckCell key={f.key} checked={j[f.key]} onChange={(v) => updateJspField(j.id, f.key, v)} />
                ))}
                {JSP_TEXT_FIELDS.map((f) => (
                  <GridTextCell key={f.key} value={j[f.key]} placeholder={f.placeholder} onChange={(v) => updateJspField(j.id, f.key, v)} />
                ))}
                <td className="px-1 text-center">
                  <IconButton icon={Pencil} title="Ouvrir la fiche" onClick={() => onOpen(j)} />
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}
