/* global React */
const { useEffect, useRef } = React;
const NOTEBOOK_SRC = "assets/notebook-conversão.png";

const PAINS = [
  "Planilhas desatualizadas sem controle",
  "Informações espalhadas em papéis e e-mails",
  "Processos manuais lentos e sujeitos a erro",
  "Decisões tomadas sem dados confiáveis",
  "Time sobrecarregado com tarefas repetitivas",
];

const GAINS = [
  ["99.9%", "disponibilidade"],
  ["-68%",  "tempo operacional"],
  ["+24%",  "eficiência da equipe"],
  ["1",     "fonte de verdade"],
];

function Conversion() {
  const containerRef = useRef(null);
  const pinRef       = useRef(null);
  const beforeRef    = useRef(null);
  const afterRef     = useRef(null);
  const cadernoRef   = useRef(null);
  const notebookRef  = useRef(null);
  const glowBgRef    = useRef(null);
  const imgGlowRef   = useRef(null);
  const barRef       = useRef(null);
  const hintRef      = useRef(null);
  const gainsRef     = useRef([]);
  const ctaRef       = useRef(null);

  useEffect(() => {
    const section = containerRef.current;
    const pin = pinRef.current;
    if (!section || !pin) return undefined;

    const clamp01 = value => Math.max(0, Math.min(1, value));
    const ease = t => t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;

    const apply = (rawProgress) => {
      const raw = clamp01(rawProgress);
      const transitionStart = 0.28;
      const transitionEnd = 0.72;
      const pt = ease(clamp01((raw - transitionStart) / (transitionEnd - transitionStart)));

      if (beforeRef.current) {
        const opacity = Math.max(0, 1 - Math.max(0, pt - 0.45) * 5.0);
        beforeRef.current.style.opacity = String(opacity);
        beforeRef.current.style.transform = `translateY(${pt * -36}px)`;
        beforeRef.current.style.pointerEvents = opacity < 0.15 ? "none" : "auto";
      }

      if (afterRef.current) {
        const opacity = clamp01((pt - 0.40) * 3.5);
        afterRef.current.style.opacity = String(opacity);
        afterRef.current.style.transform = `translateY(${(1 - opacity) * 36}px)`;
        afterRef.current.style.pointerEvents = opacity < 0.1 ? "none" : "auto";
      }

      if (cadernoRef.current) {
        const opacity = Math.max(0, 1 - Math.max(0, pt - 0.42) * 5.0);
        cadernoRef.current.style.opacity = String(opacity);
        cadernoRef.current.style.transform = `scale(${1 - pt * 0.12}) rotate(${pt * -7}deg) translateY(${pt * 22}px)`;
        cadernoRef.current.style.filter = `grayscale(${Math.min(100, pt * 140)}%) blur(${Math.min(6, pt * 8)}px)`;
      }

      if (notebookRef.current) {
        const opacity = clamp01((pt - 0.35) * 3.5);
        notebookRef.current.style.opacity = String(opacity);
        notebookRef.current.style.transform = `scale(${0.88 + pt * 0.12}) translateY(${(1 - opacity) * 28}px)`;
        notebookRef.current.style.filter = `drop-shadow(0 32px 80px rgba(0,217,255,${pt * 0.65}))`;
      }

      if (glowBgRef.current) {
        glowBgRef.current.style.background =
          `radial-gradient(ellipse 80% 80% at 68% 50%, rgba(0,217,255,${pt * 0.20}), transparent 60%)`;
      }

      if (imgGlowRef.current) {
        imgGlowRef.current.style.background = pt > 0.40
          ? `radial-gradient(ellipse at 50% 55%, rgba(0,217,255,${pt * 0.32}), transparent 65%)`
          : `radial-gradient(ellipse at 50% 55%, rgba(255,185,55,${(1 - pt) * 0.18}), transparent 65%)`;
      }

      gainsRef.current.forEach((el, i) => {
        if (!el) return;
        const show = pt > 0.55 + i * 0.06;
        el.style.opacity = show ? "1" : "0";
        el.style.transform = `translateY(${show ? 0 : 22}px)`;
      });

      if (ctaRef.current) {
        const show = pt > 0.86;
        ctaRef.current.style.opacity = show ? "1" : "0";
        ctaRef.current.style.transform = `translateY(${show ? 0 : 14}px)`;
      }

      if (barRef.current) barRef.current.style.height = `${raw * 100}%`;
      if (hintRef.current) {
        const showHint = raw < 0.96;
        hintRef.current.style.opacity = showHint ? "1" : "0";
        hintRef.current.style.pointerEvents = showHint ? "auto" : "none";
      }
    };

    apply(0);

    const mobileQuery = window.matchMedia("(max-width: 860px)");
    const isMobile = mobileQuery.matches;

    const gsapInstance = window.gsap;
    const ScrollTriggerPlugin = window.ScrollTrigger;

    if (!gsapInstance || !ScrollTriggerPlugin) {
      if (!isMobile) {
        section.style.minHeight = "245vh";
        pin.style.position = "sticky";
        pin.style.top = "0";
      }

      let target = 0;
      let current = 0;
      let rafId = null;
      const lerp = 0.08;

      const getTarget = () => {
        const rect = section.getBoundingClientRect();
        if (isMobile) {
          const start = window.innerHeight * 0.82;
          const distance = Math.max(window.innerHeight * 0.75, section.offsetHeight * 0.55);
          return clamp01((start - rect.top) / distance);
        }

        const total = section.offsetHeight - window.innerHeight;
        if (total <= 0) return 0;
        return clamp01(-rect.top / total);
      };

      const tick = () => {
        target = getTarget();
        const diff = target - current;
        if (Math.abs(diff) > 0.0006) {
          current += diff * lerp;
          apply(current);
          rafId = requestAnimationFrame(tick);
        } else {
          current = target;
          apply(current);
          rafId = null;
        }
      };

      const onScroll = () => {
        if (!rafId) rafId = requestAnimationFrame(tick);
      };

      window.addEventListener("scroll", onScroll, { passive: true });
      rafId = requestAnimationFrame(tick);

      return () => {
        window.removeEventListener("scroll", onScroll);
        if (rafId) cancelAnimationFrame(rafId);
        section.style.minHeight = "";
        pin.style.position = "";
        pin.style.top = "";
      };
    }

    gsapInstance.registerPlugin(ScrollTriggerPlugin);

    const refresh = () => ScrollTriggerPlugin.refresh();
    const images = Array.from(section.querySelectorAll("img"));

    const trigger = ScrollTriggerPlugin.create({
      trigger: section,
      start: isMobile ? "top 82%" : "top top",
      end: () => `+=${Math.round(window.innerHeight * (isMobile ? 0.9 : 1.45))}`,
      pin: isMobile ? false : pin,
      pinSpacing: !isMobile,
      scrub: isMobile ? 0.45 : 0.85,
      anticipatePin: isMobile ? 0 : 1,
      invalidateOnRefresh: true,
      onUpdate: self => apply(self.progress),
      onRefresh: self => apply(self.progress),
    });

    images.forEach(img => {
      if (!img.complete) img.addEventListener("load", refresh, { once: true });
    });

    const refreshId = requestAnimationFrame(refresh);

    return () => {
      cancelAnimationFrame(refreshId);
      images.forEach(img => img.removeEventListener("load", refresh));
      trigger.kill();
    };
  }, []);

  const panel = {
    position: "absolute", top: 0, left: 0, right: 0, bottom: 0,
    display: "flex", flexDirection: "column", justifyContent: "center",
  };

  return (
    <section ref={containerRef} className="conversion-section">
      <div ref={pinRef} className="conversion-pin">
        <div ref={glowBgRef} style={{ position: "absolute", inset: 0, pointerEvents: "none", zIndex: 0 }} />
        <div className="grid-bg" style={{ zIndex: 0 }} />

        <div style={{ position: "relative", zIndex: 2 }}>
          <div className="wrap">
            <div className="conversion-grid">
              <div style={{ position: "relative", height: "56vh", maxHeight: 500 }}>
                <div ref={beforeRef} style={panel}>
                  <div style={{
                    fontFamily: "var(--font-mono)", fontSize: 11,
                    color: "rgba(255,185,55,0.85)", letterSpacing: "0.18em",
                    marginBottom: 18, display: "flex", alignItems: "center", gap: 8,
                  }}>
                    <span style={{ width: 6, height: 6, borderRadius: "50%", background: "rgba(255,185,55,0.9)", display: "inline-block" }} />
                    REALIDADE ATUAL
                  </div>
                  <h2 style={{
                    fontFamily: "var(--font-display)", fontWeight: 400,
                    fontSize: "clamp(28px, 3vw, 48px)",
                    lineHeight: 1.1, letterSpacing: "-0.025em", marginBottom: 28,
                  }}>
                    Sua gestão ainda<br />
                    <span style={{ color: "rgba(255,185,55,0.95)", fontStyle: "italic", fontWeight: 300 }}>
                      depende do papel?
                    </span>
                  </h2>
                  <div style={{ display: "flex", flexDirection: "column", gap: 9 }}>
                    {PAINS.map((pain, i) => (
                      <div
                        key={pain}
                        style={{
                          display: "flex", alignItems: "center", gap: 11,
                          animation: `convPainIn 0.55s ${0.10 + i * 0.09}s cubic-bezier(.2,.7,.2,1) both`,
                        }}
                      >
                        <span style={{
                          width: 22, height: 22, borderRadius: 7, flexShrink: 0,
                          background: "rgba(255,80,60,0.1)", border: "1px solid rgba(255,80,60,0.25)",
                          display: "grid", placeItems: "center",
                          fontSize: 11, color: "rgba(255,120,100,0.9)",
                        }}>×</span>
                        <span style={{ fontSize: 14, color: "var(--text-dim)", lineHeight: 1.4 }}>{pain}</span>
                      </div>
                    ))}
                  </div>
                </div>

                <div ref={afterRef} style={{ ...panel, opacity: 0, transform: "translateY(36px)", pointerEvents: "none" }}>
                  <div style={{
                    fontFamily: "var(--font-mono)", fontSize: 11,
                    color: "var(--cyan)", letterSpacing: "0.18em",
                    marginBottom: 18, display: "flex", alignItems: "center", gap: 8,
                  }}>
                    <span style={{ width: 6, height: 6, borderRadius: "50%", background: "var(--cyan)", display: "inline-block" }} />
                    NEXFUTURUM · DIGITAL
                  </div>
                  <h2 style={{
                    fontFamily: "var(--font-display)", fontWeight: 400,
                    fontSize: "clamp(28px, 3vw, 48px)",
                    lineHeight: 1.1, letterSpacing: "-0.025em", marginBottom: 28,
                  }}>
                    Transforme tudo em<br />
                    <span style={{ color: "var(--cyan)", fontStyle: "italic", fontWeight: 300 }}>
                      operação digital.
                    </span>
                  </h2>
                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 24 }}>
                    {GAINS.map(([num, label], i) => (
                      <div
                        key={label}
                        ref={el => { gainsRef.current[i] = el; }}
                        style={{
                          padding: "12px 16px",
                          background: "rgba(0,217,255,0.05)", border: "1px solid rgba(0,217,255,0.12)",
                          borderRadius: 12,
                          opacity: 0, transform: "translateY(22px)",
                          transition: "opacity 0.4s ease, transform 0.4s ease",
                        }}
                      >
                        <div style={{
                          fontFamily: "var(--font-display)", fontSize: 24, fontWeight: 300,
                          background: "linear-gradient(135deg, var(--cyan), var(--blue))",
                          WebkitBackgroundClip: "text", backgroundClip: "text", color: "transparent",
                          marginBottom: 2,
                        }}>{num}</div>
                        <div style={{ fontSize: 10, color: "var(--text-mute)", textTransform: "uppercase", letterSpacing: "0.1em", fontFamily: "var(--font-mono)" }}>{label}</div>
                      </div>
                    ))}
                  </div>
                  <a
                    ref={ctaRef}
                    href="#/contato"
                    className="btn btn-primary"
                    style={{ opacity: 0, transform: "translateY(14px)", transition: "opacity 0.4s ease, transform 0.4s ease", alignSelf: "flex-start" }}
                  >
                    Quero transformar minha operação <span className="arrow">→</span>
                  </a>
                </div>
              </div>

              <div style={{ position: "relative", height: "56vh", maxHeight: 500 }}>
                <div ref={imgGlowRef} style={{
                  position: "absolute", inset: "8%", zIndex: 0,
                  background: "radial-gradient(ellipse at 50% 55%, rgba(255,185,55,0.18), transparent 65%)",
                  filter: "blur(40px)",
                }} />
                <img
                  ref={cadernoRef}
                  src="assets/caderno.png"
                  alt="Gestão em papel"
                  style={{
                    position: "absolute", top: 0, left: 0, right: 0, bottom: 0,
                    width: "100%", height: "100%",
                    objectFit: "contain", objectPosition: "center",
                    zIndex: 1,
                  }}
                />
                <img
                  ref={notebookRef}
                  src={NOTEBOOK_SRC}
                  alt="Plataforma Nexfuturum"
                  style={{
                    position: "absolute", top: 0, left: 0, right: 0, bottom: 0,
                    width: "100%", height: "100%",
                    objectFit: "contain", objectPosition: "center",
                    zIndex: 2, opacity: 0,
                  }}
                />
              </div>
            </div>
          </div>
        </div>

        <div ref={hintRef} style={{
          position: "absolute", bottom: 24, left: "50%",
          transform: "translateX(-50%)",
          display: "flex", flexDirection: "column", alignItems: "center", gap: 10,
          transition: "opacity 0.5s", zIndex: 3,
        }}>
          <div style={{ width: 1, height: 40, background: "rgba(255,255,255,0.08)", borderRadius: 2, overflow: "hidden" }}>
            <div ref={barRef} style={{ width: "100%", height: "0%", background: "var(--cyan)", boxShadow: "0 0 6px var(--cyan)" }} />
          </div>
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 9, color: "var(--text-mute)", letterSpacing: "0.22em" }}>
            ROLE PARA VER
          </span>
        </div>
      </div>
    </section>
  );
}

window.NX = window.NX || {};
Object.assign(window.NX, { Conversion });
