/* global React, ICONS, useScrollY, WordReveal, useMouseGlow, LightningBolt */
const { useEffect: useHeroEffect, useState: useHeroState, useRef: useHeroRef } = React;

function Hero() {
  const [stage, setStage] = useHeroState(0);
  const bgRef = useHeroRef(null);
  const gridRef = useHeroRef(null);
  const tracesRef = useHeroRef(null);
  const glowRef = useMouseGlow();
  const y = useScrollY();

  useHeroEffect(() => {
    const steps = [60, 280, 700, 1480, 1800];
    const timers = steps.map((t, i) => setTimeout(() => setStage(i + 1), t));
    return () => timers.forEach(clearTimeout);
  }, []);

  useHeroEffect(() => {
    if (bgRef.current) bgRef.current.style.transform = `translate3d(0, ${y * 0.32}px, 0)`;
    if (gridRef.current) gridRef.current.style.transform = `translate3d(0, ${y * 0.16}px, 0)`;
    if (tracesRef.current) tracesRef.current.style.transform = `translate3d(0, ${y * 0.08}px, 0)`;
  }, [y]);

  const visible = (i) => stage >= i;
  const on = (i) => (visible(i) ? "is-in" : "");

  return (
    <section
      id="top"
      ref={glowRef}
      style={{
        position: "relative",
        minHeight: "100vh",
        display: "flex",
        alignItems: "center",
        padding: "120px var(--pad-x) 80px",
        overflow: "hidden",
        isolation: "isolate",
        "--mx": 0.5,
        "--my": 0.4,
      }}
    >
      <HeroBackdrop bgRef={bgRef} gridRef={gridRef} tracesRef={tracesRef} />

      <div
        aria-hidden="true"
        style={{
          position: "absolute",
          inset: 0,
          zIndex: 1,
          pointerEvents: "none",
          background:
            "radial-gradient(380px circle at calc(var(--mx) * 100%) calc(var(--my) * 100%), rgba(94, 233, 242, 0.18), transparent 65%)",
          transition: "background 90ms linear",
        }}
      />

      <div
        aria-hidden="true"
        style={{
          position: "absolute",
          top: "12%",
          right: "8%",
          zIndex: 1,
          opacity: 0.7,
          animation: "lyn-bolt-float 6s ease-in-out infinite",
        }}
      >
        <LightningBolt delay={1200} color="#5EE9F2" />
      </div>
      <div
        aria-hidden="true"
        style={{
          position: "absolute",
          bottom: "18%",
          right: "22%",
          zIndex: 1,
          opacity: 0.4,
          transform: "scale(0.6) rotate(15deg)",
          animation: "lyn-bolt-float 8s ease-in-out infinite reverse",
        }}
      >
        <LightningBolt delay={1900} color="#F5B547" />
      </div>
      <style>{`
        @keyframes lyn-bolt-float {
          0%, 100% { transform: translateY(0) rotate(0); }
          50% { transform: translateY(-20px) rotate(3deg); }
        }
      `}</style>

      <div
        className="container"
        style={{
          position: "relative",
          zIndex: 2,
          display: "grid",
          gridTemplateColumns: "minmax(0, 1fr)",
          gap: 36,
        }}
      >
        <div className={"reveal reveal-left " + on(1)} style={{ transitionDelay: "0ms" }}>
          <span className="eyebrow">
            <span className="dash"></span>
            Eléctrica · Solar · Redes
          </span>
        </div>

        <h1 className="h-hero hero-title">
          <WordReveal text="Instalaciones eléctricas" play={visible(2)} baseDelay={0} step={70} />{" "}
          <br className="hero-br-mobile" aria-hidden="true" />
          <span className="hero-accent-wrap">
            <span className="hero-accent">
              <WordReveal text="profesionales" play={visible(2)} baseDelay={210} step={70} className="hero-accent-reveal" clip={false} />
            </span>
          </span>{" "}
          <WordReveal text="y reparaciones." play={visible(2)} baseDelay={350} step={70} />
        </h1>

        <p className={"lead reveal " + on(3)} style={{ transitionDelay: "0ms" }}>
          15 años de criterio técnico en instalaciones, redes y seguridad.
          Dos especialistas fundadores. Construido para durar.
        </p>

        <div
          className={"reveal " + on(4)}
          style={{
            transitionDelay: "60ms",
            display: "flex",
            gap: 14,
            flexWrap: "wrap",
            marginTop: 8,
          }}
        >
          <a href="tel:+34634707655" className="btn btn-primary btn-lg btn-shine">
            <span style={{ width: 16, height: 16, display: "inline-flex" }}>{ICONS.phone}</span>
            Llamar ahora
          </a>
          <a href="#servicios" className="btn btn-ghost btn-lg">
            Ver servicios
            <span style={{ width: 18, height: 18, display: "inline-flex" }}>{ICONS.arrow}</span>
          </a>
        </div>

        {/* Stats strip */}
        <div
          className={"reveal " + on(5)}
          style={{
            transitionDelay: "120ms",
            marginTop: 56,
            display: "grid",
            gridTemplateColumns: "repeat(auto-fit, minmax(160px, 1fr))",
            gap: 1,
            background: "rgba(255,255,255,0.06)",
            border: "1px solid rgba(255,255,255,0.06)",
            borderRadius: 14,
            overflow: "hidden",
            maxWidth: 760,
          }}
        >
          {[
            ["15+", "Años combinados"],
            ["6", "Líneas de servicio"],
            ["48h", "Tiempo de respuesta"],
            ["100%", "Certificado"],
          ].map(([n, l], i) => (
            <div
              key={l}
              style={{
                background: "rgba(10, 31, 56, 0.7)",
                padding: "20px 22px",
                position: "relative",
                overflow: "hidden",
              }}
            >
              <div
                style={{
                  fontFamily: "var(--font-mono)",
                  fontSize: 28,
                  letterSpacing: "-0.02em",
                  color: "var(--text)",
                  lineHeight: 1,
                }}
              >
                {n}
              </div>
              <div
                style={{
                  fontFamily: "var(--font-mono)",
                  fontSize: 11,
                  letterSpacing: "0.12em",
                  textTransform: "uppercase",
                  color: "var(--text-mute)",
                  marginTop: 8,
                }}
              >
                {l}
              </div>
              <div
                aria-hidden="true"
                style={{
                  position: "absolute",
                  bottom: 0,
                  left: 0,
                  width: "100%",
                  height: 2,
                  background: "var(--cyan)",
                  opacity: 0.35,
                  transformOrigin: "left",
                  transform: "scaleX(0)",
                  animation: visible(5)
                    ? `lyn-stat-bar 1.4s ease-out ${i * 200 + 400}ms forwards`
                    : "none",
                }}
              />
            </div>
          ))}
          <style>{`
            @keyframes lyn-stat-bar { to { transform: scaleX(1); } }
          `}</style>
        </div>
      </div>

      {/* Scroll indicator */}
      <div
        className={"reveal " + on(5)}
        style={{
          transitionDelay: "320ms",
          position: "absolute",
          bottom: 32,
          left: "50%",
          transform: "translateX(-50%)",
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
          gap: 10,
          zIndex: 3,
        }}
      >
        <span
          style={{
            fontFamily: "var(--font-mono)",
            fontSize: 10,
            letterSpacing: "0.18em",
            textTransform: "uppercase",
            color: "var(--text-mute)",
          }}
        >
          Scroll
        </span>
        <div
          style={{
            width: 1,
            height: 36,
            background: "linear-gradient(180deg, transparent, var(--cyan), transparent)",
            animation: "lyn-scroll 2.2s ease-in-out infinite",
          }}
        />
      </div>

      <style>{`
        @keyframes lyn-scroll {
          0%, 100% { transform: scaleY(0.4); opacity: 0.4; transform-origin: top; }
          50% { transform: scaleY(1); opacity: 1; transform-origin: top; }
        }
        .btn-shine { position: relative; overflow: hidden; }
        .btn-shine::after {
          content: "";
          position: absolute;
          top: 0; left: -120%;
          width: 60%; height: 100%;
          background: linear-gradient(90deg, transparent, rgba(255,255,255,0.5), transparent);
          transform: skewX(-20deg);
          animation: lyn-shine 4s ease-in-out infinite;
        }
        @keyframes lyn-shine {
          0%, 60% { left: -120%; }
          80%, 100% { left: 220%; }
        }
      `}</style>
    </section>
  );
}

