// All wizard steps for Rapport d'intervention
// Each step receives { data, set } where set is (key, val) => void

const D = () => window.RAPPORT_DATA;
const { useState: useS, useEffect: useE, useRef: useR, useMemo: useM } = React;

// ============================================================
// STEP 1 — Début / Répartition
// ============================================================
function StepDebut({ data, set }) {
  return (
    <>
      <div className="step-header">
        <div className="step-eyebrow">Étape 1 · Répartition</div>
        <h1 className="step-title">Début de l'intervention</h1>
        <p className="step-subtitle">Identifiez l'appel et l'heure d'intervention. Le numéro de rapport est généré automatiquement.</p>
      </div>

      <Card title="Identification de l'appel" icon={<Icon.Phone />}>
        <div className="grid">
          <Field label="N° de rapport" hint="auto" span={4}>
            <div className="input-prefix-suffix">
              <span className="prefix">{data.saison || 'ÉTÉ 2026'}</span>
              <input className="input input-mono" readOnly value={data.reportNumber || ''} />
            </div>
          </Field>
          <Field label="Date" required span={4}>
            <TextInput value={data.date} onChange={(v) => set('date', v)} type="date" />
          </Field>
          <Field label="Heure" required span={4}>
            <TextInput value={data.heure} onChange={(v) => set('heure', v)} type="time" icon={<Icon.Clock />} />
          </Field>
          <Field label="Répartiteur" required span={6}>
            <PatrouillerPicker value={data.repartiteur} onChange={(v) => set('repartiteur', v)} role="Répartiteur" />
          </Field>
          <Field label="Appelant" required span={6}>
            <PatrouillerPicker value={data.appelant} onChange={(v) => set('appelant', v)} role="Appelant" />
          </Field>
        </div>
      </Card>
    </>
  );
}

// ============================================================
// STEP 2 — Localisation
// ============================================================
function StepLocalisation({ data, set }) {
  const codes = D().codes;
  return (
    <>
      <div className="step-header">
        <div className="step-eyebrow">Étape 2 · Localisation</div>
        <h1 className="step-title">Où s'est passé l'événement ?</h1>
        <p className="step-subtitle">Précisez l'endroit, le repère sur la piste, et attribuez un code de priorité.</p>
      </div>

      <Card title="Code de priorité" icon={<Icon.AlertTriangle />} subtitle="Sélectionnez la gravité initiale">
        <div className="code-grid">
          {codes.map(c => (
            <div
              key={c.value}
              className={`code-card ${data.code === c.value ? 'selected' : ''}`}
              onClick={() => set('code', c.value)}
            >
              <div className="code-dot" style={{ background: c.color }}></div>
              <div className="code-label">{c.value}</div>
              <div className="code-desc">{c.label.split('—')[1]?.trim()}</div>
            </div>
          ))}
        </div>
      </Card>

      <Card title="Endroit et repère" icon={<Icon.MapPin />}>
        <div className="grid">
          <Field label="Endroit / sentier" required span={8}>
            <Select value={data.endroit} onChange={(v) => set('endroit', v)} options={D().endroits} placeholder="Choisir le sentier ou le lieu…" />
          </Field>
          <Field label="Repère sur la piste" required span={4}>
            <Select value={data.repere} onChange={(v) => set('repere', v)} options={D().reperes} />
          </Field>
          <Field label="Sommet de référence" span={4}>
            <Select value={data.sommet} onChange={(v) => set('sommet', v)} options={D().sommets} />
          </Field>
          <Field label="Conditions météo" span={4}>
            <Select value={data.meteo} onChange={(v) => set('meteo', v)} options={D().conditionsMeteo} />
          </Field>
          <Field label="État du sentier" span={4}>
            <Select value={data.sentierEtat} onChange={(v) => set('sentierEtat', v)} options={D().conditionsSentier} />
          </Field>
          <Field label="Notes de localisation" span={12} hint="optionnel">
            <TextArea value={data.localisationNotes} onChange={(v) => set('localisationNotes', v)} placeholder="Repères visuels, distance d'un point connu, etc." />
          </Field>
        </div>
      </Card>
    </>
  );
}

