/* =====================================================================
 * Fiche de bilan opérationnelle (affichage écran + impression A4).
 * ===================================================================== */

function FicheSection({ title, letter, children, className }) {
  return (
    <section className={cx('print-avoid-break min-w-0 rounded-lg border border-slate-300', className)}>
      <h3 className="flex items-center gap-2 border-b border-slate-300 bg-slate-100 px-3 py-1.5 text-xs font-bold uppercase tracking-wide text-slate-700">
        {letter && <span className="flex h-5 w-5 items-center justify-center rounded bg-slate-800 text-[11px] text-white">{letter}</span>}
        {title}
      </h3>
      <div className="px-3 py-2">{children}</div>
    </section>
  );
}

function FicheRow({ label, value, highlight }) {
  return (
    <div className="flex gap-2 py-0.5 text-[13px] leading-snug">
      <span className="w-28 shrink-0 text-slate-500 sm:w-40">{label}</span>
      <span className={cx('min-w-0 break-words font-medium text-slate-900', highlight && 'font-bold text-red-700')}>{display(value)}</span>
    </div>
  );
}

function BilanFiche({ bilan, settings }) {
  const b = bilan;
  const c = b.circ || {};
  const v = b.vital || {};
  const t = b.transmission || {};
  const alerts = bilanAlerts(b);
  const gcs = glasgowScore(v.d);
  const touchees = bilanZonesTouchees(b);
  const tone = (key, val) => ['danger', 'warning'].includes(vitalTone(key, val));
  const yn = (val) => (val === 'oui' ? 'Oui' : val === 'non' ? 'Non' : '—');
  const surveillance = getIn(b, 'gestes.surveillance') || [];

  return (
    <article className="print-sheet mx-auto max-w-[900px] bg-white p-2 text-slate-900 sm:p-6">
      {/* En-tête */}
      <header className="mb-4 flex flex-col-reverse gap-2 border-b-4 border-red-600 pb-3 sm:flex-row sm:items-start sm:justify-between sm:gap-4">
        <div className="min-w-0">
          <p className="text-xs font-semibold uppercase tracking-widest text-red-600">
            {(settings && settings.departement) || 'SDIS'} — {(settings && settings.centre) || 'Centre de Secours'}
          </p>
          <h1 className="text-xl font-black uppercase sm:text-2xl">Fiche bilan secours à personne</h1>
          <p className="text-sm text-slate-600">
            {c.engin || '—'} · Intervention n° {c.numInter || '—'} · {fmtDateTime(c.dateHeure)}
          </p>
        </div>
        <div className="sm:text-right">
          <p className="whitespace-nowrap font-mono text-lg font-bold">{b.numero}</p>
          <p className="text-xs text-slate-500">{(BILAN_STATUS[b.status] || BILAN_STATUS.brouillon).label}</p>
          {b.auteurNom && <p className="text-xs text-slate-500">Rédacteur : {b.auteurNom}</p>}
        </div>
      </header>

      {/* Alertes */}
      {alerts.length > 0 && (
        <div className="print-avoid-break mb-4 rounded-lg border-2 border-red-500 bg-red-50 px-3 py-2">
          <p className="mb-1 text-xs font-bold uppercase text-red-700">Points d'alerte</p>
          <ul className="grid gap-x-4 text-[13px] sm:grid-cols-2">
            {alerts.map((a, i) => (
              <li key={i} className={a.level === 'danger' ? 'font-semibold text-red-700' : 'text-amber-800'}>
                • {a.text}
              </li>
            ))}
          </ul>
        </div>
      )}

      <div className="grid gap-3 sm:grid-cols-2">
        <FicheSection title="Victime">
          <FicheRow label="Identité" value={[c.victime && c.victime.nom && c.victime.nom.toUpperCase(), c.victime && c.victime.prenom].filter(Boolean).join(' ')} />
          <FicheRow label="Sexe / âge" value={[c.victime && c.victime.sexe, c.victime && c.victime.age ? `${c.victime.age} ans` : ''].filter(Boolean).join(' — ')} />
          <FicheRow label="Date de naissance" value={c.victime && c.victime.naissance ? fmtDate(c.victime.naissance) : ''} />
          <FicheRow label="Nombre de victimes" value={c.nbVictimes} />
        </FicheSection>

        <FicheSection title="Circonstances">
          <FicheRow label="Adresse" value={[c.adresse, c.commune].filter(Boolean).join(', ')} />
          <FicheRow label="Motif" value={[c.motif, c.motifDetail].filter(Boolean).join(' — ')} />
          <FicheRow label="Équipage" value={c.equipage} />
          <FicheRow label="Sécurité zone" value={(SECURITE_ZONE.find((s) => s.value === c.securite) || {}).label} highlight={c.securite === 'danger'} />
          <FicheRow label="Risques" value={c.risques} />
          {c.risquesDetail && <FicheRow label="Mesures" value={c.risquesDetail} />}
        </FicheSection>

        <FicheSection title="Situation" className="sm:col-span-2">
          <FicheRow label="Mécanisme" value={[(MECANISMES.find((m) => m.value === c.mecanisme) || {}).label, c.mecanismeDetail].filter(Boolean).join(' — ')} />
          <FicheRow label="Environnement" value={[...(c.environnement || []), c.environnementDetail].filter(Boolean)} />
          <FicheRow label="Renforts demandés" value={[...(c.renforts || []), c.renfortsDetail].filter(Boolean)} />
        </FicheSection>

        <FicheSection title="Hémorragie" letter="X">
          <FicheRow label="Hémorragie massive" value={yn(v.x && v.x.hemorragie)} highlight={v.x && v.x.hemorragie === 'oui'} />
          {v.x && v.x.hemorragie === 'oui' && (
            <Fragment>
              <FicheRow label="Localisation" value={v.x.localisation} />
              <FicheRow label="Gestes" value={v.x.gestes} />
              <FicheRow label="Heure garrot" value={v.x.garrotHeure} highlight />
            </Fragment>
          )}
        </FicheSection>

        <FicheSection title="Voies aériennes" letter="A">
          <FicheRow label="État" value={(VA_ETAT.find((x) => x.value === (v.a && v.a.etat)) || {}).label} highlight={v.a && v.a.etat === 'obstruees'} />
          {v.a && v.a.etat === 'obstruees' && <FicheRow label="Cause" value={v.a.causes} />}
          <FicheRow label="Risque non-maintien" value={yn(v.a && v.a.risque)} />
          <FicheRow label="Collier cervical" value={yn(v.a && v.a.collier)} />
        </FicheSection>

        <FicheSection title="Ventilation" letter="B">
          <FicheRow label="FR" value={v.b && v.b.fr ? `${v.b.fr} /min` : ''} highlight={tone('fr', v.b && v.b.fr)} />
          <FicheRow label="SpO2" value={v.b && v.b.spo2 ? `${v.b.spo2} %` : ''} highlight={tone('spo2', v.b && v.b.spo2)} />
          <FicheRow label="Qualité" value={v.b && v.b.qualite} />
          <FicheRow
            label="Oxygène"
            value={v.b && v.b.o2 === 'oui' ? `${v.b.o2Debit || '?'} L/min — ${v.b.o2Dispositif || 'dispositif ?'}` : yn(v.b && v.b.o2)}
          />
        </FicheSection>

        <FicheSection title="Circulation" letter="C">
          <FicheRow label="FC" value={v.c && v.c.fc ? `${v.c.fc} bpm` : ''} highlight={tone('fc', v.c && v.c.fc)} />
          <FicheRow label="Pouls" value={v.c && v.c.pouls} highlight={v.c && v.c.pouls === 'Absent'} />
          <FicheRow label="TA" value={v.c && (v.c.tas || v.c.tad) ? `${v.c.tas || '?'} / ${v.c.tad || '?'} mmHg` : ''} highlight={tone('tas', v.c && v.c.tas)} />
          <FicheRow label="Signes périph." value={v.c && v.c.signes} />
          <FicheRow label="TRC" value={v.c && v.c.trc} highlight={v.c && v.c.trc === '> 2 s'} />
        </FicheSection>

        <FicheSection title="Neurologique" letter="D">
          <FicheRow label="AVPU" value={(AVPU.find((x) => x.value === (v.d && v.d.avpu)) || {}).label} />
          <FicheRow label="Glasgow" value={gcs !== null ? `${gcs}/15 (E${v.d.gE} V${v.d.gV} M${v.d.gM})` : ''} highlight={gcs !== null && gcs < 15} />
          <FicheRow label="PC initiale" value={v.d && v.d.pci === 'oui' ? `Oui${v.d.pciDuree ? ` (${v.d.pciDuree})` : ''}` : yn(v.d && v.d.pci)} />
          <FicheRow label="Pupilles" value={v.d && v.d.pupilles} />
          <FicheRow label="Glycémie" value={v.d && v.d.glycemie ? `${v.d.glycemie} ${v.d.glyUnite}` : ''} highlight={tone('glyGL', glycemieGL(v.d))} />
          <FicheRow label="Motricité / sensib." value={[...((v.d && v.d.neuro) || []), v.d && v.d.deficitCote ? `côté ${v.d.deficitCote}` : ''].filter(Boolean)} />
        </FicheSection>

        <FicheSection title="Exposition / douleur" letter="E">
          <FicheRow label="Température" value={v.e && v.e.temp ? `${v.e.temp} °C` : ''} highlight={tone('temp', v.e && v.e.temp)} />
          <FicheRow label="Douleur" value={v.e && v.e.douleur !== '' && v.e.douleur !== undefined ? `${v.e.echelle} ${v.e.douleur}/10` : ''} highlight={tone('douleur', v.e && v.e.douleur)} />
          <FicheRow label="Localisation" value={v.e && v.e.douleurLoc} />
        </FicheSection>

        <FicheSection title="Bilan lésionnel">
          {touchees.length === 0 ? (
            <p className="text-[13px] text-slate-500">Aucune lésion relevée.</p>
          ) : (
            touchees.map(([id, z]) => <FicheRow key={id} label={zoneLabel(id)} value={[...(z.types || []), z.details].filter(Boolean)} />)
          )}
        </FicheSection>

        <FicheSection title="Interrogatoire SAMPLE" className="sm:col-span-2">
          <div className="grid gap-x-6 sm:grid-cols-2">
            {SAMPLE.map((s) => (
              <FicheRow key={s.key} label={`${s.letter} — ${s.label}`} value={getIn(b, `lesions.sample.${s.key}`)} />
            ))}
          </div>
        </FicheSection>

        <FicheSection title="Gestes effectués" className="sm:col-span-2">
          <FicheRow label="Actes" value={getIn(b, 'gestes.actes')} />
          {getIn(b, 'gestes.daeChocs') && <FicheRow label="Chocs DAE" value={getIn(b, 'gestes.daeChocs')} />}
          {getIn(b, 'gestes.autres') && <FicheRow label="Précisions" value={getIn(b, 'gestes.autres')} />}
          {surveillance.length > 0 && (
            <div className="scrollbar-thin mt-2 overflow-x-auto">
            <table className="w-full border-collapse text-[12px]">
              <thead>
                <tr className="bg-slate-100">
                  {SURVEILLANCE_COLS.map((col) => (
                    <th key={col.key} className="border border-slate-300 px-1.5 py-1 text-left">
                      {col.label}
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {surveillance.map((r) => (
                  <tr key={r.id}>
                    {SURVEILLANCE_COLS.map((col) => (
                      <td key={col.key} className="border border-slate-300 px-1.5 py-1">
                        {display(r[col.key], '')}
                      </td>
                    ))}
                  </tr>
                ))}
              </tbody>
            </table>
            </div>
          )}
        </FicheSection>

        <FicheSection title="Transmission & transport" className="sm:col-span-2">
          <div className="grid gap-x-6 sm:grid-cols-2">
            <div>
              <FicheRow label="Appel SAMU (15)" value={t.heureAppel} />
              <FicheRow label="Médecin régulateur" value={[t.medecin, t.matricule].filter(Boolean).join(' — ')} />
              <FicheRow label="Avis / consignes" value={t.avis} />
            </div>
            <div>
              <FicheRow label="Décision" value={t.decision ? decisionLabel(t.decision) : ''} highlight={t.decision === 'smur'} />
              <FicheRow label="Destination" value={[t.destination, t.service].filter(Boolean).join(' — ')} />
              <FicheRow label="Départ / arrivée" value={t.heureDepart || t.heureArrivee ? `${t.heureDepart || '?'} → ${t.heureArrivee || '?'}` : ''} />
            </div>
          </div>
          {t.observations && <FicheRow label="Observations" value={t.observations} />}
        </FicheSection>
      </div>

      <footer className="mt-6 grid grid-cols-2 gap-6 text-[12px] text-slate-500">
        <div className="h-16 rounded border border-dashed border-slate-300 p-2">Signature</div>
        <div className="h-16 rounded border border-dashed border-slate-300 p-2">Signature réception (établissement)</div>
      </footer>
      <p className="mt-3 text-center text-[10px] text-slate-400">
        Document généré le {fmtDateTime(new Date())} — SAP Manager · Données confidentielles (secret médical)
      </p>
    </article>
  );
}
