// Vertical before/after slider — drag the handle up/down to reveal the same
// model before (everyday outfit) and after (the new look, essayé virtuellement).
function BeforeAfter() {
  const [pos, setPos] = React.useState(6); // % from top revealed as "après"
  const wrapRef = React.useRef(null);
  const dragging = React.useRef(false);
  const introDone = React.useRef(false);

  // Intro sweep on load: top → bottom → middle, then hand control to the user.
  React.useEffect(() => {
    let raf;
    const start = performance.now();
    const seq = [
      {from: 6, to: 94, t0: 400, dur: 900},   // descend to bottom
      {from: 94, to: 50, t0: 1400, dur: 700}, // back to middle
    ];
    const ease = (x) => 1 - Math.pow(1 - x, 3);
    const tick = (now) => {
      const el = now - start;
      let val = null;
      for (const s of seq) {
        if (el >= s.t0 && el <= s.t0 + s.dur) {
          val = s.from + (s.to - s.from) * ease((el - s.t0) / s.dur);
        } else if (el > s.t0 + s.dur) {
          val = s.to;
        }
      }
      if (val !== null) setPos(val);
      if (el < 2100) {
        raf = requestAnimationFrame(tick);
      } else {
        setPos(50);
        introDone.current = true;
      }
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);

  const update = React.useCallback((clientY) => {
    const el = wrapRef.current;
    if (!el) return;
    const r = el.getBoundingClientRect();
    let p = ((clientY - r.top) / r.height) * 100;
    p = Math.max(6, Math.min(94, p));
    setPos(p);
  }, []);

  React.useEffect(() => {
    const move = (e) => {
      if (!dragging.current) return;
      const y = e.touches ? e.touches[0].clientY : e.clientY;
      update(y);
    };
    const up = () => {dragging.current = false;};
    window.addEventListener('mousemove', move);
    window.addEventListener('mouseup', up);
    window.addEventListener('touchmove', move, {passive: false});
    window.addEventListener('touchend', up);
    return () => {
      window.removeEventListener('mousemove', move);
      window.removeEventListener('mouseup', up);
      window.removeEventListener('touchmove', move);
      window.removeEventListener('touchend', up);
    };
  }, [update]);

  const start = (e) => {
    introDone.current = true;
    dragging.current = true;
    const y = e.touches ? e.touches[0].clientY : e.clientY;
    update(y);
  };

  return (
    <div
      className="ba"
      ref={wrapRef}
      onMouseDown={start}
      onTouchStart={start}>
      {/* before (full, underneath) */}
      <img className="ba-img" src={window.R('heroBefore','./image-iphone-photo-user-v2-mrxt8a9x-4jk2.png')} alt="Avant l'essayage" draggable="false" />
      {/* after (clipped from top down to the handle) */}
      <div className="ba-after" style={{clipPath: `inset(0 0 ${100 - pos}% 0)`}}>
        <img className="ba-img" src={window.R('heroAfter','./image-photo-vto-v2-mrxt7x0b-3ymr.png')} alt="Essayage virtuel Myrrae" draggable="false" />
      </div>

      <div className="ba-handle" style={{top: `${pos}%`}}>
        <div className="ba-line" />
        <div className="ba-knob">
          <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
            <path d="M11 4l-3 3m3-3l3 3M11 18l-3-3m3 3l3-3" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
        </div>
      </div>
    </div>);

}

// Hero — split: AI stylist chat (left card) + virtual try-on result (right card)
function Hero() {
  // Chat appears progressively. Start with the user msg already there;
  // the bot's typing indicator + reply animate in shortly after mount.
  const [step, setStep] = React.useState(1);
  React.useEffect(() => {
    const t1 = setTimeout(() => setStep(2), 900);
    const t2 = setTimeout(() => setStep(3), 1900);
    return () => {clearTimeout(t1);clearTimeout(t2);};
  }, []);

  return (
    <section className="hero">
      <div className="stripe" />
      <div className="container hero-grid">
        <div className="hero-copy">
          <div className="hero-eyebrow">APP MODE · IOS & ANDROID</div>
          <h1>
            Essaie <em>n'importe</em>
            <br />
            <em>quel vêtement</em>
            <br />
            avant de l'acheter.
          </h1>
          <p className="lede">
            Myrrae est l'<strong>application</strong> qui aide tous les acheteurs mode en ligne à décider en confiance&nbsp;: <strong>essayage virtuel ultra-réaliste</strong> et <strong>styliste IA personnel</strong>.
            <br />
            Le bon vêtement, de la bonne marque, sur <em>toi</em>.
          </p>
          <div className="cta-row">
            <a href="#telecharger" className="cta-primary">
              Télécharger l'app
              <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
                <path d="M3 7h8m0 0L7 3m4 4l-4 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </a>
          </div>

          <div className="stats">
            <div className="stat">
              <div className="num">+10</div>
              <div className="lbl">Marques partenaires</div>
            </div>
            <div className="stat">
              <div className="num">−68%</div>
              <div className="lbl">de retours</div>
            </div>
            <div className="stat">
              <div className="num">4,9</div>
              <div className="lbl">App Store</div>
            </div>
          </div>
        </div>

        <div className="hero-visual">
          {/* Try-on result card (background, larger) */}
          <div className="hero-card try-on">
            <BeforeAfter />
          </div>

          {/* AI stylist chat card (foreground, overlapping left) */}
          <div className="hero-card chat">
            <div className="chat-head">
              <div className="avatar">M</div>
              <div className="name">
                Myrrae
                <span className="sub">Ton styliste IA</span>
              </div>
              <div className="pulse" />
            </div>

            <div className="msg user">
              Donne-moi une idée de robe d'été rouge à fleurs à moins de 100&nbsp;€ ?
            </div>

            {step >= 1 &&
            <div className="msg typing" key="typing"><span></span><span></span><span></span></div>
            }

            {step >= 2 &&
            <div className="msg bot" key="rec">
                Voici une robe cache-cœur midi rouge à moins de 100&nbsp;€,
                idéale pour cet été&nbsp;:
                <div className="product-mini">
                  <img className="sw" src={window.R('roseSwatch','./robe-rouge-mrxsdrkr-wo8z.png')} alt="Robe cache-cœur midi rouge" />
                  <div className="info">
                    <div className="title">Robe cache-cœur midi rouge</div>
                    <div className="meta">Zara · 79,90 €</div>
                  </div>
                </div>
              </div>
            }
          </div>
        </div>
      </div>
    </section>);

}

window.Hero = Hero;