/* global React */
const { useState: useStateH, useEffect: useEffectH, useRef: useRefH } = React;

/* ========================= HERO (3 variations) ========================= */

// V1 - Canvas particles (orange/bleu) with gentle parallax
function HeroParticles() {
  const ref = useRefH(null);
  useEffectH(() => {
    const canvas = ref.current; if (!canvas) return;
    const ctx = canvas.getContext('2d');
    let w, h, particles, raf, mouse = { x: 0, y: 0 };
    const resize = () => {
      w = canvas.width = canvas.offsetWidth * devicePixelRatio;
      h = canvas.height = canvas.offsetHeight * devicePixelRatio;
    };
    const init = () => {
      resize();
      particles = Array.from({ length: 100 }, () => ({
        x: Math.random()*w, y: Math.random()*h,
        vx: (Math.random()-0.5)*0.3, vy: (Math.random()-0.5)*0.3,
        r: Math.random()*2 + 0.5,
        c: Math.random() > 0.6 ? '#EB9222' : '#2C5F8D',
      }));
    };
    const onMove = e => {
      const rect = canvas.getBoundingClientRect();
      mouse.x = (e.clientX - rect.left) * devicePixelRatio;
      mouse.y = (e.clientY - rect.top) * devicePixelRatio;
    };
    const loop = () => {
      ctx.clearRect(0, 0, w, h);
      particles.forEach(p => {
        p.x += p.vx; p.y += p.vy;
        if (p.x < 0 || p.x > w) p.vx *= -1;
        if (p.y < 0 || p.y > h) p.vy *= -1;
        const dx = p.x - mouse.x, dy = p.y - mouse.y;
        const d = Math.sqrt(dx*dx + dy*dy);
        if (d < 120*devicePixelRatio) {
          p.x += dx / d * 0.8; p.y += dy / d * 0.8;
        }
        ctx.beginPath();
        ctx.arc(p.x, p.y, p.r*devicePixelRatio, 0, Math.PI*2);
        ctx.fillStyle = p.c; ctx.globalAlpha = 0.6;
        ctx.fill();
      });
      // connect
      for (let i=0;i<particles.length;i++) for (let j=i+1;j<particles.length;j++) {
        const a=particles[i], b=particles[j];
        const dx=a.x-b.x, dy=a.y-b.y, d=Math.sqrt(dx*dx+dy*dy);
        if (d < 100*devicePixelRatio) {
          ctx.beginPath(); ctx.moveTo(a.x, a.y); ctx.lineTo(b.x, b.y);
          ctx.strokeStyle = a.c; ctx.globalAlpha = (1 - d/(100*devicePixelRatio)) * 0.15;
          ctx.lineWidth = 1; ctx.stroke();
        }
      }
      raf = requestAnimationFrame(loop);
    };
    init(); loop();
    window.addEventListener('resize', init);
    window.addEventListener('mousemove', onMove);
    return () => { cancelAnimationFrame(raf); window.removeEventListener('resize', init); window.removeEventListener('mousemove', onMove); };
  }, []);
  return <div className="hero-canvas"><canvas ref={ref} /></div>;
}

// V2 - Rotating words
function RotatingWord({ words }) {
  const [i, setI] = useStateH(0);
  useEffectH(() => {
    const t = setInterval(() => setI(v => (v+1) % words.length), 2400);
    return () => clearInterval(t);
  }, [words.length]);
  return (
    <span className="rotate-wrap" aria-live="polite">
      {words.map((w, idx) => (
        <span key={idx} className={idx === i ? 'active' : (idx === (i-1+words.length)%words.length ? 'exit' : '')}>{w}</span>
      ))}
    </span>
  );
}

