/* global React, ReactDOM */
/* global Field, TextInput, Textarea, MoneyInput, SurfaceInput, PhoneInput */
/* global PillGroup, YesNo, ChipGroup, formatBelgianMoney */
const { useState } = React;

const todayFR = () => {
  const d = new Date();
  return d.toLocaleDateString('fr-BE', { day: '2-digit', month: 'long', year: 'numeric' });
};

const refNumber = () => {
  const d = new Date();
  const y = d.getFullYear();
  const m = String(d.getMonth() + 1).padStart(2, '0');
  const rand = Math.floor(1000 + Math.random() * 9000);
  return `OPI-${y}${m}-${rand}`;
};

const initial = {
  // 01 — Coordonnées (DMU)
  contactName: '',
  contactEmail: '',
  contactPhone: '',
  contactPhoneCountry: 'BE',
  contactType: 'Propriétaire',
  ownerTypes: [],
  ownerCount: '',
  ownerYears: '',
  alreadyListed: null,
  viaAgency: null,
  apporteur: '',
  sellMotive: '',

  // 02 — Le bien
  address: '',
  unitCount: '',
  propertyType: '',
  buildingUnits: [],
  condition: '',
  worksAmount: '',
  surface: '',
  surfaceKind: 'SIM',
  surfaceSource: '',
  exterior: '',
  parkingGarage: null,
  parkingCount: '',
  rented: null,
  monthlyRent: '',
  availability: '',
  availabilityOther: '',

  // 03 — Conditions (prix, documents, visite)
  askingPrice: '',
  resaleMin: '',
  resaleMax: '',
  docPlans: null,
  docPermis: null,
  docPeb: null,
  pebRating: '',
  docRu: null,
  visitPlanned: null,
  visitDate: '',
  visitTime: '',

  // 04 — Notes
  notes: '',
};

