/* Diagnostic B — Restitution.
   Calcul des scores, attribution du profil, sélection des angles morts.
   Toute la logique est verbatim au §7, §8, §9 et §13 du cadrage.
*/

// ─────────────────────────────────────────────────────────────────
// SCORING
// ─────────────────────────────────────────────────────────────────
function scoreOf(question, answer) {
  if (answer == null) return 0;
  if (question.type === 'multi') {
    const arr = Array.isArray(answer) ? answer : [];
    // Si "Aucune…" est cochée (dernier index pour exclusiveLast), score = 0
    if (question.exclusiveLast && arr.includes(question.options.length - 1)) return 0;
    return Math.min(4, arr.length);
  }
  return Math.max(0, Math.min(4, answer));
}

// Normalise un total (max 4 par item) en /5
function normalize(total, count) {
  const max = count * 4;
  return max === 0 ? 0 : (total / max) * 5;
}

function computeScores(answers) {
  const subs = {};
  QUESTIONS.forEach(q => { subs[q.id] = scoreOf(q, answers[q.id]); });

  const byAxis = {};
  CHAPTERS.forEach(ch => {
    const qs = QUESTIONS.filter(q => q.chapter === ch.id);
    const total = qs.reduce((s, q) => s + subs[q.id], 0);
    byAxis[ch.id] = {
      raw: total,
      max: qs.length * 4,
      norm: normalize(total, qs.length),  // /5
    };
  });

  return { subs, byAxis };
}

function pickProfile(byAxis) {
  const I = byAxis.impacts.norm;
  const U = byAxis.usages.norm;
  const A = byAxis.actualite.norm;
  const all = [I, U, A];
  const maxV = Math.max(...all);
  const minV = Math.min(...all);

  // Architecte : 3 axes > 2.5
  if (all.every(v => v > 2.5)) return 'architecte';

  // Stratège : 2 axes > 2.5 et 1 axe entre 1.5 et 2.5
  const high = all.filter(v => v > 2.5).length;
  const mid = all.filter(v => v >= 1.5 && v <= 2.5).length;
  if (high === 2 && mid === 1) return 'stratege';

  // Dominantes : 1 axe > 2 ET écart > 1.0 avec les 2 autres
  const dom = (idx) => {
    const v = all[idx];
    if (v <= 2) return false;
    return all.every((o, j) => j === idx || (v - o) > 1.0);
  };
  // Bris d'égalité : Impacts > Usages > Actualité
  if (dom(0)) return 'lecteur';   // Impacts dominant
  if (dom(1)) return 'praticien'; // Usages dominant
  if (dom(2)) return 'veilleur';  // Actualité dominant

  // Observateur : 3 axes < 1.5
  if (all.every(v => v < 1.5)) return 'observateur';

  // Engagé : 3 axes entre 1.5 et 2.5
  if (all.every(v => v >= 1.5 && v <= 2.5)) return 'engage';

  // Fallback : Engagé (cas limites)
  return 'engage';
}

// Trie les sous-dimensions par score croissant, garde les 3 plus basses < 3
function pickAngles(subs) {
  return QUESTIONS
    .map(q => ({ q, score: subs[q.id] }))
    .filter(x => x.score < 3)
    .sort((a, b) => a.score - b.score)
    .slice(0, 3);
}

// Calcule la ligne "Vos forces"
function pickStrengths(subs) {
  const strong = QUESTIONS
    .map(q => ({ q, score: subs[q.id] }))
    .filter(x => x.score >= 3);

  if (strong.length >= 2) {
    return {
      mode: 'two',
      text: `Vous avez un socle solide sur ${strong[0].q.short.toLowerCase()} et ${strong[1].q.short.toLowerCase()}. On s'appuie dessus pour faire avancer le reste.`,
    };
  }
  if (strong.length === 1) {
    return {
      mode: 'one',
      text: `${strong[0].q.short} est votre point d'appui. On part de là.`,
    };
  }
  // aucun ≥ 3 : prendre la plus haute
  const top = [...QUESTIONS]
    .map(q => ({ q, score: subs[q.id] }))
    .sort((a, b) => b.score - a.score)[0];
  return {
    mode: 'none',
    text: `${top.q.short} est le terrain où vous êtes le plus avancé pour l'instant. On démarre par là.`,
  };
}

