// sections-mid.jsx — Méthode (itinéraire en escalier) + Credos (bloc noir sticky)

/* ======================= Méthode / Timeline ======================= */
function Method() {
  const steps = [
    {
      n: '01', tag: 'Diagnostic', title: "L'Amorce", variant: 'peach',
      body: "On cartographie vos systèmes d'acquisition, de rétention et d'opération. On repère où ça fuit, où ça bloque, où il est rentable d'agir vite.",
      highlight: 'Audit gratuit',
    },
    {
      n: '02', tag: 'Construction', title: 'Le Câblage', variant: 'lilac',
      body: "On construit et on connecte : workflows, automations, intégrations, contenus. Les pièces éparses deviennent un système qui tourne.",
    },
    {
      n: '03', tag: 'Optimisation', title: "L'Accélération", variant: 'butter',
      body: "Le système tourne, on monte le régime. Tests, scoring, itérations. On optimise ce qui produit vraiment du résultat.",
    },
    {
      n: '04', tag: 'Transfert', title: 'Le Relais', variant: 'mint',
      body: 'On forme vos équipes, on documente tout, on vous passe le relais. Vous opérez seul, sans dépendance.',
    },
  ];

  const routeRef = useRef(null);
  const geoRef = useRef(null);
  const [geo, setGeo] = useState(null);

  React.useLayoutEffect(() => {
    const wrap = routeRef.current;
    if (!wrap) return;
    const measure = () => {
      const steps = Array.from(wrap.querySelectorAll('.mstep-step'));
      if (steps.length !== 4 || getComputedStyle(wrap).getPropertyValue('--stair').trim() !== '1') {
        geoRef.current = null;
        setGeo(null);
        return;
      }
      const w = wrap.getBoundingClientRect();
      const rects = steps.map(el => {
        const r = el.getBoundingClientRect();
        return { top: r.top - w.top, bottom: r.bottom - w.top, right: r.right - w.left };
      });
      const xs = rects.map(r => r.right + 12);
      const turns = rects.slice(1).map(r => r.top - 12);
      const srcY = rects[0].top - 36;
      const pts = [[xs[0], srcY]];
      turns.forEach((t, i) => { pts.push([xs[i], t]); pts.push([xs[i + 1], t]); });
      pts.push([xs[3], w.height + 48]);
      const segLen = pts.slice(1).map((p, k) => Math.abs(p[0] - pts[k][0]) + Math.abs(p[1] - pts[k][1]));
      const total = segLen.reduce((a, b) => a + b, 0);
      const bornes = rects.map((r, i) => {
        const cy = (r.top + r.bottom) / 2;
        const before = segLen.slice(0, 2 * i).reduce((a, b) => a + b, 0);
        return { x: xs[i], y: cy, at: (before + cy - pts[2 * i][1]) / total };
      });
      const next = {
        w: w.width, h: w.height, src: [xs[0], srcY], bornes,
        d: pts.map((p, k) => `${k ? 'L' : 'M'} ${p[0].toFixed(1)} ${p[1].toFixed(1)}`).join(' '),
      };
      geoRef.current = next;
      setGeo(next);
    };
    measure();
    const ro = new ResizeObserver(measure);
    ro.observe(wrap);
    if (document.fonts && document.fonts.ready) document.fonts.ready.then(measure);
    return () => ro.disconnect();
  }, []);

  return (
    <section id="methode" className="section section--accent-peach" style={{
      borderTop: '1px solid var(--chalk)',
      borderBottom: '1px solid var(--chalk)',
    }}>
      <div className="container">
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 32, flexWrap: 'wrap', marginBottom: 24 }}>
          <div>
            <span className="chip chip--paper reveal" style={{ marginBottom: 20 }}>
              <span className="chip__dot"></span>Méthode
            </span>
            <h2 className="display-serif reveal" style={{
              fontSize: 'clamp(36px, 5vw, 64px)', margin: '20px 0 0', maxWidth: 820,
            }}>
              Quatre étapes. <br />
              <em>Un système</em> complet.
            </h2>
          </div>
        </div>

        <div className="method-route" ref={routeRef}>
          <ol className="method-steps">
            {steps.map((s, i) => (
              <li key={s.n} className="mstep-step is-reached" style={{ '--k': i, zIndex: i + 1 }}>
                <div className="mstep-drift">
                  <article className={`mstep mstep--${s.variant}`}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                      <span className="mstep__num">{s.n}</span>
                      <span className="chip chip--paper chip--sm">{s.tag}</span>
                    </div>
                    <h3 className="mstep__title">{s.title}</h3>
                    <p className="mstep__body">{s.body}</p>
                    {s.highlight && <span className="mstep__highlight">{s.highlight}</span>}
                  </article>
                </div>
              </li>
            ))}
          </ol>

          {geo && (
            <svg className="method-path" width={geo.w} height={geo.h} viewBox={`0 0 ${geo.w} ${geo.h}`} aria-hidden="true">
              <path className="method-path__ghost" d={geo.d} />
              <path className="method-path__ink" d={geo.d} pathLength="1" />
              <circle className="method-source" cx={geo.src[0]} cy={geo.src[1]} r="4" />
              {geo.bornes.map((b, i) => (
                <circle key={i} className="method-borne is-on" cx={b.x} cy={b.y} r="5.5" />
              ))}
            </svg>
          )}

          <p className="method-closing">Au bout du chemin, le système est à vous.</p>
        </div>
      </div>
    </section>
  );
}

/* ======================= Crédos (sticky, bloc noir) ======================= */
function Credos() {
  const credos = [
    { text: <><span className="hl">Business first</span>. On part du <em>process</em>, jamais de l'outil.</> },
    { text: <>Pas d'automatisation sans <span className="hl">processus éprouvé</span> d'abord.</> },
    { text: <>Pas d'IA quand elle n'apporte rien de <span className="hl">mesurable</span>.</> },
    { text: <>On co-construit, transfère et forme. <br/>On ne crée <span className="hl">pas de dépendance</span>.</> },
  ];
  return (
    <section id="credos" className="on-dark" style={{
      padding: 'clamp(96px, 12vw, 160px) 0',
    }}>
      <div className="container">
        <div className="credos-layout" style={{
          display: 'grid',
          gridTemplateColumns: '1fr 1.4fr',
          gap: 80,
          alignItems: 'flex-start',
        }}>
          {/* Sticky left column */}
          <div style={{
            position: 'sticky',
            top: 120,
          }}>
            <span className="chip chip--lilac chip--on-dark reveal" style={{ marginBottom: 28 }}>
              <span className="chip__dot"></span>Manifeste
            </span>
            <h2 className="display-serif reveal" style={{
              fontSize: 'clamp(40px, 5vw, 72px)',
              color: 'var(--paper)',
              margin: '0 0 32px',
            }}>
              Ce en quoi <br/>
              <em style={{ color: 'var(--lilac)' }}>on croit</em>.
            </h2>
            <p className="reveal" style={{
              fontFamily: 'var(--font-sans)',
              fontSize: 16, lineHeight: 1.6,
              color: 'var(--dust)',
              maxWidth: 380, margin: 0,
            }}>
              Quatre convictions que je ne négocie pas. Elles filtrent les missions que j'accepte et celles que je refuse.
            </p>
          </div>

          {/* Right list */}
          <div className="reveal-stagger">
            {credos.map((c, i) => (
              <div key={i} className="credo-item">
                <span className="credo-item__n">{String(i + 1).padStart(2, '0')}</span>
                <p className="credo-item__text">{c.text}</p>
              </div>
            ))}


          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Method, Credos });