function App() {
  const [s, setS] = useState(initial);
  const set = (k) => (v) => setS((prev) => ({ ...prev, [k]: v }));

  // Loyer annuel dérivé du loyer mensuel × 12
  const monthlyRentNum = parseFloat(
    String(s.monthlyRent || '').replace(/[^\d,]/g, '').replace(',', '.')
  );
  const annualRentDisplay =
    s.rented === true && !isNaN(monthlyRentNum) && monthlyRentNum > 0
      ? window.formatBelgianMoney(String(Math.round(monthlyRentNum * 12)))
      : '';

  const resizeUnits = (cur, target) => {
    const safe = Math.max(0, target | 0);
    if (cur.length === safe) return cur;
    if (safe > cur.length) {
      return [
        ...cur,
        ...Array(safe - cur.length).fill(0).map(() => ({ rent: '', bedrooms: '', state: '' })),
      ];
    }
    return cur.slice(0, safe);
  };

  const setUnitCount = (v) => {
    setS((prev) => {
      const next = { ...prev, unitCount: v };
      if (next.propertyType === 'Immeuble') {
        next.buildingUnits = resizeUnits(prev.buildingUnits || [], parseInt(v || '0', 10) || 0);
      }
      return next;
    });
  };

  const setPropertyType = (v) => {
    setS((prev) => {
      const next = { ...prev, propertyType: v };
      if (v === 'Immeuble') {
        const n = parseInt(prev.unitCount || '0', 10) || 0;
        const target = n > 0 ? n : 2;
        next.unitCount = String(target);
        next.buildingUnits = resizeUnits(prev.buildingUnits || [], target);
      } else if (v === 'Appartement' || v === 'Maison') {
        // une seule ligne, qu'on préserve si possible
        next.unitCount = '1';
        next.buildingUnits = resizeUnits(prev.buildingUnits || [], 1);
      }
      return next;
    });
  };

  const updateUnit = (idx, key, val) => {
    setS((prev) => {
      const next = [...(prev.buildingUnits || [])];
      next[idx] = { ...next[idx], [key]: val };
      return { ...prev, buildingUnits: next };
    });
  };

  const addUnit = () => {
    setS((prev) => ({
      ...prev,
      unitCount: String((parseInt(prev.unitCount || '0', 10) || 0) + 1),
      buildingUnits: [...(prev.buildingUnits || []), { rent: '', bedrooms: '', state: '' }],
    }));
  };

  const removeUnit = (idx) => {
    setS((prev) => {
      const next = (prev.buildingUnits || []).filter((_, i) => i !== idx);
      return { ...prev, buildingUnits: next, unitCount: String(next.length) };
    });
  };

  return (
    <div className="page ds-surface">

      {/* ============================================================ */}
      <header className="masthead">
        <div className="masthead__brand">
          <img src="assets/logo-light.svg" alt="Objectif Patrimoine Immobilier" />
        </div>
        <div className="masthead__title-inline">
          <div className="masthead__overline">Fiche analytique — évaluation préliminaire</div>
          <h1 className="masthead__title">Évaluation préliminaire d'un bien</h1>
        </div>
      </header>

      {/* ============================================================ */}
      {/* 01 · COORDONNÉES — Decision Making Unit                       */}
      {/* ============================================================ */}
      <section className="section">
        <div className="section__head">
          <span className="section__num">01</span>
          <h2 className="section__title">Coordonnées</h2>
          <p className="section__hint">Decision Making Unit</p>
        </div>

        <div className="grid">
          <Field className="col-4" label={"Nom & prénom\n"} required>
            <TextInput value={s.contactName} onChange={set('contactName')} placeholder="Marc Dubois" />
          </Field>
          <Field className="col-4" label={"E-mail\n"} required>
            <TextInput
              type="email"
              value={s.contactEmail}
              onChange={set('contactEmail')}
              placeholder="marc.dubois@exemple.be"
            />
          </Field>
          <Field className="col-4" label="Téléphone" required>
            <PhoneInput
              value={s.contactPhone}
              onChange={set('contactPhone')}
              country={s.contactPhoneCountry}
              onCountryChange={set('contactPhoneCountry')}
            />
          </Field>

          <Field className="col-4" label="Type de contact" required>
            <PillGroup
              value={s.contactType}
              onChange={set('contactType')}
              options={['Propriétaire', 'Tiers', 'Agent']}
              fill
            />
          </Field>
          <Field className="col-8" label="Type de propriétaire">
            <div className="chips-row">
              <ChipGroup
                values={s.ownerTypes}
                onChange={set('ownerTypes')}
                options={['Indivisaire', 'Bailleur', 'Occupant']}
                variant="pill"
              />
              <span className="chips-row__note">Plusieurs choix possibles.</span>
            </div>
          </Field>

          <Field className="col-2" label="Nbre proprios">
            <TextInput
              type="number"
              value={s.ownerCount}
              onChange={set('ownerCount')}
              placeholder="1"
              min="1"
            />
          </Field>
          <Field className="col-2" label="Détention">
            <div className="input-wrap">
              <input
                className="input"
                type="number"
                value={s.ownerYears}
                onChange={(e) => set('ownerYears')(e.target.value)}
                placeholder="0"
                min="0"
                style={{ fontVariantNumeric: 'tabular-nums' }}
              />
              <span className="input-wrap__suffix">ans</span>
            </div>
          </Field>
          <Field className="col-2" label="Déjà publié">
            <YesNo value={s.alreadyListed} onChange={set('alreadyListed')} fill />
          </Field>
          <Field className="col-2" label="Via agence">
            <YesNo value={s.viaAgency} onChange={set('viaAgency')} fill />
          </Field>
          <Field className="col-4" label="Apporteur d'affaires">
            <TextInput
              value={s.apporteur}
              onChange={set('apporteur')}
              placeholder={s.viaAgency === true ? "Nom de l'agence…" : '—'}
              disabled={s.viaAgency !== true}
              style={s.viaAgency !== true ? { background: 'var(--slate-50)', color: 'var(--fg-disabled)' } : null}
            />
          </Field>

          <Field className="col-12" label={"Motif & but de la vente\n"} required>
            <Textarea
              value={s.sellMotive}
              onChange={set('sellMotive')}
              placeholder="Succession, départ à l'étranger, arbitrage patrimonial, financement d'un autre projet…"
              rows={2}
            />
          </Field>
        </div>
      </section>

      {/* ============================================================ */}
      {/* 02 · LE BIEN — Descriptif                                     */}
      {/* ============================================================ */}
      <section className="section">
        <div className="section__head">
          <span className="section__num">02</span>
          <h2 className="section__title">Le bien</h2>
          <p className="section__hint">Descriptif</p>
        </div>

        <div className="grid">
          <Field className="col-6" label={"Adresse complète\n"} required>
            <TextInput
              value={s.address}
              onChange={set('address')}
              placeholder="Rue de la Loi 16, 1000 Bruxelles"
            />
          </Field>
          <Field className="col-2" label="Unités">
            <TextInput
              type="number"
              value={s.unitCount}
              onChange={setUnitCount}
              placeholder="1"
              min="1"
            />
          </Field>
          <Field className="col-4" label="Type de bien" required>
            <PillGroup
              value={s.propertyType}
              onChange={setPropertyType}
              options={['Appartement', 'Maison', 'Immeuble']}
              fill
            />
          </Field>

          <Field className="col-6" label="État général" required>
            <PillGroup
              value={s.condition}
              onChange={set('condition')}
              options={['À rénover', 'Correct', 'Excellent']}
              fill
            />
          </Field>
          <Field className="col-3" label="Surface bien">
            <SurfaceInput value={s.surface} onChange={set('surface')} />
          </Field>
          <Field className="col-3" label="Calcul">
            <PillGroup
              value={s.surfaceKind}
              onChange={set('surfaceKind')}
              options={['SIM', 'SEM']}
              fill
            />
          </Field>

          {s.propertyType ? (
            <div className="col-12">
              <UnitsTable
                propertyType={s.propertyType}
                units={s.buildingUnits || []}
                onChange={updateUnit}
                onAdd={addUnit}
                onRemove={removeUnit}
              />
            </div>
          ) : (
            <div className="col-12">
              <div className="units units--empty">
                <div className="units__empty">
                  Sélectionnez un type de bien pour saisir le détail.
                </div>
              </div>
            </div>
          )}

          <Field className="col-3" label="Mesuré via">
            <PillGroup
              value={s.surfaceSource}
              onChange={set('surfaceSource')}
              options={['Plans', 'PEB', 'Approx.']}
              fill
            />
          </Field>
          <Field className="col-3" label="Travaux estimés">
            <MoneyInput value={s.worksAmount} onChange={set('worksAmount')} placeholder="0" />
          </Field>
          <Field className="col-2" label="Loué">
            <YesNo value={s.rented} onChange={set('rented')} fill />
          </Field>
          <Field className="col-2" label="Loyer mensuel">
            <div className="input-wrap">
              <input
                className="input"
                type="text"
                inputMode="decimal"
                value={formatBelgianMoney(s.monthlyRent || '')}
                onChange={(e) => set('monthlyRent')(e.target.value)}
                placeholder={s.rented === true ? '0' : '—'}
                disabled={s.rented !== true}
                aria-label="Loyer mensuel"
                style={{
                  fontVariantNumeric: 'tabular-nums',
                  ...(s.rented !== true ? { background: 'var(--slate-50)', color: 'var(--fg-disabled)' } : {}),
                }}
              />
              <span className="input-wrap__suffix">€</span>
            </div>
          </Field>
          <Field className="col-2" label="Loyer annuel" hint="Mensuel × 12 (auto).">
            <div className="input-wrap">
              <input
                className="input"
                type="text"
                value={annualRentDisplay}
                placeholder="—"
                disabled
                aria-label="Loyer annuel (calculé automatiquement)"
                style={{
                  fontVariantNumeric: 'tabular-nums',
                  background: 'var(--slate-50)',
                  color: annualRentDisplay ? 'var(--fg)' : 'var(--fg-disabled)',
                  fontWeight: annualRentDisplay ? 500 : 400,
                }}
              />
              <span className="input-wrap__suffix">€</span>
            </div>
          </Field>

          <Field className="col-5" label="Espace extérieur" required>
            <PillGroup
              value={s.exterior}
              onChange={set('exterior')}
              options={['Jardin', 'Terrasse', 'Aucun']}
              fill
            />
          </Field>
          <Field className="col-2" label="Surface">
            <div className="input-wrap">
              <input
                className="input"
                type="text"
                inputMode="decimal"
                value={s.exteriorSurface || ''}
                onChange={(e) => set('exteriorSurface')(e.target.value)}
                placeholder={s.exterior === 'Jardin' || s.exterior === 'Terrasse' ? '0' : '—'}
                disabled={s.exterior !== 'Jardin' && s.exterior !== 'Terrasse'}
                aria-label="Surface extérieure"
                style={{
                  fontVariantNumeric: 'tabular-nums',
                  ...(s.exterior !== 'Jardin' && s.exterior !== 'Terrasse' ? { background: 'var(--slate-50)', color: 'var(--fg-disabled)' } : {}),
                }}
              />
              <span className="input-wrap__suffix">m²</span>
            </div>
          </Field>
          <Field className="col-5" label="Parking / garage · places">
            <div className="compose" style={{ alignItems: 'center' }}>
              <div style={{ flex: '1 1 auto', minWidth: 0 }}>
                <YesNo value={s.parkingGarage} onChange={set('parkingGarage')} fill />
              </div>
              <input
                className="compose__inline-input"
                type="number"
                value={s.parkingCount}
                onChange={(e) => set('parkingCount')(e.target.value)}
                placeholder={s.parkingGarage === true ? '0' : '—'}
                min="0"
                disabled={s.parkingGarage !== true}
                aria-label="Nombre d'emplacements"
                style={{ width: 70, flex: '0 0 auto', ...(s.parkingGarage !== true ? { background: 'var(--slate-50)', color: 'var(--fg-disabled)' } : {}) }}
              />
            </div>
          </Field>

          <Field className="col-12" label="Disponibilité" required>
            <div className="compose">
              <div style={{ flex: '1 1 auto', minWidth: 0 }}>
                <PillGroup
                  value={s.availability}
                  onChange={set('availability')}
                  options={['À l\u2019acte', 'À convenir', 'Selon locataire', 'Autre']}
                  fill
                />
              </div>
              <input
                className="input"
                type="text"
                value={s.availabilityOther}
                onChange={(e) => set('availabilityOther')(e.target.value)}
                placeholder={s.availability === 'Autre'
                  ? 'Précisez (date prévisionnelle, condition…)'
                  : '— sélectionner « Autre » pour préciser'}
                disabled={s.availability !== 'Autre'}
                aria-label="Précisez la disponibilité"
                style={{
                  flex: '1 1 110px',
                  minWidth: 0,
                  padding: '5px 10px',
                  fontSize: 13,
                  ...(s.availability !== 'Autre' ? { background: 'var(--slate-50)', color: 'var(--fg-disabled)' } : {}),
                }}
              />
            </div>
          </Field>
        </div>
      </section>

      {/* ============================================================ */}
      {/* 03 · CONDITIONS — Prix · Documents · Visite                   */}
      {/* ============================================================ */}
      <section className="section">
        <div className="section__head">
          <span className="section__num">03</span>
          <h2 className="section__title">Conditions</h2>
          <p className="section__hint">Prix · Documents · Visite</p>
        </div>

        <div className="grid">
          <Field className="col-4" label="Prix d'achat demandé" required>
            <MoneyInput value={s.askingPrice} onChange={set('askingPrice')} placeholder="0" />
          </Field>
          <Field className="col-8" label="Revente estimée — fourchette">
            <div className="sub-row">
              <MoneyInput value={s.resaleMin} onChange={set('resaleMin')} placeholder="Min" />
              <MoneyInput value={s.resaleMax} onChange={set('resaleMax')} placeholder="Max" />
            </div>
          </Field>

          {s.visitPlanned === true ? null : null}

          <div className="col-12">
            <span className="field__label" style={{ display: 'block', marginBottom: 6 }}>
              Documents disponibles
            </span>
            <div className="docs-line">
              {[
                { key: 'docPlans', label: 'Plans' },
                { key: 'docPermis', label: "Permis d'urbanisme" },
                { key: 'docRu', label: 'RU' },
              ].map(({ key, label }) => (
                <div className="doc-item" key={key}>
                  <span className="doc-item__label">{label}</span>
                  <div className="doc-item__toggle" role="radiogroup" aria-label={label}>
                    <button
                      type="button"
                      role="radio"
                      aria-checked={s[key] === true}
                      className={'doc-item__btn doc-item__btn--yes' + (s[key] === true ? ' is-on' : '')}
                      onClick={() => set(key)(s[key] === true ? null : true)}
                      title="Disponible"
                    >
                      <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                        <polyline points="20 6 9 17 4 12" />
                      </svg>
                    </button>
                    <button
                      type="button"
                      role="radio"
                      aria-checked={s[key] === false}
                      className={'doc-item__btn doc-item__btn--no' + (s[key] === false ? ' is-on' : '')}
                      onClick={() => set(key)(s[key] === false ? null : false)}
                      title="Non disponible"
                    >
                      <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                        <line x1="18" y1="6" x2="6" y2="18" />
                        <line x1="6" y1="6" x2="18" y2="18" />
                      </svg>
                    </button>
                  </div>
                </div>
              ))}
              <div className="doc-item doc-item--rating">
                <span className="doc-item__label">PEB</span>
                <div className="peb-rating" role="radiogroup" aria-label="Classe PEB">
                  {['A', 'B', 'C', 'D', 'E', 'F', 'G', '✗'].map((letter, i) => (
                    <React.Fragment key={letter}>
                      {letter === '✗' ? <span className="peb-rating__sep" aria-hidden="true" /> : null}
                      <button
                        type="button"
                        role="radio"
                        aria-checked={s.pebRating === letter}
                        className={'peb-rating__btn peb-rating__btn--' + letter.toLowerCase() + (s.pebRating === letter ? ' is-on' : '')}
                        onClick={() => set('pebRating')(s.pebRating === letter ? '' : letter)}
                        title={letter === '✗' ? 'Classe PEB inconnue' : 'Classe ' + letter}
                      >
                        {letter}
                      </button>
                    </React.Fragment>
                  ))}
                </div>
              </div>
              <div className="doc-item">
                <span className="doc-item__label">Visite</span>
                <div className="doc-item__toggle" role="radiogroup" aria-label="Visite planifiée">
                  <button
                    type="button"
                    role="radio"
                    aria-checked={s.visitPlanned === true}
                    className={'doc-item__btn doc-item__btn--yes' + (s.visitPlanned === true ? ' is-on' : '')}
                    onClick={() => set('visitPlanned')(s.visitPlanned === true ? null : true)}
                    title="Planifiée"
                  >
                    <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                      <polyline points="20 6 9 17 4 12" />
                    </svg>
                  </button>
                  <button
                    type="button"
                    role="radio"
                    aria-checked={s.visitPlanned === false}
                    className={'doc-item__btn doc-item__btn--no' + (s.visitPlanned === false ? ' is-on' : '')}
                    onClick={() => set('visitPlanned')(s.visitPlanned === false ? null : false)}
                    title="Pas planifiée"
                  >
                    <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                      <line x1="18" y1="6" x2="6" y2="18" />
                      <line x1="6" y1="6" x2="18" y2="18" />
                    </svg>
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* ============================================================ */}
      {/* 04 · NOTES — Observations complémentaires                     */}
      {/* ============================================================ */}
      <section className="section">
        <div className="section__head">
          <span className="section__num">04</span>
          <h2 className="section__title">Notes</h2>
          <p className="section__hint">Observations complémentaires</p>
        </div>

        <Textarea
          value={s.notes}
          onChange={set('notes')}
          placeholder="Contexte familial, particularités juridiques, copropriété, voisinage, projets urbanistiques aux abords…"
          large
          rows={3}
        />
      </section>

      {/* ============================================================ */}
      <div className="actions">
        <div className="actions__footer-note">
          <img src="assets/logo-mark-light.svg" alt="" className="actions__mark" aria-hidden="true" />
          <span>OPI · Objectif Patrimoine Immobilier — Fiche analytique</span>
        </div>
        <div className="actions__buttons no-print">
          <button
            type="button"
            className="btn-ghost"
            onClick={() => {
              if (confirm('Réinitialiser tous les champs de la fiche ?')) setS(initial);
            }}
          >
            Réinitialiser
          </button>
          <button type="button" className="btn-primary" onClick={() => window.print()}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6">
              <path d="M6 9V3h12v6M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2" />
              <rect x="6" y="14" width="12" height="8" rx="1" />
            </svg>
            Exporter la fiche en PDF
          </button>
        </div>
      </div>
    </div>
  );
}