// ============================================================
// STEP 3 — Équipe de patrouille
// ============================================================
function StepEquipe({ data, set }) {
  const team = data.team || [];
  const setSlot = (i, v) => {
    const t = [...team];
    t[i] = v;
    set('team', t);
  };

  // figure out how many to show — at least 2 + filled + 1 empty
  const shown = Math.max(2, team.filter(Boolean).length + 1, team.length);
  const slots = Array.from({ length: Math.min(shown, 12) });

  return (
    <>
      <div className="step-header">
        <div className="step-eyebrow">Étape 3 · Équipe</div>
        <h1 className="step-title">Équipe de patrouille</h1>
        <p className="step-subtitle">P1 est le chef d'intervention. Ajoutez jusqu'à 12 patrouilleurs.</p>
      </div>

      <Card>
        <div className="grid">
          {slots.map((_, i) => (
            <div className="col-6" key={i}>
              <PatrouillerPicker
                value={team[i]}
                onChange={(v) => setSlot(i, v)}
                role={i === 0 ? 'P1 — Chef d\'intervention' : `P${i + 1}`}
              />
            </div>
          ))}
          {shown < 12 && (
            <div className="col-12">
              <button className="btn btn-ghost" onClick={() => set('team', [...team, ''])}>
                <Icon.Plus /> Ajouter un patrouilleur
              </button>
            </div>
          )}
        </div>
      </Card>
    </>
  );
}

// ============================================================
// STEP 4 — Patient
// ============================================================
function StepPatient({ data, set }) {
  const p = data.patient || {};
  const sp = (k, v) => set('patient', { ...p, [k]: v });
  return (
    <>
      <div className="step-header">
        <div className="step-eyebrow">Étape 4 · Patient</div>
        <h1 className="step-title">Informations patient</h1>
        <p className="step-subtitle">Identité et coordonnées. Cochez « Refus de soins » si applicable.</p>
      </div>

      <Card title="Identité" icon={<Icon.User />}>
        <div className="grid">
          <Field label="Prénom" required span={6}>
            <TextInput value={p.prenom} onChange={(v) => sp('prenom', v)} />
          </Field>
          <Field label="Nom" required span={6}>
            <TextInput value={p.nom} onChange={(v) => sp('nom', v)} />
          </Field>
          <Field label="Adresse postale" span={12}>
            <TextInput value={p.adresse} onChange={(v) => sp('adresse', v)} placeholder="Rue, app." />
          </Field>
          <Field label="Ville" span={5}>
            <TextInput value={p.ville} onChange={(v) => sp('ville', v)} />
          </Field>
          <Field label="Province / État" span={4}>
            <TextInput value={p.province} onChange={(v) => sp('province', v)} />
          </Field>
          <Field label="Code postal" span={3}>
            <TextInput value={p.cp} onChange={(v) => sp('cp', v)} mono />
          </Field>
          <Field label="Téléphone" required span={6}>
            <TextInput value={p.tel} onChange={(v) => sp('tel', v)} placeholder="(514) 555-1234" mono />
          </Field>
          <Field label="Genre" span={6}>
            <ChipGroup value={p.genre} onChange={(v) => sp('genre', v)} options={D().sexes} />
          </Field>
        </div>
      </Card>

      <Card title="Profil sportif" icon={<Icon.Activity />}>
        <div className="grid">
          <Field label="Âge" span={3}>
            <TextInput value={p.age} onChange={(v) => sp('age', v)} type="number" />
          </Field>
          <Field label="Niveau" span={5}>
            <ChipGroup value={p.niveau} onChange={(v) => sp('niveau', v)} options={D().niveaux} />
          </Field>
          <Field label="Sorties cette année" hint="estim." span={4}>
            <TextInput value={p.sorties} onChange={(v) => sp('sorties', v)} type="number" />
          </Field>
          <Field label="Activité pratiquée" span={6}>
            <Select value={p.activite} onChange={(v) => sp('activite', v)} options={D().activites} />
          </Field>
          <Field label="Protections portées" span={6}>
            <ChipMulti value={p.protections} onChange={(v) => sp('protections', v)} options={D().protections} />
          </Field>
        </div>
      </Card>

      <Toggle
        label="Refus de soins (signature requise à la fin)"
        desc="Le patient refuse les soins prodigués ou le transport"
        value={!!data.refus}
        onChange={(v) => set('refus', v)}
      />
    </>
  );
}

