/* Clara v2 — Hero banner (carousel of 3 questions → CLARA. logo reveal) */

const { useEffect, useState, useRef, useMemo } = React;

const HERO_SLIDES = [
  {
    area: 'DIRECCIÓN FINANCIERA',
    question:
      '¿Sabes cuál es el margen real de tu negocio este mes, o el número cambia según qué sistema consultes?',
  },
  {
    area: 'GERENCIA DE MARKETING',
    question:
      '¿Sabes qué campañas te están generando ventas reales después de devoluciones, descuentos y costos de adquisición?',
  },
  {
    area: 'GERENCIA GENERAL',
    question:
      '¿Cuánto capital tienes dormido en inventario que lleva más de 90 días sin moverse? ¿Y cuánto te cuesta cada mes?',
  },
];

const SLIDE_DURATION = 7000;
const FINAL_DURATION = 18000;
const WORD_STAGGER = 35; // ms per word

function HeroWordReveal({ text, run }) {
  const words = useMemo(() => text.split(' '), [text]);
  return (
    <React.Fragment>
      {words.map((w, i) => (
        <span
          key={`${i}-${w}`}
          className={`word ${run ? 'in' : ''}`}
          style={{ transitionDelay: run ? `${180 + i * WORD_STAGGER}ms` : '0ms' }}
        >
          {w}{i < words.length - 1 ? ' ' : ''}
        </span>
      ))}
    </React.Fragment>
  );
}