// Phrase ressenti contextuelle
function buildFeelingSentence(values) {
  // FEELING.options sont des objets { label, tone } → on extrait .label
  const sel = (values || [])
    .map(i => FEELING.options[i])
    .filter(Boolean)
    .map(o => (typeof o === 'string' ? o : o.label));
  if (sel.length === 0) return null;
  if (sel.length === 1) return `Vous abordez le sujet IA avec ${sel[0].toLowerCase()}.`;
  if (sel.length === 2) {
    const contrastes = [
      [0, 6], [0, 7], [2, 5], [2, 7], [1, 3], [1, 4],
    ];
    const isContrast = contrastes.some(([a, b]) =>
      (values[0] === a && values[1] === b) || (values[0] === b && values[1] === a));
    if (isContrast) {
      return `Votre ressenti combine ${sel[0].toLowerCase()} et ${sel[1].toLowerCase()}. Un contraste qu'on peut explorer en séance.`;
    }
    return `Vous vivez le sujet entre ${sel[0].toLowerCase()} et ${sel[1].toLowerCase()}.`;
  }
  return `Votre ressenti est multiple : ${sel.slice(0, 3).map(s => s.toLowerCase()).join(', ')}. On en reparle.`;
}

// ─────────────────────────────────────────────────────────────────
// Radar SVG (terracotta, sans chiffres) — animated draw-in + diamond vertices
// ─────────────────────────────────────────────────────────────────
function Radar({ byAxis, size = 360 }) {
  const values = [byAxis.impacts.norm, byAxis.usages.norm, byAxis.actualite.norm];
  const labels = ['Impacts', 'Usages', 'Actualité'];
  const padX = 90;
  const padY = 44;
  const W = size + padX * 2;
  const H = size + padY * 2;
  const cx = W / 2, cy = H / 2;
  const radius = size * 0.36;
  const axes = 3;

  const pt = (i, v) => {
    const a = (Math.PI * 2 * i) / axes - Math.PI / 2;
    const r = (v / 5) * radius;
    return [cx + Math.cos(a) * r, cy + Math.sin(a) * r];
  };

  const rings = [1, 2, 3, 4, 5].map(lvl => {
    const pts = Array.from({ length: axes }, (_, i) => pt(i, lvl).join(',')).join(' ');
    return <polygon key={lvl} className="ring" points={pts} />;
  });
  const lines = Array.from({ length: axes }, (_, i) => {
    const [x2, y2] = pt(i, 5);
    return <line key={i} className="axis-line" x1={cx} y1={cy} x2={x2} y2={y2} />;
  });
  const data = Array.from({ length: axes }, (_, i) => pt(i, values[i]).join(',')).join(' ');

  // Labels positionnés plus loin
  const labelEls = Array.from({ length: axes }, (_, i) => {
    const a = (Math.PI * 2 * i) / axes - Math.PI / 2;
    const lx = cx + Math.cos(a) * (radius + 36);
    const ly = cy + Math.sin(a) * (radius + 36);
    let anchor = 'middle';
    if (Math.cos(a) > 0.3) anchor = 'start';
    else if (Math.cos(a) < -0.3) anchor = 'end';
    return (
      <text key={i} className="axis-label" x={lx} y={ly} textAnchor={anchor} dominantBaseline="middle">
        {labels[i]}
      </text>
    );
  });

  // Diamond vertices (rotated square at each data point)
  const vertexEls = Array.from({ length: axes }, (_, i) => {
    const [px, py] = pt(i, values[i]);
    const s = 6;
    const delay = 1.3 + i * 0.12; // appears after polygon draw finishes
    return (
      <rect
        key={i}
        className="vertex-diamond"
        x={px - s} y={py - s}
        width={s * 2} height={s * 2}
        transform={`rotate(45 ${px} ${py})`}
        rx="0.8"
        style={{ animationDelay: delay + 's', transformOrigin: `${px}px ${py}px` }}
      />
    );
  });

  return (
    <svg viewBox={`0 0 ${W} ${H}`} className="db-radar" aria-label="Radar des trois axes"
         style={{ width: '100%', height: 'auto', maxWidth: 480, display: 'block', margin: '0 auto' }}>
      {rings}{lines}
      <polygon className="data-poly animated" points={data} />
      {vertexEls}
      {labelEls}
    </svg>
  );
}

