/* Helix / 3D scroll-driven benefits section.
   Pure CSS 3D transforms — single scene element updates per scroll tick;
   cards & dashes have static transforms (cheap). */

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

const BENEFITS = [
  { num: "01", title: "Web za 24 hodín", desc: "Prvý draft do 24 hodín od briefu. Žiadne týždne čakania.", icon: "clock" },
  { num: "02", title: "Od 350€", desc: "Transparentný cenník bez skrytých poplatkov. Pevná cena, pevné slovo.", icon: "euro" },
  { num: "03", title: "Mobilná verzia", desc: "Dokonalý na každom zariadení — od mobilu po 4K displej.", icon: "device" },
  { num: "04", title: "SEO v cene", desc: "Google Analytics, Search Console, meta tagy a sitemapa.", icon: "seo" },
  { num: "05", title: "Hosting + doména", desc: "Všetko technické riešime za vás. Prvý rok zdarma.", icon: "server" },
  { num: "06", title: "Podpora každý deň", desc: "Jeden kontakt, vždy dostupní. Mailom či telefónom.", icon: "support" },
];

/* ─── Icons ─── */
const HelixIcon = ({ name }) => {
  const s = { width: "100%", height: "100%", fill: "none", stroke: "currentColor", strokeWidth: 1.2, strokeLinecap: "round", strokeLinejoin: "round" };
  switch (name) {
    case "clock":
      return (
        <svg viewBox="0 0 44 44" style={s}>
          <circle cx="22" cy="22" r="17" />
          <path d="M22 12v10l7 4" />
          <text x="22" y="40" textAnchor="middle" fontSize="6" fontFamily="var(--mono)" fill="currentColor" stroke="none" letterSpacing="0.5">24H</text>
        </svg>
      );
    case "euro":
      return (
        <svg viewBox="0 0 44 44" style={s}>
          <path d="M30 14a10 10 0 1 0 0 16" />
          <path d="M11 19h14M11 25h14" />
        </svg>
      );
    case "device":
      return (
        <svg viewBox="0 0 44 44" style={s}>
          <rect x="6" y="9" width="22" height="14" rx="1.5" />
          <rect x="28" y="14" width="11" height="20" rx="2" />
          <path d="M10 27h14" />
        </svg>
      );
    case "seo":
      return (
        <svg viewBox="0 0 44 44" style={s}>
          <circle cx="19" cy="19" r="10" />
          <path d="M27 27l8 8" />
          <path d="M14 22l3-4 3 3 4-6" />
        </svg>
      );
    case "server":
      return (
        <svg viewBox="0 0 44 44" style={s}>
          <rect x="8" y="10" width="28" height="8" rx="1.5" />
          <rect x="8" y="22" width="28" height="8" rx="1.5" />
          <circle cx="13" cy="14" r="1" fill="currentColor" stroke="none" />
          <circle cx="13" cy="26" r="1" fill="currentColor" stroke="none" />
          <path d="M18 14h12M18 26h12" opacity="0.4" />
        </svg>
      );
    case "support":
      return (
        <svg viewBox="0 0 44 44" style={s}>
          <path d="M9 24v-4a13 13 0 0 1 26 0v4" />
          <rect x="6" y="22" width="6" height="11" rx="2" />
          <rect x="32" y="22" width="6" height="11" rx="2" />
          <path d="M35 33v1a4 4 0 0 1-4 4h-5" />
        </svg>
      );
  }
};