// ============================================================
// STEP 5 — Évaluation primaire (ABCDE + AVPU)
// ============================================================
function StepEvaluation({ data, set }) {
  const e = data.evaluation || {};
  const se = (k, v) => set('evaluation', { ...e, [k]: v });
  const avpu = e.avpu || {};
  const sav = (k, v) => se('avpu', { ...avpu, [k]: v });
  return (
    <>
      <div className="step-header">
        <div className="step-eyebrow">Étape 5 · Évaluation primaire</div>
        <h1 className="step-title">ABCDE & AVPU</h1>
        <p className="step-subtitle">Évaluation primaire systématique du patient.</p>
      </div>

      <Card title="ABCDE" icon={<Icon.Stethoscope />}>
        <div className="assess-row">
          <div className="assess-letter" data-l="A">A</div>
          <div className="assess-content">
            <div>
              <div className="assess-label">Airway — Voies respiratoires</div>
              <div className="assess-hint">Libres, partiellement obstruées, obstruées</div>
            </div>
            <ChipGroup value={e.airway} onChange={(v) => se('airway', v)} options={D().qualitatif} />
          </div>
        </div>
        <div className="assess-row">
          <div className="assess-letter" data-l="B">B</div>
          <div className="assess-content">
            <div>
              <div className="assess-label">Breathing — Respiration</div>
              <div className="assess-hint">Qualité, rythme</div>
            </div>
            <ChipGroup value={e.breathing} onChange={(v) => se('breathing', v)} options={D().qualitatif} />
          </div>
        </div>
        <div className="assess-row">
          <div className="assess-letter" data-l="C">C</div>
          <div className="assess-content">
            <div>
              <div className="assess-label">Circulation — Apparence peau</div>
              <div className="assess-hint">Couleur, température, humidité</div>
            </div>
            <ChipMulti value={e.peau || []} onChange={(v) => se('peau', v)} options={D().apparencePeau} />
          </div>
        </div>
        <div className="assess-row">
          <div className="assess-letter" data-l="D">D</div>
          <div className="assess-content">
            <div>
              <div className="assess-label">Disability — Conscience</div>
              <div className="assess-hint">Niveau global</div>
            </div>
            <ChipGroup value={e.conscience} onChange={(v) => se('conscience', v)} options={D().niveauxConscience} />
          </div>
        </div>
        <div className="assess-row">
          <div className="assess-letter" data-l="E">E</div>
          <div className="assess-content">
            <div>
              <div className="assess-label">Exposure — Douleur à la poitrine ?</div>
              <div className="assess-hint">Symptôme à signaler</div>
            </div>
            <ChipGroup value={e.douleurPoitrine} onChange={(v) => se('douleurPoitrine', v)} options={D().ouiNon} />
          </div>
        </div>
      </Card>

      <Card title="AVPU — Niveau de conscience détaillé" subtitle="Réponses du patient aux stimuli" icon={<Icon.Activity />}>
        <div className="grid">
          <Field label="A — Alerte" span={6}>
            <ChipGroup value={avpu.A} onChange={(v) => sav('A', v)} options={["Oui", "Confus", "Non"]} />
          </Field>
          <Field label="V — Verbal" span={6}>
            <ChipGroup value={avpu.V} onChange={(v) => sav('V', v)} options={D().ouiNon} />
          </Field>
          <Field label="P — Pain (douleur)" span={6}>
            <ChipGroup value={avpu.P} onChange={(v) => sav('P', v)} options={D().ouiNon} />
          </Field>
          <Field label="U — Unresponsive" span={6}>
            <ChipGroup value={avpu.U} onChange={(v) => sav('U', v)} options={D().ouiNon} />
          </Field>
        </div>
      </Card>

      <Card title="Hémorragie & arrêts" icon={<Icon.AlertTriangle />}>
        <div className="grid">
          <Field label="Hémorragie grave ?" span={4}>
            <ChipGroup value={e.hemorragie} onChange={(v) => se('hemorragie', v)} options={D().ouiNon} />
          </Field>
          {e.hemorragie === 'OUI' && (
            <Field label="Site de l'hémorragie" span={8}>
              <Select value={e.hemorragieSite} onChange={(v) => se('hemorragieSite', v)} options={D().hemorragieSites} />
            </Field>
          )}
          <Field label="Arrêt respiratoire ?" span={6}>
            <ChipGroup value={e.arretResp} onChange={(v) => se('arretResp', v)} options={D().ouiNon} />
          </Field>
          <Field label="Arrêt cardiaque ?" span={6}>
            <ChipGroup value={e.arretCard} onChange={(v) => se('arretCard', v)} options={D().ouiNon} />
          </Field>
        </div>
      </Card>
    </>
  );
}