// ─────────────────────────────────────────────────────────────────
// ÉCRAN — Restitution
// ─────────────────────────────────────────────────────────────────
function ResultsScreen({ answers, feeling, freeform, email, firstName, clientId }) {
  const { subs, byAxis } = computeScores(answers);
  const profileKey = pickProfile(byAxis);
  const profile = PROFILES[profileKey];
  const displayEmail = email || 'votre adresse';
  const pdfUrl = clientId ? '/api/pdf/' + encodeURIComponent(clientId) : null;

  const angles = pickAngles(subs);
  const strengths = pickStrengths(subs);
  const feelingSentence = buildFeelingSentence(feeling);
  const today = new Date().toLocaleDateString('fr-FR', { day: 'numeric', month: 'long', year: 'numeric' });

  // Regroupe les angles morts par axe
  const anglesByChapter = CHAPTERS.map(ch => {
    const inCh = angles.filter(a => a.q.chapter === ch.id);
    return { chapter: ch, items: inCh };
  });

  return (
    <>
      <Chrome showChips={false} />
      <div className="db-body db-fade" style={{ paddingBottom: 56 }}>
        <div className="db-narrow" style={{ maxWidth: 720 }}>
          {/* — Bloc 1 : En-tête — */}
          <div style={{ marginBottom: 36 }}>
            <div className="db-kicker" style={{ marginBottom: 16 }}>Diagnostic terminé</div>
            <h1 className="db-h1" style={{ fontSize: 44, marginBottom: 18 }}>Votre point de départ.</h1>
            <p className="db-body-text" style={{ marginBottom: 8 }}>
              On en reparle ensemble lors de notre prochaine séance.
            </p>
            <p className="db-body-text s">
              Vos résultats viennent d'être envoyés par email à {displayEmail}.
            </p>
            <div className="db-meta-row" style={{ marginTop: 16 }}>
              <span>Diagnostic du {today}</span>
            </div>
          </div>

          {/* — Première phrase d'accueil (Marie en JE) — */}
          <div className="db-marie-intro" style={{ marginBottom: 56 }}>
            <p className="db-body-text" style={{ fontFamily: "'Fraunces', Georgia, serif", fontWeight: 300, fontSize: 19, lineHeight: 1.55, fontStyle: 'italic', color: 'var(--db-ink)' }}>
              Ce que je vois dans vos réponses&nbsp;: trois axes regardés, des angles morts qui
              ressortent, des points d'appui sur lesquels avancer. Pas de note, pas de verdict,
              un point de départ.
            </p>
          </div>

          {/* — Bloc 2 : Votre carte (au-dessus, pleine largeur) — */}
          <div style={{ marginBottom: 56 }}>
            <div className="db-kicker muted" style={{ marginBottom: 22, textAlign: 'center' }}>Votre carte</div>
            <Radar byAxis={byAxis} size={360} />
          </div>

          {/* — Bloc 3 : Votre profil — */}
          <div style={{ marginBottom: 64 }}>
            <div className="db-kicker muted" style={{ marginBottom: 14 }}>Votre profil</div>
            <h2 className="db-profile-name">{profile.name}</h2>
            <hr className="db-rule" style={{ marginBottom: 24 }} />
            <p className="db-body-text" style={{ maxWidth: 620 }}>{profile.text}</p>
          </div>

          {/* — Bloc 4 : Ce que je creuserais en priorité — */}
          <div style={{ marginBottom: 56 }}>
            <div className="db-kicker" style={{ marginBottom: 22 }}>Ce que je creuserais en priorité</div>

            {angles.length === 0 ? (
              <p className="db-body-text">
                Aucune sous-dimension n'est sous le palier de vigilance. Le mentoring va
                travailler à monter le niveau d'exigence d'ensemble.
              </p>
            ) : (
              anglesByChapter.map(({ chapter, items }) => {
                if (items.length === 0) return null;
                return (
                  <div key={chapter.id} style={{ marginBottom: 36 }}>
                    <div className="db-chapter-tag" style={{ marginBottom: 22 }}>
                      <span className="num">{chapter.num}</span>
                      <span className="name">{chapter.name}</span>
                    </div>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
                      {items.map(({ q, score }) => {
                        const angle = ANGLES[q.id];
                        if (!angle) return null;
                        const txt = angle.levels[score] || angle.levels[0];
                        return (
                          <div key={q.id} className="db-angle">
                            <h3 className="db-h3 title">{angle.title}</h3>
                            <p className="db-body-text m" style={{ margin: 0 }}>{txt}</p>
                          </div>
                        );
                      })}
                    </div>
                  </div>
                );
              })
            )}
          </div>

          {/* — Bloc 5 : Vos points d'appui — */}
          <div style={{ marginBottom: 48 }}>
            <div className="db-kicker muted" style={{ marginBottom: 14 }}>Vos points d'appui</div>
            <p className="db-body-text" style={{ fontStyle: 'italic', fontFamily: "'Fraunces', Georgia, serif", fontWeight: 300, fontSize: 19, lineHeight: 1.45 }}>
              {strengths.text}
            </p>
          </div>

          {/* — Bloc 6 : Votre rapport au sujet · Bloc 7 : Votre note — */}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(240px, 1fr))', gap: 16, marginBottom: 56 }}>
            {feelingSentence && (
              <div className="db-card sage">
                <div className="db-kicker muted" style={{ marginBottom: 10 }}>Votre rapport au sujet</div>
                <p className="db-body-text m" style={{
                  fontStyle: 'italic', fontFamily: "'Fraunces', Georgia, serif",
                  fontWeight: 300, fontSize: 16.5, lineHeight: 1.5, margin: 0,
                }}>
                  {feelingSentence}
                </p>
              </div>
            )}
            {(freeform && freeform.trim()) && (
              <div className="db-card subtle">
                <div className="db-kicker muted" style={{ marginBottom: 10 }}>Votre note</div>
                <p className="db-body-text m" style={{ margin: 0, fontStyle: 'italic' }}>
                  « {freeform} »
                </p>
              </div>
            )}
          </div>

          {/* — Bloc 8 : On en reparle — */}
          <div style={{ borderTop: '1px solid var(--db-border)', paddingTop: 32 }}>
            <div className="db-kicker" style={{ marginBottom: 18 }}>On en reparle</div>
            <p className="db-body-text m" style={{ marginBottom: 14 }}>
              Ce diagnostic est un point de départ, pas un verdict. Il sert à structurer nos
              prochaines séances autour de ce qui compte vraiment pour vous.
            </p>
            <p className="db-body-text m" style={{ marginBottom: 24 }}>
              Vos résultats viennent d'être envoyés par email à {displayEmail}.
            </p>

            <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
              {pdfUrl ? (
                <a className="db-btn ghost" href={pdfUrl} target="_blank" rel="noopener">Télécharger en PDF</a>
              ) : (
                <button className="db-btn ghost" disabled>Télécharger en PDF</button>
              )}
            </div>
          </div>

          {/* — Bloc 9 : Mention RGPD bas de page — */}
          <p className="db-body-text s" style={{ color: 'var(--db-text-3)', marginTop: 56, fontStyle: 'italic', lineHeight: 1.55 }}>
            Vos résultats sont stockés sur les serveurs SEREL et accessibles via ce lien jusqu'à
            la fin de notre programme. Pour demander leur effacement à tout moment&nbsp;: <a href="mailto:marie@serel-ia.com" style={{ color: 'var(--db-text-2)', textDecoration: 'underline', textUnderlineOffset: 2, fontStyle: 'normal' }}>marie@serel-ia.com</a>.
          </p>
        </div>
      </div>
    </>
  );
}

Object.assign(window, {
  scoreOf, computeScores, pickProfile, pickAngles, pickStrengths, buildFeelingSentence,
  Radar, ResultsScreen,
});