// V3 - Parallax gallery
function HeroGallery() {
  const t = useI18n();
  const ref = useRefH(null);
  useEffectH(() => {
    const onMove = e => {
      const cards = ref.current?.querySelectorAll('.card') || [];
      const cx = (e.clientX / window.innerWidth - 0.5);
      const cy = (e.clientY / window.innerHeight - 0.5);
      cards.forEach((c, i) => {
        const f = (i+1) * 12;
        c.style.transform = `translate(${cx*f}px, ${cy*f}px) rotate(${c.dataset.r}deg)`;
      });
    };
    window.addEventListener('mousemove', onMove);
    return () => window.removeEventListener('mousemove', onMove);
  }, []);
  return (
    <div className="hero-gallery" ref={ref}>
      <div className="card c1" data-r="6" style={{ background: 'linear-gradient(135deg, #EB9222, #D27814)' }}></div>
      <div className="card c2" data-r="-4" style={{ background: 'linear-gradient(135deg, #2C5F8D, #1B3F60)' }}></div>
      <div className="card c3" data-r="3" style={{ background: 'linear-gradient(135deg, #F7B867, #EB9222)' }}></div>
      <div className="card c4" data-r="-8" style={{ background: '#0E1116', color: '#EB9222', display: 'grid', placeItems: 'center', fontFamily: 'Bricolage Grotesque', fontWeight: 700, fontSize: 22 }}>{t('home.hero.gallery_years', '14 ans')}</div>
    </div>
  );
}

function Hero({ variant = 'mix' }) {
  const t = useI18n();
  return (
    <section className={'hero hero-variant-' + variant} id="hero">
      {(variant === 'particles' || variant === 'mix') && <HeroParticles />}
      {(variant === 'gallery' || variant === 'mix') && <HeroGallery />}
      <div className="container hero-inner">
        <div className="chip reveal in"><span className="dot"></span>{t('home.hero.chip', 'Agence web à Fuveau · Aix-en-Provence')}</div>

        {variant === 'rotate' ? (
          <h1 className="hero-title reveal in" style={{ marginTop: 24 }}>
            {t('home.hero.rotate_prefix', 'Je crée des sites web qui')}{' '}
            <RotatingWord words={[t('home.hero.rotate_word1', 'convertissent.'), t('home.hero.rotate_word2', 'attirent.'), t('home.hero.rotate_word3', 'performent.'), t('home.hero.rotate_word4', 'durent.'), t('home.hero.rotate_word5', 'rayonnent.')]} />
          </h1>
        ) : (
          <h1 className="hero-title reveal in" style={{ marginTop: 24 }}>
            <span style={{ color: 'var(--yo-blue)' }}>{t('home.hero.title_line1', 'Votre site web,')}</span><br/>
            {t('home.hero.title_line2', 'fait avec soin,')}<br/>
            {t('home.hero.title_line3', 'pensé pour durer.')}
          </h1>
        )}

        <p className="hero-sub reveal in">
          {t('home.hero.subtitle', "Je m'appelle Yann, et depuis 2012 j'accompagne les entrepreneurs et TPE autour d'Aix-en-Provence pour donner vie à leur présence en ligne. Un interlocuteur, des tarifs clairs, du travail soigné.")}
        </p>

        <div className="hero-actions reveal in">
          <a href="#services" className="btn accent">{t('home.hero.btn_services', 'Découvrir mes services')}
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
          </a>
          <a href="#contact" className="btn ghost">{t('home.hero.btn_devis', 'Demander un devis gratuit')}</a>
        </div>

        <div className="hero-meta reveal in">
          <div className="item"><div className="num">{t('home.hero.meta_sites_num', '200+')}</div><div className="label">{t('home.hero.meta_sites_label', 'sites créés & maintenus depuis 2012')}</div></div>
          <div className="item"><div className="num" style={{ color: 'var(--yo-blue)' }}>{t('home.hero.meta_response_num', '24h')}</div><div className="label">{t('home.hero.meta_response_label', 'délai de réponse sur vos demandes')}</div></div>
          <div className="item"><div className="num">{t('home.hero.meta_rating_num', '5/5')}</div><div className="label">{t('home.hero.meta_rating_label', "d'avis Google vérifiés par nos clients")}</div></div>
        </div>
      </div>

      <div className="scroll-cue"><span>{t('home.hero.scroll_cue', 'Scrollez')}</span><span className="line"></span></div>
    </section>
  );
}

Object.assign(window, { Hero, HeroParticles, HeroGallery, RotatingWord });