// ============================================================
// STEP 6 — Blessures (parties du corps × jusqu'à 3)
// ============================================================
function StepBlessures({ data, set }) {
  const inj = data.injuries || [{}];
  const setInj = (next) => set('injuries', next);
  const upd = (i, k, v) => {
    const n = [...inj];
    n[i] = { ...n[i], [k]: v };
    setInj(n);
  };

  return (
    <>
      <div className="step-header">
        <div className="step-eyebrow">Étape 6 · Blessures</div>
        <h1 className="step-title">Blessures soupçonnées</h1>
        <p className="step-subtitle">Documentez jusqu'à 3 blessures distinctes. Une carte par partie du corps.</p>
      </div>

      {inj.map((b, i) => (
        <div className="injury-card" key={i}>
          <div className="injury-header">
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <span className="injury-num">BL. #{i + 1}</span>
              <strong>{b.partie || 'Nouvelle blessure'}</strong>
            </div>
            {inj.length > 1 && (
              <button className="btn btn-danger btn-sm" onClick={() => setInj(inj.filter((_, j) => j !== i))}>
                <Icon.X /> Retirer
              </button>
            )}
          </div>
          <div className="grid">
            <Field label="Partie du corps" required span={12}>
              <ChipGroup value={b.partie} onChange={(v) => upd(i, 'partie', v)} options={D().partiesCorps} square />
            </Field>
            <Field label="Blessure soupçonnée" required span={6}>
              <Select value={b.type} onChange={(v) => upd(i, 'type', v)} options={D().blessuresSoupconnees} />
            </Field>
            <Field label="Endroit / face" span={6}>
              <Select value={b.endroit} onChange={(v) => upd(i, 'endroit', v)} options={D().endroitsBlessure} />
            </Field>
            <Field label="Préexistante connue ?" span={12}>
              <ChipGroup value={b.preexistante} onChange={(v) => upd(i, 'preexistante', v)} options={D().ouiNonInconnu} />
            </Field>
          </div>
        </div>
      ))}

      {inj.length < 3 && (
        <button className="btn" onClick={() => setInj([...inj, {}])}>
          <Icon.Plus /> Ajouter une blessure
        </button>
      )}
    </>
  );
}

// ============================================================
// STEP 7 — SAMPLE
// ============================================================
function StepSample({ data, set }) {
  const s = data.sample || {};
  const ss = (k, v) => set('sample', { ...s, [k]: v });
  return (
    <>
      <div className="step-header">
        <div className="step-eyebrow">Étape 7 · SAMPLE</div>
        <h1 className="step-title">Anamnèse SAMPLE</h1>
        <p className="step-subtitle">Signes, Allergies, Médicaments, Passé médical, Last meal, Événement.</p>
      </div>

      <Card title="S — Signes & symptômes" icon={<span style={{ fontWeight: 700, fontFamily: 'Geist Mono' }}>S</span>}>
        <Field label="Décrire les signes et symptômes observés" span={12}>
          <TextArea value={s.signes} onChange={(v) => ss('signes', v)} placeholder="Ex : douleur localisée, gonflement, nausée…" rows={3} />
        </Field>
      </Card>

      <Card title="Évaluation de la douleur" icon={<Icon.Activity />}>
        <Field label="Quantifier — Échelle 0 à 10" span={12}>
          <div>
            <div className="pain-scale">
              {Array.from({ length: 11 }).map((_, n) => (
                <button
                  key={n}
                  type="button"
                  className={`pain-num ${s.douleurNiveau === n ? 'selected' : ''}`}
                  data-level={n}
                  onClick={() => ss('douleurNiveau', n)}
                >{n}</button>
              ))}
            </div>
            <div className="pain-labels">
              <span>Aucune douleur</span>
              <span>Pire douleur imaginable</span>
            </div>
          </div>
        </Field>
        <div className="grid" style={{ marginTop: 14 }}>
          <Field label="Qualifier la douleur" span={12}>
            <ChipMulti value={s.douleurQuali} onChange={(v) => ss('douleurQuali', v)} options={D().douleurQualitative} />
          </Field>
        </div>
      </Card>

      <Card title="A · M · P · L · E" subtitle="Allergies, médicaments, passé médical, dernier repas, événement" icon={<Icon.FileText />}>
        <div className="grid">
          <Field label="A — Allergies connues" hint="Si oui, lesquelles ?" span={12}>
            <TextArea value={s.allergies} onChange={(v) => ss('allergies', v)} placeholder="Ex : pollen, pénicilline. NON si aucune." rows={2} />
          </Field>
          <Field label="M — Médicaments" hint="Si oui, lesquels ?" span={12}>
            <TextArea value={s.medicaments} onChange={(v) => ss('medicaments', v)} placeholder="Ex : anti-dépresseur. NON si aucun." rows={2} />
          </Field>
          <Field label="P — Passé / historique médical" hint="Quoi & quand" span={12}>
            <TextArea value={s.passe} onChange={(v) => ss('passe', v)} placeholder="Ex : opération genou D en déc. 2025." rows={2} />
          </Field>
          <Field label="L — Dernier repas" hint="Heure et nature" span={12}>
            <TextInput value={s.last} onChange={(v) => ss('last', v)} placeholder="Ex : 12h30 — sandwich, café" />
          </Field>
          <Field label="E — Événement déclencheur" hint="Que faisait le patient juste avant ?" span={12}>
            <TextArea value={s.evenement} onChange={(v) => ss('evenement', v)} rows={2} />
          </Field>
        </div>
      </Card>
    </>
  );
}