/* ─── Card ─── */
const BenefitCard = ({ benefit, isActive }) => (
  <div style={{
    width: "100%", height: "100%", padding: 36, borderRadius: 24,
    background: isActive ? "rgba(22,16,10,0.97)" : "rgba(14,12,10,0.95)",
    border: isActive ? "1px solid rgba(255,107,53,0.55)" : "1px solid rgba(245,241,235,0.10)",
    boxShadow: isActive ? "0 0 60px -15px rgba(255,107,53,0.35)" : "none",
    transition: "border-color 500ms ease, box-shadow 500ms ease",
    display: "flex", flexDirection: "column", color: "var(--fg)",
  }}>
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 36 }}>
      <span style={{
        fontFamily: "var(--mono)", fontSize: 12, letterSpacing: 1.5,
        color: isActive ? "var(--accent)" : "var(--fg-mute)", transition: "color 500ms",
      }}>
        / {benefit.num}
      </span>
      <div style={{
        width: 44, height: 44, color: isActive ? "var(--accent)" : "var(--fg-dim)",
        transition: "color 500ms",
        filter: isActive ? "drop-shadow(0 0 12px rgba(255,107,53,0.6))" : "none",
      }}>
        <HelixIcon name={benefit.icon} />
      </div>
    </div>

    <h3 style={{
      fontFamily: "var(--serif)", fontSize: 46, fontWeight: 400,
      lineHeight: 1.02, letterSpacing: "-0.025em", marginBottom: 14,
    }}>
      {benefit.title}
    </h3>
    <p style={{ fontSize: 15.5, lineHeight: 1.55, color: "var(--fg-dim)" }}>{benefit.desc}</p>

    <div style={{
      marginTop: "auto", paddingTop: 20,
      borderTop: "1px solid rgba(245,241,235,0.08)",
      display: "flex", justifyContent: "space-between", alignItems: "center",
    }}>
      <span style={{ fontFamily: "var(--mono)", fontSize: 11, color: "var(--fg-mute)", letterSpacing: 1.5, textTransform: "uppercase" }}>
        Benefit · WA-{benefit.num}
      </span>
      <span style={{
        width: 8, height: 8, borderRadius: "50%",
        background: isActive ? "var(--accent)" : "rgba(245,241,235,0.18)",
        boxShadow: isActive ? "0 0 14px var(--accent)" : "none",
        transition: "background 400ms, box-shadow 400ms",
      }} />
    </div>
  </div>
);

/* ─── Progress dots ─── */
const ProgressDots = ({ count, activeIdx }) => (
  <div className="progress-dots" style={{
    position: "absolute", bottom: 60, left: "50%", transform: "translateX(-50%)",
    zIndex: 35, display: "flex", alignItems: "center", gap: 12,
    padding: "12px 20px", borderRadius: 999,
    border: "1px solid rgba(245,241,235,0.08)",
    background: "rgba(10,10,10,0.6)",
    backdropFilter: "blur(12px)", WebkitBackdropFilter: "blur(12px)",
  }}>
    <span style={{ fontFamily: "var(--mono)", fontSize: 10, color: "var(--fg-mute)", letterSpacing: 1.5, marginRight: 6 }}>
      0{activeIdx + 1}
    </span>
    {Array.from({ length: count }).map((_, i) => (
      <div key={i} style={{
        width: i === activeIdx ? 36 : 6,
        height: 6, borderRadius: 3,
        background: i === activeIdx ? "var(--accent)" : (i < activeIdx ? "rgba(255,107,53,0.4)" : "rgba(245,241,235,0.18)"),
        boxShadow: i === activeIdx ? "0 0 14px var(--accent)" : "none",
        transition: "all 600ms cubic-bezier(.2,.7,.2,1)",
      }} />
    ))}
    <span style={{ fontFamily: "var(--mono)", fontSize: 10, color: "var(--fg-mute)", letterSpacing: 1.5, marginLeft: 6 }}>
      06
    </span>
  </div>
);