function HeroBackdrop({ bgRef, gridRef, tracesRef }) {
  return (
    <>
      <div
        ref={bgRef}
        style={{
          position: "absolute",
          inset: "-20% -10% -10% -10%",
          zIndex: 0,
          background:
            "radial-gradient(60% 50% at 80% 30%, rgba(94, 233, 242, 0.18) 0%, transparent 60%), radial-gradient(50% 50% at 20% 80%, rgba(245, 181, 71, 0.10) 0%, transparent 60%), linear-gradient(180deg, #081729 0%, #0a1f38 60%, #050f1d 100%)",
        }}
      />

      <svg
        ref={gridRef}
        style={{ position: "absolute", inset: 0, zIndex: 1, width: "100%", height: "100%", opacity: 0.5 }}
        aria-hidden="true"
      >
        <defs>
          <pattern id="grid" width="64" height="64" patternUnits="userSpaceOnUse">
            <path d="M 64 0 L 0 0 0 64" fill="none" stroke="rgba(255,255,255,0.045)" strokeWidth="1" />
          </pattern>
          <radialGradient id="gridMask" cx="65%" cy="40%" r="70%">
            <stop offset="0%" stopColor="white" stopOpacity="0.9" />
            <stop offset="100%" stopColor="white" stopOpacity="0.1" />
          </radialGradient>
          <mask id="gridMaskApply">
            <rect width="100%" height="100%" fill="url(#gridMask)" />
          </mask>
        </defs>
        <rect width="100%" height="100%" fill="url(#grid)" mask="url(#gridMaskApply)" />
      </svg>

      <svg
        ref={tracesRef}
        style={{ position: "absolute", inset: 0, width: "100%", height: "100%", zIndex: 1, pointerEvents: "none" }}
        viewBox="0 0 1200 800"
        preserveAspectRatio="xMidYMid slice"
        aria-hidden="true"
      >
        <defs>
          <linearGradient id="trace" x1="0" y1="0" x2="1" y2="0">
            <stop offset="0%" stopColor="#5EE9F2" stopOpacity="0" />
            <stop offset="40%" stopColor="#5EE9F2" stopOpacity="0.8" />
            <stop offset="100%" stopColor="#F5B547" stopOpacity="0" />
          </linearGradient>
          <linearGradient id="trace2" x1="0" y1="0" x2="1" y2="0">
            <stop offset="0%" stopColor="#F5B547" stopOpacity="0" />
            <stop offset="60%" stopColor="#F5B547" stopOpacity="0.6" />
            <stop offset="100%" stopColor="#5EE9F2" stopOpacity="0" />
          </linearGradient>
        </defs>

        {[
          [180, 220], [380, 140], [620, 240], [820, 180], [1040, 280],
          [240, 540], [460, 480], [700, 580], [920, 520], [1100, 620],
        ].map(([cx, cy], i) => (
          <g key={i}>
            <circle cx={cx} cy={cy} r="3" fill="#5EE9F2" opacity="0.9">
              <animate attributeName="opacity" values="0.3;1;0.3" dur={`${2.4 + (i % 3) * 0.4}s`} repeatCount="indefinite" begin={`${i * 0.15}s`} />
            </circle>
            <circle cx={cx} cy={cy} r="10" fill="none" stroke="#5EE9F2" strokeWidth="0.6" opacity="0.3">
              <animate attributeName="r" values="10;18;10" dur="3s" repeatCount="indefinite" begin={`${i * 0.3}s`} />
              <animate attributeName="opacity" values="0.4;0;0.4" dur="3s" repeatCount="indefinite" begin={`${i * 0.3}s`} />
            </circle>
          </g>
        ))}

        <path d="M 180 220 L 380 140 L 620 240 L 820 180 L 1040 280" fill="none" stroke="url(#trace)" strokeWidth="1.2">
          <animate attributeName="stroke-dashoffset" values="0;-120" dur="6s" repeatCount="indefinite" />
        </path>
        <path d="M 180 220 L 380 140 L 620 240 L 820 180 L 1040 280" fill="none" stroke="#5EE9F2" strokeWidth="0.6" strokeDasharray="4 12" opacity="0.8">
          <animate attributeName="stroke-dashoffset" values="0;-32" dur="1.4s" repeatCount="indefinite" />
        </path>
        <path d="M 240 540 L 460 480 L 700 580 L 920 520 L 1100 620" fill="none" stroke="url(#trace2)" strokeWidth="1.2" />
        <path d="M 240 540 L 460 480 L 700 580 L 920 520 L 1100 620" fill="none" stroke="#F5B547" strokeWidth="0.5" strokeDasharray="4 14" opacity="0.7">
          <animate attributeName="stroke-dashoffset" values="0;36" dur="2s" repeatCount="indefinite" />
        </path>
        <path d="M 380 140 L 460 480" fill="none" stroke="#5EE9F2" strokeWidth="0.5" opacity="0.3" strokeDasharray="2 4" />
        <path d="M 820 180 L 920 520" fill="none" stroke="#F5B547" strokeWidth="0.5" opacity="0.3" strokeDasharray="2 4" />
      </svg>

      <div
        style={{
          position: "absolute",
          inset: 0,
          zIndex: 1,
          background: "linear-gradient(180deg, transparent 60%, rgba(5, 15, 29, 0.85) 100%)",
          pointerEvents: "none",
        }}
      />
    </>
  );
}

window.Hero = Hero;