// ============================================================
// STEP 8 — Soins prodigués & matériel
// ============================================================
function StepSoins({ data, set }) {
  return (
    <>
      <div className="step-header">
        <div className="step-eyebrow">Étape 8 · Premiers soins</div>
        <h1 className="step-title">Soins & matériel utilisé</h1>
        <p className="step-subtitle">Détails de la prise en charge et inventaire du matériel.</p>
      </div>

      <Card title="Détail des premiers soins et immobilisation" icon={<Icon.Bandage />}>
        <Field label="Description complète" hint="ABCDE, nettoyage, immobilisation, etc." span={12}>
          <TextArea
            value={data.soinsDetail}
            onChange={(v) => set('soinsDetail', v)}
            placeholder="Ex : ABCDE fait, nettoyer les égratignures, procéder à l'immobilisation du poignet D avec carton, écharpe simple et bande de transport"
            rows={5}
          />
        </Field>
      </Card>

      <Card title="Matériels utilisés" icon={<Icon.FileText />}>
        <Field label="Liste du matériel consommé" span={12}>
          <TextArea
            value={data.materiel}
            onChange={(v) => set('materiel', v)}
            placeholder="Ex : 2 tampons de nettoyant et un 4×4, carton, 2 bandes beige"
            rows={4}
          />
        </Field>
      </Card>

      <Card title="Photos" icon={<Icon.Camera />} subtitle="Optionnel — ajoutez jusqu'à 6 photos">
        <div className="grid">
          {[0, 1, 2].map(i => (
            <div className="col-4" key={i}>
              <div style={{
                background: 'var(--panel-2)', border: '1.5px dashed var(--border-strong)',
                borderRadius: 10, aspectRatio: '4/3', display: 'grid', placeItems: 'center',
                color: 'var(--muted-2)', fontSize: 13, cursor: 'pointer'
              }}>
                <div style={{ textAlign: 'center' }}>
                  <Icon.Camera style={{ width: 24, height: 24, opacity: 0.5 }} />
                  <div style={{ marginTop: 6 }}>Photo {i + 1}</div>
                </div>
              </div>
            </div>
          ))}
        </div>
      </Card>
    </>
  );
}