/* ─── Main section ─── */
const HelixSection = () => {
  const trackRef = useRef(null);
  const sceneRef = useRef(null);
  const cardRefs = useRef([]);
  const progressRef = useRef(0);
  const [activeIdx, setActiveIdx] = useState(0);

  const RADIUS = 460;
  const Y_RANGE = 220;
  const ROT_RANGE = 300; // 5 * 60deg

  useEffect(() => {
    let rafId = null;

    const apply = () => {
      rafId = null;
      const p = progressRef.current;
      if (sceneRef.current) {
        // No CSS transition on this transform — rotation tracks scroll 1:1
        sceneRef.current.style.transform =
          `translateY(${(-p * Y_RANGE).toFixed(2)}px) rotateY(${(-p * ROT_RANGE).toFixed(2)}deg)`;
      }
      // Per-card opacity based on continuous distance from active
      const refs = cardRefs.current;
      for (let i = 0; i < refs.length; i++) {
        const el = refs[i];
        if (!el) continue;
        const tCard = i / 5;
        const dist = Math.abs(p - tCard);
        const op = Math.max(0.08, 1 - dist * 4.5);
        el.style.opacity = op.toFixed(3);
      }
      const newActive = Math.min(5, Math.max(0, Math.round(p * 5)));
      setActiveIdx((prev) => (prev !== newActive ? newActive : prev));
    };

    const onScroll = () => {
      if (!trackRef.current) return;
      const rect = trackRef.current.getBoundingClientRect();
      const progress = Math.max(0, Math.min(1, -rect.top / (trackRef.current.offsetHeight - window.innerHeight)));
      progressRef.current = progress;
      // Only schedule one rAF per frame; latest progress is read inside the callback
      if (rafId === null) {
        rafId = requestAnimationFrame(apply);
      }
    };

    onScroll();
    apply();
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll);
    return () => {
      if (rafId !== null) cancelAnimationFrame(rafId);
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("resize", onScroll);
    };
  }, []);

  /* Spiral dashes — two strands (DNA feel) */
  const strands = useMemo(() => {
    const N = 44;
    const A = [], B = [];
    for (let i = 0; i < N; i++) {
      const t = (i - 14) / (N - 28); // extend beyond card range so spiral fades at edges
      const y = t * Y_RANGE;
      const angle = t * ROT_RANGE;
      const fade = Math.max(0, 1 - Math.pow(Math.abs(t - 0.5) * 1.7, 2));
      A.push({ y, angle, fade, i });
      B.push({ y, angle: angle + 180, fade, i });
    }
    return { A, B };
  }, []);

  /* Floating particles — capped at 6 to avoid frame drops */
  const particles = useMemo(() => {
    const arr = [];
    for (let i = 0; i < 6; i++) {
      arr.push({
        x: 12 + Math.random() * 76,
        y: 10 + Math.random() * 80,
        size: 1.5 + Math.random() * 2,
        opacity: 0.12 + Math.random() * 0.28,
        delay: -Math.random() * 12,
        duration: 10 + Math.random() * 8,
        drift: (Math.random() - 0.5) * 30,
      });
    }
    return arr;
  }, []);

  return (
    <section ref={trackRef} data-screen-label="Helix Benefits" style={{
      position: "relative", height: "calc(100svh * 7)", background: "#0a0a0a",
    }}>
      <style>{`
        @keyframes helixDrift {
          0% { transform: translate(0, 0); opacity: var(--op, 0.2); }
          50% { opacity: calc(var(--op, 0.2) * 1.6); }
          100% { transform: translate(var(--dx, 10px), -30px); opacity: var(--op, 0.2); }
        }
        @keyframes helixPulse {
          0%, 100% { opacity: 0.35; }
          50% { opacity: 0.65; }
        }
      `}</style>

      <div style={{
        position: "sticky", top: 0, height: "100svh", overflow: "hidden",
      }}>
        {/* Vignette / center glow */}
        <div style={{
          position: "absolute", inset: 0, pointerEvents: "none",
          background: "radial-gradient(ellipse 700px 480px at 50% 50%, rgba(255,107,53,0.08), transparent 65%)",
        }} />
        {/* Vertical band lines */}
        <div style={{
          position: "absolute", inset: 0, pointerEvents: "none", opacity: 0.5,
          backgroundImage: "linear-gradient(90deg, transparent 0, transparent calc(50% - 1px), rgba(255,107,53,0.06) 50%, transparent calc(50% + 1px))",
        }} />

        {/* Top / bottom fades into surrounding sections */}
        <div style={{
          position: "absolute", top: 0, left: 0, right: 0, height: 200,
          background: "linear-gradient(180deg, #0a0a0a 0%, transparent 100%)",
          zIndex: 30, pointerEvents: "none",
        }} />
        <div style={{
          position: "absolute", bottom: 0, left: 0, right: 0, height: 260,
          background: "linear-gradient(0deg, #0a0a0a 0%, transparent 100%)",
          zIndex: 30, pointerEvents: "none",
        }} />

        {/* Particles */}
        <div style={{ position: "absolute", inset: 0, pointerEvents: "none", zIndex: 2 }}>
          {particles.map((p, i) => (
            <div key={i} style={{
              position: "absolute", left: `${p.x}%`, top: `${p.y}%`,
              width: p.size, height: p.size, borderRadius: "50%",
              background: "#f5f1eb",
              animation: `helixDrift ${p.duration}s ease-in-out ${p.delay}s infinite alternate`,
              "--op": p.opacity, "--dx": `${p.drift}px`,
            }} />
          ))}
        </div>

        {/* Ghost text (active title, very faint) */}
        <div style={{
          position: "absolute", inset: 0, pointerEvents: "none", zIndex: 3,
          display: "flex", alignItems: "center", justifyContent: "center", overflow: "hidden",
        }}>
          {BENEFITS.map((b, i) => (
            <div key={i} style={{
              position: "absolute",
              fontFamily: "var(--serif)", fontStyle: "italic", fontWeight: 400,
              fontSize: "clamp(180px, 24vw, 380px)", lineHeight: 0.85,
              letterSpacing: "-0.05em", color: "#f5f1eb",
              whiteSpace: "nowrap",
              opacity: i === activeIdx ? 0.035 : 0,
              transition: "opacity 900ms cubic-bezier(.2,.7,.2,1)",
            }}>
              {b.title}
            </div>
          ))}
        </div>

        {/* Section labels */}
        <div className="helix-labels" style={{
          position: "absolute", top: 60, left: 40, right: 40, zIndex: 25,
          display: "flex", justifyContent: "space-between", alignItems: "baseline",
        }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10, fontFamily: "var(--mono)", fontSize: 12, color: "var(--accent)", textTransform: "uppercase", letterSpacing: 1.5 }}>
            <span>[02·H]</span>
            <span style={{ width: 24, height: 1, background: "var(--accent)" }} />
            <span>Šesť dôvodov — Helix view</span>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 14, fontFamily: "var(--mono)", fontSize: 11, color: "var(--fg-mute)", letterSpacing: 1.5 }}>
            <span style={{ width: 6, height: 6, borderRadius: "50%", background: "var(--accent)", animation: "helixPulse 2s ease-in-out infinite" }} />
            <span>Scroll-driven · 60fps</span>
          </div>
        </div>

        {/* Title intro (top-left, fades after start) */}
        <div className="helix-intro-title" style={{
          position: "absolute", top: 120, left: 40, zIndex: 25,
          maxWidth: 360,
          opacity: 1 - Math.min(1, activeIdx > 0 ? 1 : 0),
          transition: "opacity 600ms",
        }}>
          <h2 style={{
            fontFamily: "var(--serif)", fontSize: 48, fontWeight: 400,
            lineHeight: 0.96, letterSpacing: "-0.025em",
            opacity: activeIdx === 0 ? 0.9 : 0,
            transition: "opacity 700ms",
          }}>
            Šesť <em style={{ fontStyle: "italic", color: "var(--accent)" }}>dôvodov</em>,<br />
            prečo si nás vybrať.
          </h2>
        </div>

        {/* 3D scene */}
        <div className="helix-perspective" style={{
          position: "absolute", inset: 0, zIndex: 10,
          perspective: "1600px", perspectiveOrigin: "50% 50%",
        }}>
          <div ref={sceneRef} style={{
            position: "absolute",
            left: "50%", top: "50%",
            width: 0, height: 0,
            transformStyle: "preserve-3d",
            transform: "translateY(0px) rotateY(0deg)",
            willChange: "transform",
          }}>
            {/* Helix strand A (orange) */}
            {strands.A.map((d) => (
              <div key={`a-${d.i}`} style={{
                position: "absolute", left: -3, top: -3,
                width: 6, height: 6, borderRadius: "50%",
                background: "#FF6B35",
                boxShadow: "0 0 6px #FF6B35, 0 0 14px rgba(255,107,53,0.5)",
                opacity: 0.55 * d.fade,
                transform: `translateY(${d.y}px) rotateY(${d.angle}deg) translateZ(${RADIUS}px)`,
              }} />
            ))}
            {/* Helix strand B (white/dim) */}
            {strands.B.map((d) => (
              <div key={`b-${d.i}`} style={{
                position: "absolute", left: -2, top: -2,
                width: 4, height: 4, borderRadius: "50%",
                background: "#f5f1eb",
                opacity: 0.22 * d.fade,
                transform: `translateY(${d.y}px) rotateY(${d.angle}deg) translateZ(${RADIUS}px)`,
              }} />
            ))}

            {/* Cards */}
            {BENEFITS.map((b, i) => {
              const t = i / 5;
              const cardY = t * Y_RANGE;
              const cardAngle = t * ROT_RANGE;
              return (
                <div key={i}
                  ref={(el) => (cardRefs.current[i] = el)}
                  style={{
                    position: "absolute",
                    left: -220, top: -150,
                    width: 440, height: 300,
                    transformStyle: "preserve-3d",
                    backfaceVisibility: "hidden",
                    WebkitBackfaceVisibility: "hidden",
                    willChange: "transform, opacity",
                    transform: `translateY(${cardY}px) rotateY(${cardAngle}deg) translateZ(${RADIUS}px)`,
                  }}>
                  <BenefitCard benefit={b} isActive={i === activeIdx} />
                </div>
              );
            })}
          </div>
        </div>

        {/* Progress dots */}
        <ProgressDots count={6} activeIdx={activeIdx} />
      </div>
    </section>
  );
};

Object.assign(window, { HelixSection });