function UnitsTable({ propertyType, units, onChange, onAdd, onRemove }) {
  const CONFIGS = {
    Appartement: {
      title: 'Caractéristiques du logement',
      multi: false,
      cols: [
        { key: 'floor',          label: 'Étage',           kind: 'num',     ph: '0' },
        { key: 'bedrooms',       label: 'Chambres',        kind: 'num',     ph: '0' },
        { key: 'bathrooms',      label: 'SdB',             kind: 'num',     ph: '0' },
        { key: 'balconySurface', label: 'Balcon / terrasse', kind: 'surface' },
        { key: 'state',          label: 'État',            kind: 'state' },
      ],
      rowLabel: () => 'Appartement',
    },
    Maison: {
      title: 'Caractéristiques du logement',
      multi: false,
      cols: [
        { key: 'levels',        label: 'Niveaux',     kind: 'num',     ph: '1' },
        { key: 'bedrooms',      label: 'Chambres',    kind: 'num',     ph: '0' },
        { key: 'bathrooms',     label: 'SdB',         kind: 'num',     ph: '0' },
        { key: 'gardenSurface', label: 'Jardin',      kind: 'surface' },
        { key: 'state',         label: 'État',        kind: 'state' },
      ],
      rowLabel: () => 'Maison',
    },
    Immeuble: {
      title: 'Détail par unité — immeuble de rapport',
      multi: true,
      cols: [
        { key: 'rent',      label: 'Loyer mensuel', kind: 'money' },
        { key: 'bedrooms',  label: 'Chambres',      kind: 'num',   ph: '0' },
        { key: 'bathrooms', label: 'SdB',           kind: 'num',   ph: '0' },
        { key: 'state',     label: 'État',          kind: 'state' },
      ],
      rowLabel: (i) => `Unité ${String(i + 1).padStart(2, '0')}`,
    },
  };
  const cfg = CONFIGS[propertyType];
  if (!cfg) return null;

  // grid-template-columns: label → N cols → (remove btn si multi)
  const tmpl = `1.3fr ${cfg.cols.map((c) => c.kind === 'state' ? '1fr' : c.kind === 'money' ? '1.1fr' : '0.7fr').join(' ')}${cfg.multi ? ' 22px' : ''}`;

  const renderCell = (col, value, onCellChange) => {
    if (col.kind === 'money') {
      return (
        <div className="input-wrap">
          <input
            className="input"
            type="text"
            inputMode="decimal"
            value={window.formatBelgianMoney(value || '')}
            onChange={(e) => onCellChange(e.target.value)}
            placeholder="0"
          />
          <span className="input-wrap__suffix">€</span>
        </div>
      );
    }
    if (col.kind === 'surface') {
      return (
        <div className="input-wrap">
          <input
            className="input"
            type="text"
            inputMode="decimal"
            value={value || ''}
            onChange={(e) => onCellChange(e.target.value)}
            placeholder="0"
          />
          <span className="input-wrap__suffix">m²</span>
        </div>
      );
    }
    if (col.kind === 'state') {
      return (
        <select
          className="select"
          value={value || ''}
          onChange={(e) => onCellChange(e.target.value)}
        >
          <option value="">État…</option>
          <option value="À rénover">À rénover</option>
          <option value="Correct">Correct</option>
          <option value="Excellent">Excellent</option>
        </select>
      );
    }
    // num
    return (
      <input
        className="input"
        type="number"
        value={value || ''}
        onChange={(e) => onCellChange(e.target.value)}
        placeholder={col.ph || '0'}
        min="0"
        style={{ fontVariantNumeric: 'tabular-nums' }}
      />
    );
  };

  return (
    <div className="units">
      <div className="units__head" style={{ gridTemplateColumns: tmpl }}>
        <span className="units__title">{cfg.title}</span>
        {cfg.cols.map((c) => <span key={c.key}>{c.label}</span>)}
        {cfg.multi ? <span /> : null}
      </div>

      {units.length === 0 ? (
        <div className="units__empty">
          {cfg.multi
            ? 'Aucune unité saisie — ajoutez-en ci-dessous.'
            : 'Renseignez les caractéristiques ci-dessous.'}
        </div>
      ) : null}

      {units.map((u, i) => (
        <div className="units__row" key={i} style={{ gridTemplateColumns: tmpl }}>
          <span className="units__num">{cfg.rowLabel(i)}</span>
          {cfg.cols.map((c) =>
            <div key={c.key} className="units__cell">
              {renderCell(c, u[c.key], (val) => onChange(i, c.key, val))}
            </div>
          )}
          {cfg.multi ? (
            <button
              type="button"
              className="units__remove"
              onClick={() => onRemove(i)}
              aria-label="Supprimer cette unité"
              title="Supprimer"
            >
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8">
                <path d="M3 6h18M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2m3 0v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6" />
              </svg>
            </button>
          ) : null}
        </div>
      ))}

      {cfg.multi ? (
        <button type="button" className="units__add no-print" onClick={onAdd}>
          + Ajouter une unité
        </button>
      ) : null}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