// ============================================================
// STEP 9 — Événement (facteurs + autres impliqués)
// ============================================================
function StepEvenement({ data, set }) {
  const ev = data.evenement || {};
  const sev = (k, v) => set('evenement', { ...ev, [k]: v });

  return (
    <>
      <div className="step-header">
        <div className="step-eyebrow">Étape 9 · Événement</div>
        <h1 className="step-title">Facteurs et personnes impliquées</h1>
        <p className="step-subtitle">Contextualisez l'événement et documentez les autres impliqués si présents.</p>
      </div>

      <Card title="Facteurs contributifs" icon={<Icon.AlertTriangle />}>
        <div className="grid">
          <Field label="Qu'est-ce qui a causé l'événement ?" span={12}>
            <ChipGroup value={ev.cause} onChange={(v) => sev('cause', v)} options={D().facteursContributifs} square />
          </Field>
          <Field label="Type d'événement" span={6}>
            <Select value={ev.type} onChange={(v) => sev('type', v)} options={D().typesEvenement} />
          </Field>
          <Field label="Collision avec" span={6}>
            <Select value={ev.collision} onChange={(v) => sev('collision', v)} options={D().collisions} />
          </Field>
          <Field label="Récit / description libre" hint="optionnel" span={12}>
            <TextArea value={ev.recit} onChange={(v) => sev('recit', v)} rows={3}
              placeholder="Comment l'événement s'est déroulé, dans les mots du patient ou des témoins" />
          </Field>
        </div>
      </Card>

      <Toggle
        label="Une autre personne a été blessée"
        desc="Cocher si l'événement implique une seconde victime"
        value={!!data.autreBlesse}
        onChange={(v) => set('autreBlesse', v)}
      />

      {data.autreBlesse && (
        <Card title="Autre personne blessée" icon={<Icon.User />}>
          <div className="grid">
            <Field label="Prénom & nom" span={6}>
              <TextInput value={data.autrePrenom} onChange={(v) => set('autrePrenom', v)} />
            </Field>
            <Field label="Téléphone" span={6}>
              <TextInput value={data.autreTel} onChange={(v) => set('autreTel', v)} mono />
            </Field>
            <Field label="Adresse" span={12}>
              <TextInput value={data.autreAdresse} onChange={(v) => set('autreAdresse', v)} />
            </Field>
          </div>
        </Card>
      )}

      <div style={{ marginTop: 12 }}>
        <Toggle
          label="Des témoins étaient présents"
          desc="Cocher pour ajouter les coordonnées d'un témoin"
          value={!!data.temoin}
          onChange={(v) => set('temoin', v)}
        />
      </div>

      {data.temoin && (
        <Card title="Témoin" icon={<Icon.Users />}>
          <div className="grid">
            <Field label="Prénom & nom" span={6}>
              <TextInput value={data.temoinPrenom} onChange={(v) => set('temoinPrenom', v)} />
            </Field>
            <Field label="Téléphone" span={6}>
              <TextInput value={data.temoinTel} onChange={(v) => set('temoinTel', v)} mono />
            </Field>
            <Field label="Adresse" span={12}>
              <TextInput value={data.temoinAdresse} onChange={(v) => set('temoinAdresse', v)} />
            </Field>
          </div>
        </Card>
      )}
    </>
  );
}

// ============================================================
// STEP 10 — Transport (911 conditional)
// ============================================================
function StepTransport({ data, set }) {
  const t = data.transport || {};
  const st = (k, v) => set('transport', { ...t, [k]: v });
  return (
    <>
      <div className="step-header">
        <div className="step-eyebrow">Étape 10 · Transport</div>
        <h1 className="step-title">Transport du blessé</h1>
        <p className="step-subtitle">Méthode utilisée et, si requis, détails de l'appel 911 / ambulance.</p>
      </div>

      <Card title="Transport interne" icon={<Icon.Truck />}>
        <div className="grid">
          <Field label="Méthode de transport" required span={6}>
            <Select value={t.methode} onChange={(v) => st('methode', v)} options={D().transports} />
          </Field>
          <Field label="Sommet de départ" span={6}>
            <Select value={t.sommet} onChange={(v) => st('sommet', v)} options={D().sommets} />
          </Field>
          <Field label="Heure départ vers clinique" span={6}>
            <TextInput value={t.heureDepart} onChange={(v) => st('heureDepart', v)} type="time" icon={<Icon.Clock />} />
          </Field>
          <Field label="Heure arrivée à la clinique" span={6}>
            <TextInput value={t.heureArrivee} onChange={(v) => st('heureArrivee', v)} type="time" icon={<Icon.Clock />} />
          </Field>
        </div>
      </Card>

      <Toggle
        label="Appel 911 / ambulance effectué"
        desc="Cocher pour saisir les détails de l'appel et de l'ambulance"
        value={!!data.appel911}
        onChange={(v) => set('appel911', v)}
      />

      {data.appel911 && (
        <Card title="Appel 911 / ambulance" icon={<Icon.Phone />}>
          <div className="grid">
            <Field label="Appelant 911" span={6}>
              <PatrouillerPicker value={data.amb911Appelant} onChange={(v) => set('amb911Appelant', v)} role="Appelant 911" />
            </Field>
            <Field label="Heure d'appel" span={6}>
              <TextInput value={data.amb911Heure} onChange={(v) => set('amb911Heure', v)} type="time" icon={<Icon.Clock />} />
            </Field>
            <Field label="Adresse pour la prise en charge" span={12}>
              <TextInput value={data.amb911Adresse} onChange={(v) => set('amb911Adresse', v)} placeholder="Ex : stationnement P1 — entrée nord" />
            </Field>
            <Field label="Heure d'arrivée de l'ambulance" span={6}>
              <TextInput value={data.amb911Arrivee} onChange={(v) => set('amb911Arrivee', v)} type="time" icon={<Icon.Clock />} />
            </Field>
            <Field label="Heure de départ de l'ambulance" span={6}>
              <TextInput value={data.amb911Depart} onChange={(v) => set('amb911Depart', v)} type="time" icon={<Icon.Clock />} />
            </Field>
            <Field label="# ambulance" span={6}>
              <TextInput value={data.amb911Num} onChange={(v) => set('amb911Num', v)} mono />
            </Field>
            <Field label="Hôpital de destination" span={6}>
              <Select value={data.amb911Dest} onChange={(v) => set('amb911Dest', v)} options={D().hopitaux} />
            </Field>
          </div>
        </Card>
      )}
    </>
  );
}

