/* global React, Eyebrow, Reveal, PhotoBlock, PinkCircle, Mark, CTABanner, ParallaxCTASection */
// Page 3 — CHI SIAMO

/* ── ChiSiamoHero — scroll-expand "hijack" (21st.dev style)
   Wheel/touch input alimenta un targetRef. Un loop RAF interpola
   currentRef → targetRef con easing esponenziale (~0.12 / frame) e
   scrive direttamente width/height/opacity via DOM refs: no React
   re-render per frame, motion sempre fluida indipendentemente dal
   rate degli eventi scroll. Scroll bloccato finché expanded=true. */
function ChiSiamoHero() {
  const [vw, setVw] = React.useState(typeof window !== 'undefined' ? window.innerWidth : 1024);
  const [vh, setVh] = React.useState(typeof window !== 'undefined' ? window.innerHeight : 800);

  const targetRef = React.useRef(0);    // progress target (input scroll)
  const currentRef = React.useRef(0);   // progress mostrato (lerp)
  const wrapperRef = React.useRef(null);
  const overlayRef = React.useRef(null);
  const rafRef = React.useRef(0);
  // expandedRef è SOLO un ref (no React state) → flip sincrono dentro
  // gli handler, niente race con useEffect/re-render
  const expandedRef = React.useRef(false);

  // Reset + viewport tracking
  React.useEffect(() => {
    targetRef.current = 0;
    currentRef.current = 0;
    expandedRef.current = false;
    window.scrollTo(0, 0);
    const onResize = () => { setVw(window.innerWidth); setVh(window.innerHeight); };
    onResize();
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, []);

  // RAF lerp + DOM update
  React.useEffect(() => {
    const isMobile = vw < 768;
    const startW = isMobile ? 240 : 320;
    const startH = isMobile ? 320 : 420;
    const endW = isMobile ? Math.min(vw - 24, 720) : Math.min(vw - 60, 1280);
    // Mobile: forziamo 4:3 (landscape) all'espansione max per non tagliare i volti
    const endH = isMobile
      ? Math.min(endW * 3 / 4, vh - 300)
      : Math.min(vh - 300, 720);

    const applyDOM = (p) => {
      const w = wrapperRef.current;
      const o = overlayRef.current;
      if (w) {
        w.style.width = `${(startW + p * (endW - startW)).toFixed(1)}px`;
        w.style.height = `${(startH + p * (endH - startH)).toFixed(1)}px`;
      }
      if (o) {
        o.style.opacity = (0.45 - p * 0.37).toFixed(4);
      }
    };

    const tick = () => {
      const t = targetRef.current;
      const c = currentRef.current;
      const diff = t - c;
      if (Math.abs(diff) > 0.0008) {
        // Lerp asimmetrico: shrink (target < current) leggermente più rapido
        // così l'uscita non sembra "lazy" rispetto all'espansione
        const k = diff > 0 ? 0.12 : 0.18;
        currentRef.current = c + diff * k;
      } else {
        currentRef.current = t;
      }
      applyDOM(currentRef.current);

      // Auto-promozione: appena target=1 e visual quasi al limite → expand
      // + riattiva Lenis perché ora la pagina deve scrollare normalmente
      if (t >= 1 && currentRef.current > 0.985 && !expandedRef.current) {
        expandedRef.current = true;
        if (window.__lenis) window.__lenis.start();
      }

      rafRef.current = requestAnimationFrame(tick);
    };
    applyDOM(currentRef.current);
    rafRef.current = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(rafRef.current);
  }, [vw, vh]);

  // Input handlers — flag SINCRONO, niente useEffect-sync (no race)
  React.useEffect(() => {
    let touchStartY = 0;
    const WHEEL_K = 0.0010;
    const TOUCH_DOWN_K = 0.007;
    const TOUCH_UP_K = 0.005;

    const handleWheel = (e) => {
      // Caso 1: image espansa, utente al top, scroll-up → riapri il lock E
      // processa lo stesso evento per iniziare lo shrink (niente eventi persi)
      if (expandedRef.current && e.deltaY < 0 && window.scrollY <= 5) {
        expandedRef.current = false;  // sync, no setState
        if (window.__lenis) window.__lenis.stop();
        e.preventDefault();
        const delta = e.deltaY * WHEEL_K;
        targetRef.current = Math.min(Math.max(targetRef.current + delta, 0), 1);
        return;
      }
      // Caso 2: lock attivo → wheel guida il target
      if (!expandedRef.current) {
        e.preventDefault();
        const delta = e.deltaY * WHEEL_K;
        targetRef.current = Math.min(Math.max(targetRef.current + delta, 0), 1);
      }
    };
    const handleTouchStart = (e) => { touchStartY = e.touches[0].clientY; };
    const handleTouchMove = (e) => {
      if (!touchStartY) return;
      const touchY = e.touches[0].clientY;
      const deltaY = touchStartY - touchY;
      if (expandedRef.current && deltaY < -20 && window.scrollY <= 5) {
        expandedRef.current = false;
        if (window.__lenis) window.__lenis.stop();
        e.preventDefault();
        const delta = deltaY * TOUCH_DOWN_K;
        targetRef.current = Math.min(Math.max(targetRef.current + delta, 0), 1);
        touchStartY = touchY;
        return;
      }
      if (!expandedRef.current) {
        e.preventDefault();
        const factor = deltaY < 0 ? TOUCH_DOWN_K : TOUCH_UP_K;
        const delta = deltaY * factor;
        targetRef.current = Math.min(Math.max(targetRef.current + delta, 0), 1);
        touchStartY = touchY;
      }
    };
    const handleTouchEnd = () => { touchStartY = 0; };
    const handleScroll = () => { if (!expandedRef.current) window.scrollTo(0, 0); };

    window.addEventListener('wheel', handleWheel, { passive: false });
    window.addEventListener('touchstart', handleTouchStart, { passive: false });
    window.addEventListener('touchmove', handleTouchMove, { passive: false });
    window.addEventListener('touchend', handleTouchEnd);
    window.addEventListener('scroll', handleScroll);
    return () => {
      window.removeEventListener('wheel', handleWheel);
      window.removeEventListener('touchstart', handleTouchStart);
      window.removeEventListener('touchmove', handleTouchMove);
      window.removeEventListener('touchend', handleTouchEnd);
      window.removeEventListener('scroll', handleScroll);
    };
  }, []);

  return (
    <section className="section-hero" style={{
      background: 'var(--color-surface-pure)',
      minHeight: '100dvh',
      padding: '110px 30px 40px',
      display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'flex-start',
      gap: 32,
      overflow: 'hidden',
    }}>
      <div style={{ maxWidth: 920, textAlign: 'center' }}>
        <Eyebrow style={{ marginBottom: 14 }}>Chi ti seguirà</Eyebrow>
        <h1 className="anim-char-reveal" style={{
          fontFamily: 'Fraunces, serif', fontWeight: 600,
          fontSize: 'clamp(40px, 4.8vw, 60px)', lineHeight: 1.05,
          letterSpacing: '-0.02em', color: 'var(--color-text-primary)',
          margin: 0, textWrap: 'balance',
        }}>Un team di <em style={{ fontStyle: 'italic', color: 'var(--color-primary)' }}>professionisti</em> dedicato a te</h1>
        <p style={{
          fontFamily: 'Inter, sans-serif', fontSize: 17, lineHeight: 1.55,
          color: 'var(--color-text-secondary)', margin: '14px auto 0', maxWidth: 580,
          textWrap: 'balance',
        }}>Persone vere, con anni di esperienza, che conoscono la tua storia e i tuoi obiettivi.</p>
      </div>

      {/* Expanding image — width/height aggiornate via DOM refs in RAF loop */}
      <div ref={wrapperRef} style={{
        position: 'relative',
        maxWidth: '94vw',
        overflow: 'hidden',
        borderRadius: 14,
        boxShadow: '0 32px 80px rgba(26,26,26,0.22)',
        willChange: 'width, height',
      }}>
        <img
          src="assets/foto/team-completo.webp"
          alt="Team completo Progetto Forma — Ferrara"
          loading="eager"
          style={{
            width: '100%', height: '100%',
            objectFit: 'cover', objectPosition: 'center',
            display: 'block',
          }}
        />
        <div ref={overlayRef} aria-hidden="true" style={{
          position: 'absolute', inset: 0,
          background: '#000',
          pointerEvents: 'none',
          willChange: 'opacity',
        }} />
      </div>
    </section>
  );
}

function TrainerCards() {
  const trainers = [
    {
      photo: 'assets/foto/marco.webp',
      name: 'Marco Gabrielli',
      tagline: 'Il tuo punto di riferimento',
      body: 'Marco è la persona che conosci dal primo giorno e che ti accompagna fino all\u2019ultimo. Conosce la tua storia, i tuoi obiettivi e i tuoi giorni difficili. Monitora i tuoi progressi e aggiusta il percorso quando serve.',
      credentials: ['Laureato in scienze motorie e in osteopatia', '8 anni nel mondo del fitness'],
    },
    {
      photo: 'assets/foto/francesco.webp',
      name: 'Francesco Borghesi',
      tagline: 'Ti senti a casa dal primo giorno',
      body: 'Francesco è la persona che trovi in sala ogni sessione. Ti spiega ogni movimento con pazienza, adatta la seduta se hai un giorno storto e non ti fa mai sentire in difetto. Quello che le palestre commerciali non ti danno — un ambiente tranquillo dove ti senti protetta — con lui lo hai da subito.',
      credentials: ['Istruttore di sala', 'Laureato in scienze motorie'],
    },
    {
      photo: 'assets/foto/davide.webp',
      name: 'Davide Filippini',
      tagline: 'La nutrizione costruita sulla tua vita',
      body: 'Davide è il motivo per cui il tuo piano alimentare funzionerà. Ha due competenze in una sola persona. Per questo costruisce il tuo piano alimentare sapendo esattamente come ti alleni e di cosa ha bisogno il tuo corpo.',
      credentials: ['Biologo Nutrizionista con Laurea Magistrale', 'Personal trainer certificato, laureato in scienze motorie'],
    },
  ];
  return (
    <section className="trainers-section bg-radial" style={{ padding: '80px 30px' }}>
      <div style={{ maxWidth: 1370, margin: '0 auto' }}>
        <div className="trainer-grid" style={{
          display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 28,
        }}>
          {trainers.map((t, i) => (
            <Reveal key={i} delay={i * 100}>
              <TrainerCard {...t} />
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

function TrainerCard({ photo, name, tagline, body, credentials }) {
  return (
    <article style={{ display: 'flex', flexDirection: 'column', gap: 22 }}>
      {/* Image card with overlay */}
      <div className="anim-mask-wipe" style={{
        position: 'relative', borderRadius: 12, overflow: 'hidden',
        aspectRatio: '3 / 4', boxShadow: 'var(--shadow-md)',
      }}>
        <img
          className="anim-mask-wipe"
          src={photo}
          alt={name}
          loading="lazy"
          style={{
            position: 'absolute', inset: 0,
            width: '100%', height: '100%',
            objectFit: 'cover', objectPosition: 'center',
            display: 'block',
          }}
        />
        {/* Gradient overlay for text legibility */}
        <div style={{
          position: 'absolute', inset: 0,
          background: 'linear-gradient(to bottom, rgba(26,26,26,0) 40%, rgba(26,26,26,0.65) 100%)',
        }} />
        {/* Overlay text */}
        <div style={{
          position: 'absolute', left: 0, right: 0, bottom: 0,
          padding: '24px 26px',
          color: 'var(--color-background)',
        }}>
          <div style={{
            fontFamily: 'Fraunces, serif', fontStyle: 'italic', fontWeight: 400,
            fontSize: 14.5, lineHeight: 1.4,
            color: 'var(--color-accent-pink)',
            marginBottom: 6,
          }}>{tagline}</div>
          <h3 className="anim-char-reveal" style={{
            fontFamily: 'Fraunces, serif', fontWeight: 600,
            fontSize: 28, lineHeight: 1.1, letterSpacing: '-0.01em',
            color: 'var(--color-background)', margin: 0,
          }}>{name}</h3>
        </div>
      </div>

      {/* Body */}
      <p style={{
        fontFamily: 'Inter, sans-serif', fontSize: 15, lineHeight: 1.7,
        color: 'var(--color-text-secondary)', margin: 0,
      }}>{body}</p>

      {/* Credentials bullets */}
      <ul style={{
        listStyle: 'none', margin: 0, padding: '16px 0 0',
        borderTop: '1px solid var(--color-border)',
        display: 'flex', flexDirection: 'column', gap: 10,
      }}>
        {credentials.map((c, i) => (
          <li key={i} style={{
            display: 'flex', alignItems: 'flex-start', gap: 10,
            fontFamily: 'Inter, sans-serif', fontWeight: 500, fontSize: 14,
            color: 'var(--color-text-primary)', lineHeight: 1.45,
          }}>
            <span style={{ color: 'var(--color-primary)', flexShrink: 0, marginTop: 1 }}>
              <Mark size={14} />
            </span>
            {c}
          </li>
        ))}
      </ul>
    </article>
  );
}

function ChiSiamoClosing({ onCTA }) {
  return (
    <ParallaxCTASection
      onCTA={onCTA}
      bgSrc="assets/foto/il-centro.webp"
      eyebrow="Vieni a trovarci"
      title="Vieni a conoscerci di persona"
      subtitle="Raccontaci la tua storia e scopri cosa possiamo costruire insieme per il tuo corpo."
    />
  );
}

Object.assign(window, { ChiSiamoHero, TrainerCards, ChiSiamoClosing });