function HeroBanner() {
  const [index, setIndex] = useState(0);
  const [phase, setPhase] = useState('slides'); // 'slides' | 'final'
  const [paused, setPaused] = useState(false);
  const [progress, setProgress] = useState(0); // 0..1
  const [wordsRun, setWordsRun] = useState(false);
  const elapsedRef = useRef(0);
  const startedAtRef = useRef(null);
  const rafRef = useRef(null);
  const beatRef = useBeatAnchor('beat-hero-final');

  const duration = phase === 'final' ? FINAL_DURATION : SLIDE_DURATION;

  // Restart word-reveal on slide / phase change
  useEffect(() => {
    setWordsRun(false);
    const t = setTimeout(() => setWordsRun(true), 60);
    return () => clearTimeout(t);
  }, [index, phase]);

  const resetTimer = () => {
    elapsedRef.current = 0;
    startedAtRef.current = null;
    setProgress(0);
  };

  const goNext = () => {
    resetTimer();
    if (phase === 'final') {
      setIndex(0);
      setPhase('slides');
      return;
    }
    if (index < HERO_SLIDES.length - 1) {
      setIndex((i) => i + 1);
    } else {
      setPhase('final');
    }
  };

  useEffect(() => {
    resetTimer();
  }, [index, phase]);

  useEffect(() => {
    if (paused) {
      if (startedAtRef.current !== null) {
        elapsedRef.current += performance.now() - startedAtRef.current;
        startedAtRef.current = null;
      }
      if (rafRef.current) cancelAnimationFrame(rafRef.current);
      return;
    }
    startedAtRef.current = performance.now();
    const tick = () => {
      if (startedAtRef.current === null) return;
      const elapsed = elapsedRef.current + performance.now() - startedAtRef.current;
      const p = Math.min(elapsed / duration, 1);
      setProgress(p);
      if (elapsed >= duration) { goNext(); return; }
      rafRef.current = requestAnimationFrame(tick);
    };
    rafRef.current = requestAnimationFrame(tick);
    return () => { if (rafRef.current) cancelAnimationFrame(rafRef.current); };
  }, [index, phase, paused, duration]);

  // Fire a global "beat-hero" pulse on phase change to slides → final
  useEffect(() => {
    if (phase === 'final') BeatBus.fire('beat-hero-final');
  }, [phase]);

  const current = HERO_SLIDES[index];

  return (
    <section
      className="act hero-banner"
      data-screen-label="01 Hero"
      id="hero"
      onMouseEnter={() => setPaused(true)}
      onMouseLeave={() => setPaused(false)}
      ref={beatRef}
    >
      <div className="stage-bg" />

      <button className="replay-btn" onClick={() => { setIndex(0); setPhase('slides'); resetTimer(); }}>
        Repetir
      </button>

      {phase === 'slides' ? (
        <div key={index} className="slide-frame">
          <div className="area-tag">{current.area}</div>
          <h1 className="question">
            <HeroWordReveal text={current.question} run={wordsRun} />
          </h1>
          <div className="clara-knows">
            <span className="ko-dot" />
            Clara sí lo sabe
            <span className="arr">→</span>
          </div>
        </div>
      ) : (
        <div className="slide-frame" style={{ gridTemplateColumns: '1fr' }}>
          <div className="final-stage">
            <div className="clara-logo fx-rise in" style={{ transitionDelay: '0.15s' }}>
              reCLARA<span className="live" aria-hidden="true" />
            </div>
            <p className="lede fx-rise in" style={{ transitionDelay: '0.6s' }}>
              Si la tienes <span style={{ color: 'var(--accent)', fontStyle: 'italic' }}>clara</span> te mueves.
            </p>
            <div className="ctas fx-rise in" style={{ transitionDelay: '0.9s' }}>
              <a className="btn btn-primary" href="#cta">Solicitar demo →</a>
              <a className="btn btn-ghost-dark" href="#cmo">Ver cómo funciona →</a>
            </div>
            <div className="integrations-strip fx-fade in" style={{ transitionDelay: '1.2s' }}>
              <span className="lbl">Conecta con</span>
              <div className="integrations-grid">

                {/* ERP SAP */}
                <div className="int-icon">
                  <svg viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <ellipse cx="24" cy="14" rx="13" ry="4.5" stroke="currentColor" strokeWidth="2.5" fill="none"/>
                    <path d="M11 14v8M37 14v8" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"/>
                    <ellipse cx="24" cy="22" rx="13" ry="4.5" stroke="currentColor" strokeWidth="2.5" fill="none"/>
                    <path d="M11 22v8M37 22v8" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"/>
                    <ellipse cx="24" cy="30" rx="13" ry="4.5" stroke="currentColor" strokeWidth="2.5" fill="none"/>
                  </svg>
                  <span>ERP SAP</span>
                </div>

                {/* Shopify */}
                <div className="int-icon">
                  <svg viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M14 18h20l-2.5 20H16.5L14 18z" stroke="currentColor" strokeWidth="2.5" strokeLinejoin="round" fill="none"/>
                    <path d="M19 18c0-2.8 2.2-5 5-5s5 2.2 5 5" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" fill="none"/>
                    <path d="M21.5 31c0-1.2 1.1-2 2.5-2s2.5.7 2.5 1.6-1.1 1.6-2.5 1.6-2.5.6-2.5 1.5 1.1 1.8 2.5 1.8 2.5-.6 2.5-1.5" stroke="currentColor" strokeWidth="2" fill="none" strokeLinecap="round"/>
                  </svg>
                  <span>Shopify</span>
                </div>

                {/* Google Sheets */}
                <div className="int-icon">
                  <svg viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M11 8h18l9 9v25H11V8z" stroke="currentColor" strokeWidth="2.5" strokeLinejoin="round" fill="none"/>
                    <path d="M29 8v9h9" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"/>
                    <line x1="11" y1="24" x2="38" y2="24" stroke="currentColor" strokeWidth="2"/>
                    <line x1="11" y1="31" x2="38" y2="31" stroke="currentColor" strokeWidth="2"/>
                    <line x1="25" y1="17" x2="25" y2="42" stroke="currentColor" strokeWidth="2"/>
                  </svg>
                  <span>Google Sheets</span>
                </div>

                {/* Meta Ads */}
                <div className="int-icon">
                  <svg viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M8 24c0-4.8 3-8.5 7.5-8.5 2.5 0 4.8 1.4 7 4.2.5.7 1 1.4 1.5 2.3.5-.9 1-1.6 1.5-2.3 2.2-2.8 4.5-4.2 7-4.2C37 15.5 40 19.2 40 24s-3 8.5-7.5 8.5c-2.5 0-4.8-1.4-7-4.2-.5-.7-1-1.4-1.5-2.3-.5.9-1 1.6-1.5 2.3-2.2 2.8-4.5 4.2-7 4.2C11 32.5 8 28.8 8 24z" stroke="currentColor" strokeWidth="2.5" fill="none"/>
                  </svg>
                  <span>Meta Ads</span>
                </div>

                {/* Contabilidad */}
                <div className="int-icon">
                  <svg viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <rect x="11" y="8" width="26" height="32" rx="3" stroke="currentColor" strokeWidth="2.5" fill="none"/>
                    <rect x="15" y="12" width="18" height="8" rx="2" stroke="currentColor" strokeWidth="2" fill="none"/>
                    <circle cx="18" cy="27" r="1.8" fill="currentColor"/>
                    <circle cx="24" cy="27" r="1.8" fill="currentColor"/>
                    <circle cx="30" cy="27" r="1.8" fill="currentColor"/>
                    <circle cx="18" cy="33" r="1.8" fill="currentColor"/>
                    <circle cx="24" cy="33" r="1.8" fill="currentColor"/>
                    <rect x="28.5" y="31.5" width="3" height="3" rx="0.5" fill="currentColor"/>
                  </svg>
                  <span>Contabilidad</span>
                </div>

                {/* Vtex */}
                <div className="int-icon">
                  <svg viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M8 13l16 22L40 13" stroke="currentColor" strokeWidth="3.5" strokeLinecap="round" strokeLinejoin="round"/>
                    <path d="M17 13l7 10 7-10" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" opacity="0.45"/>
                  </svg>
                  <span>Vtex</span>
                </div>

                {/* Más */}
                <div className="int-icon int-more">
                  <svg viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <circle cx="24" cy="24" r="16" stroke="currentColor" strokeWidth="2" fill="none"/>
                    <path d="M24 16v16M16 24h16" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"/>
                  </svg>
                  <span>y más</span>
                </div>

              </div>
            </div>
          </div>
        </div>
      )}

      {phase === 'slides' && (
        <div className="progress-dots">
          {HERO_SLIDES.map((_, i) => (
            <span key={i} className={`pd ${i === index ? 'active' : ''}`} />
          ))}
        </div>
      )}

      <div className="progress-bar">
        <div
          className="fill"
          style={{ transform: `scaleX(${progress})` }}
        />
      </div>
    </section>
  );
}

window.HeroBanner = HeroBanner;