// ============================================================
// STEP 11 — Récapitulatif & signature
// ============================================================
function StepRecap({ data, set, jumpTo, onSubmit }) {
  const canvasRef = useR(null);
  const [signed, setSigned] = useS(!!data.signature);
  const drawing = useR(false);
  const last = useR(null);

  useE(() => {
    const c = canvasRef.current;
    if (!c) return;
    const dpr = window.devicePixelRatio || 1;
    const rect = c.getBoundingClientRect();
    c.width = rect.width * dpr;
    c.height = rect.height * dpr;
    const ctx = c.getContext('2d');
    ctx.scale(dpr, dpr);
    ctx.strokeStyle = '#1A2520';
    ctx.lineWidth = 2;
    ctx.lineCap = 'round';
    ctx.lineJoin = 'round';
  }, []);

  const pos = (e) => {
    const c = canvasRef.current;
    const rect = c.getBoundingClientRect();
    const t = e.touches ? e.touches[0] : e;
    return { x: t.clientX - rect.left, y: t.clientY - rect.top };
  };
  const start = (e) => { drawing.current = true; last.current = pos(e); };
  const move = (e) => {
    if (!drawing.current) return;
    e.preventDefault();
    const ctx = canvasRef.current.getContext('2d');
    const p = pos(e);
    ctx.beginPath();
    ctx.moveTo(last.current.x, last.current.y);
    ctx.lineTo(p.x, p.y);
    ctx.stroke();
    last.current = p;
    if (!signed) { setSigned(true); set('signature', true); }
  };
  const end = () => { drawing.current = false; };
  const clear = () => {
    const c = canvasRef.current;
    const ctx = c.getContext('2d');
    ctx.clearRect(0, 0, c.width, c.height);
    setSigned(false);
    set('signature', false);
  };

  const recapSections = [
    { idx: 0, title: '1 · Répartition', items: [
      ['Date', data.date],
      ['Heure', data.heure],
      ['Répartiteur', data.repartiteur],
      ['Appelant', data.appelant],
    ]},
    { idx: 1, title: '2 · Localisation', items: [
      ['Endroit', data.endroit],
      ['Repère', data.repere],
      ['Code', data.code],
      ['Météo', data.meteo],
    ]},
    { idx: 2, title: '3 · Équipe', items: [
      ['Équipe', (data.team || []).filter(Boolean).join(' · ')],
    ]},
    { idx: 3, title: '4 · Patient', items: [
      ['Nom', [data.patient?.prenom, data.patient?.nom].filter(Boolean).join(' ')],
      ['Téléphone', data.patient?.tel],
      ['Âge / Genre', [data.patient?.age, data.patient?.genre].filter(Boolean).join(' · ')],
      ['Activité', data.patient?.activite],
      ['Niveau', data.patient?.niveau],
      ['Refus de soins', data.refus ? 'Oui' : 'Non'],
    ]},
    { idx: 4, title: '5 · Évaluation primaire', items: [
      ['Conscience', data.evaluation?.conscience],
      ['Airway', data.evaluation?.airway],
      ['Breathing', data.evaluation?.breathing],
      ['Hémorragie grave', data.evaluation?.hemorragie],
    ]},
    { idx: 5, title: '6 · Blessures', items: (data.injuries || []).map((b, i) => [
      `Bl. #${i + 1}`, [b.partie, b.type].filter(Boolean).join(' — ')
    ]) },
    { idx: 6, title: '7 · SAMPLE', items: [
      ['Douleur', data.sample?.douleurNiveau != null ? `${data.sample.douleurNiveau}/10` : ''],
      ['Allergies', data.sample?.allergies],
      ['Médicaments', data.sample?.medicaments],
      ['Passé médical', data.sample?.passe],
    ]},
    { idx: 7, title: '8 · Soins', items: [
      ['Détail', data.soinsDetail],
      ['Matériel', data.materiel],
    ]},
    { idx: 8, title: '9 · Événement', items: [
      ['Cause', data.evenement?.cause],
      ['Type', data.evenement?.type],
      ['Collision', data.evenement?.collision],
    ]},
    { idx: 9, title: '10 · Transport', items: [
      ['Méthode', data.transport?.methode],
      ['Heure départ', data.transport?.heureDepart],
      ['911', data.appel911 ? `Oui — ${data.amb911Dest || ''}` : 'Non'],
    ]},
  ];

  return (
    <>
      <div className="step-header">
        <div className="step-eyebrow">Étape 11 · Récapitulatif</div>
        <h1 className="step-title">Vérifier & soumettre</h1>
        <p className="step-subtitle">Vérifiez chaque section. Cliquez « Modifier » pour revenir à une étape. Signez pour soumettre.</p>
      </div>

      <Card>
        {recapSections.map(s => (
          <div className="recap-section" key={s.idx}>
            <div className="recap-section-title">
              {s.title}
              <span className="recap-edit" onClick={() => jumpTo(s.idx)}>Modifier ↗</span>
            </div>
            <div className="recap-grid">
              {s.items.length === 0 ? (
                <span className="recap-val empty">—</span>
              ) : s.items.map(([k, v], i) => (
                <React.Fragment key={i}>
                  <div className="recap-key">{k}</div>
                  <div className={`recap-val ${v ? '' : 'empty'}`}>{v || 'À remplir'}</div>
                </React.Fragment>
              ))}
            </div>
          </div>
        ))}
      </Card>

      <Card title={data.refus ? "Signature du patient (refus de soins)" : "Signature du chef d'intervention (P1)"} icon={<Icon.FileText />} action={
        signed && <button className="btn btn-sm btn-ghost" onClick={clear}>Effacer</button>
      }>
        <div className={`signature ${signed ? 'signed' : ''}`}>
          <canvas
            ref={canvasRef}
            onMouseDown={start} onMouseMove={move} onMouseUp={end} onMouseLeave={end}
            onTouchStart={start} onTouchMove={move} onTouchEnd={end}
          />
          <div className="signature-placeholder">Signer ici avec le doigt ou la souris</div>
        </div>
      </Card>
    </>
  );
}

