// HOME page — hero photo + category list + crossfade slideshow
const { useState, useEffect, useRef, useCallback } = React;

window.Home = function Home({ navigate, lang, hoverBehavior = 'crossfade-zoom' }) {
  const t = STRINGS[lang];
  const data = window.PORTFOLIO_DATA;
  const [hovered, setHovered] = useState(null);
  const [mobilePreview, setMobilePreview] = useState(null);
  const [slideIdx, setSlideIdx] = useState(0);
  const timer = useRef(null);
  const isTouchDevice = useRef(typeof window !== 'undefined' && 'ontouchstart' in window);

  // ── Liquid reveal ──────────────────────────────────────
  const mousePos  = useRef({ x: -2000, y: -2000 });
  const lag2      = useRef({ x: -2000, y: -2000 });
  const lag3      = useRef({ x: -2000, y: -2000 });
  const elReveal2 = useRef(null);
  const elReveal3 = useRef(null);
  const rafId     = useRef(null);
  const stageEl   = useRef(null);
  const hasEntered = useRef(false);

  const activeId = hovered || mobilePreview;

  // Slide rotation timer
  useEffect(() => {
    if (!activeId) {
      setSlideIdx(0);
      if (timer.current) { clearInterval(timer.current); timer.current = null; }
      return;
    }
    setSlideIdx(0);
    timer.current = setInterval(() => setSlideIdx(i => i + 1), 3000);
    return () => { if (timer.current) clearInterval(timer.current); };
  }, [activeId]);

  // Smooth organic blob — Catmull-Rom → cubic bezier, no sharp corners
  const blobPath = (cx, cy, r, t, pts = 14) => {
    const points = [];
    for (let i = 0; i < pts; i++) {
      const a = (i / pts) * Math.PI * 2;
      const n = 1
        + Math.sin(a * 2 + t)       * 0.11
        + Math.sin(a * 3 - t * 0.7) * 0.08
        + Math.cos(a * 5 + t * 1.1) * 0.05;
      points.push({ x: cx + Math.cos(a) * r * n, y: cy + Math.sin(a) * r * n });
    }
    const len = points.length;
    let d = `M ${points[0].x.toFixed(1)},${points[0].y.toFixed(1)}`;
    for (let i = 0; i < len; i++) {
      const p0 = points[(i - 1 + len) % len];
      const p1 = points[i];
      const p2 = points[(i + 1) % len];
      const p3 = points[(i + 2) % len];
      const cp1x = (p1.x + (p2.x - p0.x) / 6).toFixed(1);
      const cp1y = (p1.y + (p2.y - p0.y) / 6).toFixed(1);
      const cp2x = (p2.x - (p3.x - p1.x) / 6).toFixed(1);
      const cp2y = (p2.y - (p3.y - p1.y) / 6).toFixed(1);
      d += ` C ${cp1x},${cp1y} ${cp2x},${cp2y} ${p2.x.toFixed(1)},${p2.y.toFixed(1)}`;
    }
    d += ' Z';
    return `path('${d}')`;
  };

  // RAF loop — lerp + organic blob shape for liquid feel
  useEffect(() => {
    if (isTouchDevice.current) return;

    const lerp = (a, b, t) => a + (b - a) * t;

    const tick = () => {
      if (!hasEntered.current) {
        rafId.current = requestAnimationFrame(tick);
        return;
      }

      // Layer 2 — large blob, very slow (heavy liquid feel)
      lag2.current.x = lerp(lag2.current.x, mousePos.current.x, 0.045);
      lag2.current.y = lerp(lag2.current.y, mousePos.current.y, 0.045);
      // Layer 3 — small blob, snappier (inner highlight catches up faster)
      lag3.current.x = lerp(lag3.current.x, mousePos.current.x, 0.16);
      lag3.current.y = lerp(lag3.current.y, mousePos.current.y, 0.16);

      const now = Date.now() * 0.0009;

      const x2 = lag2.current.x, y2 = lag2.current.y;
      const x3 = lag3.current.x, y3 = lag3.current.y;

      const path2 = blobPath(x2, y2, 370, now,       14);
      const path3 = blobPath(x3, y3, 195, now + 1.8, 14);

      // Soft radial mask — large opaque center, 3-stop gradient for gradual fade
      const mask2 = `radial-gradient(circle 400px at ${x2.toFixed(0)}px ${y2.toFixed(0)}px, black 58%, rgba(0,0,0,0.35) 82%, transparent 100%)`;
      const mask3 = `radial-gradient(circle 215px at ${x3.toFixed(0)}px ${y3.toFixed(0)}px, black 52%, rgba(0,0,0,0.3) 80%, transparent 100%)`;

      if (elReveal2.current) {
        elReveal2.current.style.clipPath           = path2;
        elReveal2.current.style.webkitClipPath     = path2;
        elReveal2.current.style.maskImage          = mask2;
        elReveal2.current.style.webkitMaskImage    = mask2;
      }
      if (elReveal3.current) {
        elReveal3.current.style.clipPath           = path3;
        elReveal3.current.style.webkitClipPath     = path3;
        elReveal3.current.style.maskImage          = mask3;
        elReveal3.current.style.webkitMaskImage    = mask3;
      }

      rafId.current = requestAnimationFrame(tick);
    };

    rafId.current = requestAnimationFrame(tick);
    return () => { if (rafId.current) cancelAnimationFrame(rafId.current); };
  }, []);

  const onStageMouseMove = useCallback((e) => {
    if (!stageEl.current) return;
    hasEntered.current = true;
    const r = stageEl.current.getBoundingClientRect();
    mousePos.current = { x: e.clientX - r.left, y: e.clientY - r.top };
  }, []);

  const onStageMouseLeave = useCallback(() => {
    hasEntered.current = false;
    mousePos.current = { x: -2000, y: -2000 };
    // Collapse blobs instantly when mouse leaves
    const hide = 'polygon(0px 0px)';
    const hideMask = 'radial-gradient(circle 0px at -2000px -2000px, black 0%, transparent 0%)';
    if (elReveal2.current) {
      elReveal2.current.style.clipPath = hide;
      elReveal2.current.style.webkitClipPath = hide;
      elReveal2.current.style.maskImage = hideMask;
      elReveal2.current.style.webkitMaskImage = hideMask;
    }
    if (elReveal3.current) {
      elReveal3.current.style.clipPath = hide;
      elReveal3.current.style.webkitClipPath = hide;
      elReveal3.current.style.maskImage = hideMask;
      elReveal3.current.style.webkitMaskImage = hideMask;
    }
    lag2.current = { x: -2000, y: -2000 };
    lag3.current = { x: -2000, y: -2000 };
  }, []);

  // ── Touch handlers (mobile liquid reveal) ──────────────
  const onTouchCapture = useCallback((e) => {
    if (!stageEl.current) return;
    const r = stageEl.current.getBoundingClientRect();
    const t = e.touches[0];
    hasEntered.current = true;
    mousePos.current = { x: t.clientX - r.left, y: t.clientY - r.top };
  }, []);

  const onTouchEndCapture = useCallback(() => {
    hasEntered.current = false;
    mousePos.current = { x: -2000, y: -2000 };
    lag2.current = { x: -2000, y: -2000 };
    lag3.current = { x: -2000, y: -2000 };
    const hide = 'polygon(0px 0px)';
    const hideMask = 'radial-gradient(circle 0px at -2000px -2000px, black 0%, transparent 0%)';
    if (elReveal2.current) {
      elReveal2.current.style.clipPath = hide;
      elReveal2.current.style.webkitClipPath = hide;
      elReveal2.current.style.maskImage = hideMask;
      elReveal2.current.style.webkitMaskImage = hideMask;
    }
    if (elReveal3.current) {
      elReveal3.current.style.clipPath = hide;
      elReveal3.current.style.webkitClipPath = hide;
      elReveal3.current.style.maskImage = hideMask;
      elReveal3.current.style.webkitMaskImage = hideMask;
    }
  }, []);

  // ── Category slideshow ─────────────────────────────────
  const cat = activeId ? data.categories.find(c => c.id === activeId) : null;
  const slides = cat ? cat.slides : [];
  const activeSlide = slides.length ? slides[slideIdx % slides.length] : null;

  const handleCatClick = (c) => {
    if (isTouchDevice.current) {
      if (mobilePreview !== c.id) setMobilePreview(c.id);
    } else {
      navigate({ name: 'category', id: c.id });
    }
  };

  return (
    <section
      className={`home ${activeId ? 'is-hovering' : ''}`}
      data-screen-label="01 Home"
      ref={stageEl}
      onMouseMove={onStageMouseMove}
      onMouseLeave={onStageMouseLeave}
    >

      <div className="home-stage">
        {/* Layer 1 — base photo */}
        <div className="home-photo" />

        {/* Layer 2 — liquid reveal, large slow blob */}
        <div ref={elReveal2} className="home-reveal-layer home-reveal-2" />

        {/* Layer 3 — liquid reveal, small fast inner highlight */}
        <div ref={elReveal3} className="home-reveal-layer home-reveal-3" />

        {/* Touch capture layer — mobile only, sits above layers but below overlay */}
        <div
          className="touch-capture"
          onTouchStart={onTouchCapture}
          onTouchMove={onTouchCapture}
          onTouchEnd={onTouchEndCapture}
          onTouchCancel={onTouchEndCapture}
        />

        {/* Category crossfade slideshow (category hover) */}
        <div className="home-slideshow">
          {data.categories.map(c => (
            c.slides.map((s, i) => {
              const isVisible = (hovered === c.id || mobilePreview === c.id) && (i === (slideIdx % c.slides.length));
              const slideSrc = (isTouchDevice.current && s.mobileSrc) ? s.mobileSrc : s.src;
              return (
                <div key={`${c.id}-${i}`} className={`slide ${isVisible ? 'is-active' : ''}`}>
                  <ColorField hue={s.hue} lightness={s.lightness} chroma="rich" src={slideSrc} />
                </div>
              );
            })
          ))}
        </div>

        <div className="home-tint" />
      </div>

      {/* Slideshow caption */}
      <div className="slide-caption">
        {activeSlide && (
          <>
            <div style={{ opacity: 0.55 }}>{cat.label[lang]} / {String(slideIdx % slides.length + 1).padStart(2, '0')}</div>
            <div style={{ marginTop: 4 }}>{activeSlide.label}</div>
          </>
        )}
      </div>

      {/* Category list */}
      <div className="cat-list">
        <div className="cat-list-label">{t.catLabel} / 04</div>
        {data.categories.map(c => (
          <button
            key={c.id}
            className={`cat-item ${activeId === c.id ? 'is-hovered' : ''}`}
            onMouseEnter={() => !isTouchDevice.current && setHovered(c.id)}
            onMouseLeave={() => !isTouchDevice.current && setHovered(null)}
            onClick={() => handleCatClick(c)}
          >
            <span className="num">{c.number}</span>
            <span className="label">{c.label[lang]}</span>
            <span className="arrow">→</span>
          </button>
        ))}
      </div>

      {/* Mobile preview bar */}
      {mobilePreview && (
        <div className="mobile-preview-bar">
          <div className="mobile-preview-label">
            {data.categories.find(c => c.id === mobilePreview)?.label[lang]}
          </div>
          <div className="mobile-preview-actions">
            <button className="mobile-preview-back" onClick={() => setMobilePreview(null)}>← {lang === 'pt' ? 'Voltar' : 'Back'}</button>
            <button className="mobile-preview-enter" onClick={() => navigate({ name: 'category', id: mobilePreview })}>{lang === 'pt' ? 'Entrar' : 'Enter'} →</button>
          </div>
        </div>
      )}

      <div className="home-overlay">
        <div className="home-overlay-top" />

        {/* Intro tagline */}
        <div style={{
          maxWidth: 480,
          marginBottom: 36,
          transition: 'opacity .5s, color .8s',
          opacity: activeId ? 0 : 1,
          color: 'var(--ink)'
        }}>
          <div className="mono" style={{ opacity: 0.5, marginBottom: 14 }}>{t.photoLabel}</div>
          <h1 style={{
            fontFamily: 'var(--display)', fontWeight: 400,
            fontSize: 'clamp(22px, 2vw, 30px)',
            lineHeight: 1.1, letterSpacing: '-0.02em', margin: 0
          }}>
            {lang === 'pt'
              ? <>Há mais de 15 anos <em style={{ fontStyle: 'italic', color: 'var(--accent)', fontWeight: 300 }}>criando universos.</em></>
              : <>Over 15 years <em style={{ fontStyle: 'italic', color: 'var(--accent)', fontWeight: 300 }}>creating universes.</em></>
            }
          </h1>
        </div>

        <div className="home-foot">
          <div className="left">
            <span>{t.portfolio}</span>
            <span>{t.based}</span>
          </div>
          <div className="right">
            <span className="scrub"><span className="dot" /> {t.available}</span>
          </div>
        </div>
      </div>
    </section>
  );
};