// ============================================================
// STEP 12 — Submitted
// ============================================================
function StepSubmitted({ data, onNewReport }) {
  return (
    <div className="submitted">
      <div className="submitted-check">
        <Icon.Check />
      </div>
      <h1>Rapport soumis</h1>
      <p>Une copie PDF a été archivée et envoyée à l'administration.</p>
      <div className="submitted-meta">
        <div className="recap-grid">
          <div className="recap-key">N° de rapport</div>
          <div className="recap-val mono">{data.reportNumber}</div>
          <div className="recap-key">Soumis</div>
          <div className="recap-val">{new Date().toLocaleString('fr-CA')}</div>
          <div className="recap-key">Patient</div>
          <div className="recap-val">{[data.patient?.prenom, data.patient?.nom].filter(Boolean).join(' ') || '—'}</div>
        </div>
      </div>
      <div style={{ marginTop: 28, display: 'flex', gap: 10, justifyContent: 'center' }}>
        <button className="btn btn-primary btn-lg" onClick={onNewReport}>
          <Icon.Plus /> Nouveau rapport
        </button>
      </div>
    </div>
  );
}

Object.assign(window, {
  StepDebut, StepLocalisation, StepEquipe, StepPatient, StepEvaluation,
  StepBlessures, StepSample, StepSoins, StepEvenement, StepTransport,
  StepRecap, StepSubmitted
});
